'Ansible when condition: only run the script if the command failed
I would like a bash script to run only if the command run into an error, yet I am not too familiar how to use the when condition, can someone please help?
gaiacli status
ERROR: Status: Post "http://localhost:26657": dial tcp 127.0.0.1:26657: connect: connection refused
- 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 |
Solution 1:[1]
You want to do 2 things, so you have to split them into 2 separate tasks:
- name: Run the script
command: gaiacli status
failed_when: false
register: gaia_status
changed_when: false
- name: Init when script fails
become: true
shell: sh init.sh # you can also use the command module
when: gaia_status.rc != 0
Solution 2:[2]
Ansible's 'when' command is more or less like your everyday conditional operator, just a little more concise.
Let's take this example from the official documentation of 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
On the first task, Ansible executes a shell command using it's command module, and registers it's output in a variable called result.
Right after that, you can see the next task using result and checking it with when. Interestingly, skipped/succeeded/failed are official keywords.
You can use a similar approach on your piece of code. An alternate approach would be to generate a variable on failure from the bash command, register it to Ansible and then use it in when, like in the example below.
- 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
Let me know if it helps, or if you'd like additional assistance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lester |
Solution 2 | 4wk_ |