Red Cricket
Red Cricket

Reputation: 10480

How to avoid repeating when conditionals in ansible?

I have this playbook:

---
- name: Test
  hosts: localhost

  tasks:
    - name: Ansible grep pattern with ignore_errors example
      shell: "grep 'authorization' /tmp/junk.test"
      register: grep_output
      ignore_errors: true

    - name: Output debug grep_output
      debug:
        var: grep_output
        verbosity: 0
      shell: "echo 'Hello!'"
      when: grep_output.failed

When I run it I get this error:

ERROR! conflicting action statements: debug, shell

So I have to rewrite the playbook to look like this:

---
- name: Test
  hosts: localhost

  tasks:
    - name: Ansible grep pattern with ignore_errors example
      shell: "grep 'authorization' /tmp/junk.test"
      register: grep_output
      ignore_errors: true

    - name: Output debug grep_output
      debug:
        var: grep_output
        verbosity: 0
      when: grep_output.failed

    - name: Echo hello
      shell: "echo 'Hello!'"
      when: grep_output.failed

So I am repeating the when: grep_output.failed. Is there a better way of writing the above playbook?

Thanks

Upvotes: 1

Views: 282

Answers (1)

Alassane Ndiaye
Alassane Ndiaye

Reputation: 4787

You can use the block statement. It allows you to group modules and use a single when statement for the entire block. This should work:

---
- name: Test
  hosts: localhost

  tasks:
    - name: Ansible grep pattern with ignore_errors example
      shell: "grep 'authorization' /tmp/junk.test"
      register: grep_output
      ignore_errors: true

    - block:
      - name: Output debug grep_output
        debug:
          var: grep_output
          verbosity: 0

      - name: Echo hello
        shell: "echo 'Hello!'"
      when: grep_output.failed

Upvotes: 3

Related Questions