ansible

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

  • 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