Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ansible if else construct

Tags:

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?

like image 865
danday74 Avatar asked Feb 04 '17 07:02

danday74


People also ask

How do you write an if else condition 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.

What is Ansible Set_fact?

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.

Why is Ansible skipping tasks?

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.

Does Ansible do until loop?

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.


1 Answers

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.

like image 63
Willem van Ketwich Avatar answered Jan 02 '23 00:01

Willem van Ketwich