WoJ
WoJ

Reputation: 30035

How to use a state conditionally?

I have in a playbook a blockinfile which should be present on not depending on the value of a previously set variable. The bruteforce solution is

  - name: shorewall rules
    blockinfile:
      dest: /etc/shorewall/rules
      state: present
      block: |
        # settings for machine {{ machine }}
        # outgoing internet
        ACCEPT {{ machine }} int
        # more here
      when: active == "y"

  - name: shorewall rules
    blockinfile:
      dest: /etc/shorewall/rules
      state: absent
      block: |
        # settings for machine {{ machine }}
        # outgoing internet
        ACCEPT {{ machine }} int
        # more here
      when: active == "n"

Is there a way to set a condition in state? Something along the lines of

state: present if active == "y" else absent

Upvotes: 4

Views: 2901

Answers (1)

Arbab Nazar
Arbab Nazar

Reputation: 23811

You can do it like this:

state: "{{ 'present' if active == 'y' else 'absent' }}"

Upvotes: 12

Related Questions