miguel lara
miguel lara

Reputation: 11

how to add failed_when in ansible tower?

Im trying to add second rescue: in my ansible playbook but it only uses the last rescue for example: i wanted to run 3 diferent commands if one of them fails cmd: hostname fails_when: hostname=TEST rescue: cmd: hostname command v2 fails_when: hostname=TEST2 rescue: cmd: hostname final command fails_when: hostname=TEST

 --- 
- hosts: localhost
  connection: local
  gather_facts: no
  tasks:
     - block:
        - name: hostname start
          command: "hostname"
          register: hostname_start
          failed_when: '"HOSTNAMETEST" in hostname_start.stdout'

       rescue:
        - name: Rescue block V1 (perform recovery)
          command: "ip address"
          register: hostname_start
          failed_when: '"127.0.01" in hostname_start.stdout'

        - name: print hostname
          debug: var=hostname_start

       rescue:   
        - name: Rescue block (perform recovery) V2
          command: "hostname"
          register: hostname_start

        - name: print hostname
          debug: var=hostname_start

Upvotes: 1

Views: 147

Answers (1)

larsks
larsks

Reputation: 312263

I think you may of misunderstood my comment. This is what I am suggesting:

- hosts: localhost
  gather_facts: false
  tasks:
    - block:
        - name: hostname start
          command: "hostname"
          register: hostname_start
          failed_when: '"HOSTNAMETEST" in hostname_start.stdout'

      rescue:
        - name: Rescue block V1 (perform recovery)
          command: "ip address"
          register: hostname_start_1
          ignore_errors: true
          failed_when: >-
            "127.0.0.1" in hostname_start.stdout

        - name: Rescue block (perform recovery) V2
          when: hostname_start_1 is failed
          command: "hostname"
          register: hostname_start_2

        - set_fact:
            hostname_start: "{{ hostname_start_1 is failed|ternary(hostname_start_2.stdout, hostname_start_1.stdout) }}"

    - name: print hostname
      debug: var=hostname_start

If the first command task fails, Ansible will enter the rescue block. The second command will only run if the first command fails. The set_fact command picks the value from the successful command.

Upvotes: 1

Related Questions