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?
Traditional programming language usually uses the if-else statement when more than one outcome is expected. In Ansible, 'when' statement is used instead to determine the outcome of a variable. So instead of using the if-else statement, you define what you want to happen.
In Ansible, we have various modules that work with variables and are used to get or set variable values. One such important module is set_fact. This module is used to set new variables. These variables are set on a host-by-host basis which is just like ansible facts, discovered by setup module.
Ansible runs or skips all tasks with tags that match the tags you pass at the command line. If you have added a tag at the block or play level, with roles , or with an import, that tag applies to every task within the block, play, role, or imported role or file.
To use this loop in task you essentially need to add 3 arguments to your task arguments: until - condition that must be met for loop to stop. That is Ansible will continue executing the task until expression used here evaluates to true. retry - specifies how many times we want to run the task before Ansible gives up.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With