ansible if else construct

danday74 picture danday74 · Feb 4, 2017 · Viewed 72.3k times · Source

Heres my if else Ansible logic ..

- name: Check certs exist
  stat: path=/etc/letsencrypt/live/{{ rootDomain }}/fullchain.pem
  register: st

- include: ./_common/check-certs-renewable.yaml
  when: st.stat.exists

- include: ./_common/create-certs.yaml
  when: not st.stat.exists

This code boils down to:

IF certs exist

renew certs

ELSE

create certs

END IF

Is this the correct approach or is there a better approach to the IF ELSE construct in ansible?

Answer

Willem van Ketwich picture Willem van Ketwich · Feb 4, 2017

What you have there should work and is one way of doing it.

Alternatively, you could use a Jinja query to reduce it to 2 tasks, such that:

 - name: Check certs exist
   stat: path=/etc/letsencrypt/live/{{ rootDomain }}/fullchain.pem
   register: st

- include: "{{ './_common/check-certs-renewable.yaml' if st.stat.exists else './_common/create-certs.yaml' }}"

However, it's more a matter of personal preference than anything else, and your way is more readable, so I would just stick with that IMHO.