Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a state conditionally?

Tags:

ansible

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
like image 256
WoJ Avatar asked Oct 29 '25 08:10

WoJ


1 Answers

You can do it like this:

state: "{{ 'present' if active == 'y' else 'absent' }}"
like image 147
Arbab Nazar Avatar answered Oct 31 '25 12:10

Arbab Nazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!