我希望 bash 脚本仅在命令遇到错误时运行,但我不太熟悉如何使用when条件,有人可以帮忙吗?
gaiacli status
ERROR: Status: Post "http://localhost:26657": dial tcp 127.0.0.1:26657: connect: connection refused
Run Code Online (Sandbox Code Playgroud)
- name: Run the script
command: gaiacli status
ignore_errors: yes
register: gaia_status
chaned_when: False
become: true
shell: sh init.sh
when: gaia_status|ERROR #not sure what to put in after |
Run Code Online (Sandbox Code Playgroud)
Ansible 的“when”命令或多或少类似于您日常的条件运算符,只是更简洁一些。
我们以Ansible官方文档中的这个例子为例。
tasks:
- name: Register a variable, ignore errors and continue
ansible.builtin.command: /bin/false
register: result
ignore_errors: true
- name: Run only if the task that registered the "result" variable fails
ansible.builtin.command: /bin/something
when: result is failed
- name: Run only if the task that registered the "result" variable succeeds
ansible.builtin.command: /bin/something_else
when: result is succeeded
- name: Run only if the task that registered the "result" variable is skipped
ansible.builtin.command: /bin/still/something_else
when: result is skipped
Run Code Online (Sandbox Code Playgroud)
在第一个任务中,Ansible 使用其命令模块执行 shell 命令,并将其输出注册在名为result的变量中。
之后,您可以使用结果查看下一个任务,并使用when进行检查。有趣的是,skipped/succeeded/failed是官方关键字。
您可以对您的代码使用类似的方法。另一种方法是在 bash 命令失败时生成一个变量,将其注册到 Ansible,然后在when中使用它,如下例所示。
- name: Test play
hosts: all
tasks:
- name: Register a variable
ansible.builtin.shell: cat /etc/motd
register: motd_contents
- name: Use the variable in conditional statement
ansible.builtin.shell: echo "motd contains the word hi"
when: motd_contents.stdout.find('hi') != -1
Run Code Online (Sandbox Code Playgroud)
如果有帮助,或者您是否需要其他帮助,请告诉我。