gpt4 book ai didi

ansible-2.x - 如何将 grep 命令结果存储在 ansible 变量中?

转载 作者:行者123 更新时间:2023-12-04 09:14:06 25 4
gpt4 key购买 nike

我正在尝试根据 grep 命令返回的计数设置一个 Ansible 变量。

代码如下。

tasks:

- name: Check for 12.1 databases
shell: "grep -c /u1/app/oracle/product/12.1.0/dbhome_1 /etc/oratab"
register: grep_output

- name: Print
debug:
msg="grep_output.stdout"

- name: Set the variable
set_fact:
oracle_version_12_1_0: "true"
when: "grep_output.stdout > 0"

- name: Print variable
command: echo "{{ oracle_version_12_1_0 }}"

代码错误如下。

PLAY [oradbpoc1] ***********************************************************************************************************************************************

TASK [Gathering Facts] *********************************************************************************************************
ok: [oradbpoc1]

TASK [Check for 12.1 databases] *********************************************************************************************************
fatal: [oradbpoc1]: FAILED! => {"changed": true, "cmd": "grep -c /u1/app/oracle/product/12.1.0/dbhome_1 /etc/oratab", "delta": "0:00:00.003425", "end": "2020-08-06 18:33:04.476299", "msg": "non-zero return code", "rc": 1, "start": "2020-08-06 18:33:04.472874", "stderr": "", "stderr_lines": [], "stdout": "0", "stdout_lines": ["0"]}

PLAY RECAP *********************************************************************************************************
oradbpoc1 : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0

PS:另外,有没有办法为 oracle_version_12_1_0 变量分配一个默认值(“false”)?

谢谢

法国

最佳答案

关于失败条件,这是因为如果在文件中找不到 PATTERN,grep -c PATTERN FILE 将返回非零退出代码。

简单示例:

# grep -c root /etc/passwd; echo $?
2
0

# grep -c rootNO /etc/passwd; echo $?
0
1

所以,我认为有两种选择:

  1. 仅基于退出代码
  2. 设置忽略错误,并处理值

由于计数应该足够,这里显示选项 2:

- hosts: localhost
tasks:
- name: get value
shell:
cmd: grep -c root /etc/passwd
register: grep_output
ignore_errors: yes
changed_when: false

- name: Print
debug:
msg: "{{ inventory_hostname }}: '{{ grep_output.stdout }}'"

- name : Set the variable
set_fact:
oracle_version_12_1_0: "{% if grep_output.stdout == '0' %}false{% else %}true{% endif %}"

- name: Print
debug:
msg: "val: {{ oracle_version_12_1_0 }}

root 调整为 rootNo(例如)以查看 true/false 的区别。

此外,根据您的具体需要,也可以按照 get value 中的指示注册变量,然后在 when 检查中使用它(即避免设置变量):

- name : task name
...
when: grep_output.stdout != '0'

后一种方法是否有用取决于整体用例。

关于ansible-2.x - 如何将 grep 命令结果存储在 ansible 变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63292751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com