Either/or tasks

Apologies if this is a FAQ, but I haven't found been able to find it anywhere.

I keep wanting a pattern where something happens if a variable is true and something positively doesn't happen if the variable is false (or unset). For example having a service running or not running. Is there any way to achieve this other than having pairs of tasks with inverted when clauses?

e.g:

- name: be sure openais is running and enabled
   service: name=openais state=running enabled=yes
   when: enable_service_address is defined and enable_service_address

- name: be sure openais is NOT running and NOT enabled
   service: name=openais state=stopped enabled=no
   when: enable_service_address is not defined or not enable_service_address

Or, as an other example, creating or removing a marker file (which seems to be further complicated by needing 'copy' for create and 'file' for remove):

- name: Set standalone marker file
   copy: content='' dest=/var/role-standalone
   when: '"standalone" in group_names'

- name: Unset standalone marker file
   file: path=/var/role-standalone state=absent
   when: '"standalone" not in group_names'

Jon.

not currently, what you have is what works.

Ta. At least I wasn't missing something obvious...

Jon.

Alternatively, something like this:

vars:
openais_enabled: "{% if enable_service_address is defined and enable_service_address %}yes{% else %}no{% endif %}

openais_running: "{% if enable_service_address is defined and enable_service_address %}running{% else %}stopped{% endif %}

and in tasks:

  • name: be sure openais is running and enabled
    service: name=openais state={{ openais_running }} enabled={{ openais_enabled }}

I’m not sure I really like that, as the conditional is a bit thick, though.

More so just sharing for completeness.

I like to use the ternary operator in cases like these (not as “thick” as the conditionals):

vars:
openais_enabled: “{{ ‘yes’ if enable_service_address is defined and enable_service_address else ‘no’ }}”

openais_running: “{{ ‘running’ if enable_service_address is defined and enable_service_address else ‘stopped’ }}”

Or, to avoid variables and have the logic all in the task definition:

  • name: be sure openais is running and enabled
    service:
    name: openais

state: “{{ ‘running’ if enable_service_address is defined and enable_service_address else ‘stopped’ }}”

enabled: “{{ ‘yes’ if enable_service_address is defined and enable_service_address else ‘no’ }}”

Cheers,
Christian