29

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?

Community
  • 1
  • 1
danday74
  • 52,471
  • 49
  • 232
  • 283

3 Answers3

34

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.

Willem van Ketwich
  • 5,666
  • 7
  • 49
  • 57
8

What about the following:

condition_arg: >-
  {%- if ansible_distribution == 'Ubuntu' -%}
  'param for ubuntu'
  {%- elif ansible_distribution == 'Debian' -%}
  'params for debian'
  {%- else -%}
  'what else'
  {%- end -%}

Kind of if-else statement.. ? They have been used in some projects with Ansible. This form isn't available from the official docs but from an active thread on stackexchange.

Dmitriy Popov
  • 2,150
  • 3
  • 25
  • 34
TRicks43
  • 121
  • 1
  • 5
4

The following can be used if you want to search if a register is empty. The msg Unavailable is printed if php -version info is not found.If it is found, it prints the output of the command.

enter image description here

- name: Check php
  shell: php -version
  register: result

- name: Print register
  debug:
    msg: '{{ (result.stdout) | ternary( (result.stdout),"Unavailable") }}'
VMAtm
  • 27,943
  • 17
  • 79
  • 125
Shruthi Rajaram
  • 131
  • 1
  • 3