Improving code readability for Ansible conditionals
Improving readability when using the when conditional
The when condition is very commonly used in Ansible and gives playbook writers an if like conditional. It must be placed at the same level as the task name and the task itself.
The official documentation uses the example below.
tasks:
- name: Configure SELinux to start mysql on any port
ansible.posix.seboolean:
name: mysql_connect_any
state: true
persistent: true
when: ansible_selinux.status == "enabled"
I think we can improve the readability of this code by moving the when block as shown below.
tasks:
- name: Configure SELinux to start mysql on any port
when: ansible_selinux.status == "enabled"
ansible.posix.seboolean:
name: mysql_connect_any
state: true
persistent: true
This becomes exceptionally useful when evaluating code that uses block/rescue sections as shown below
tasks:
- name: End gracefully if software_ad_group is empty
block:
- name: Print debug info for AD add
ansible.builtin.debug:
msg:
- "No AD group specified, skipping AD group add"
when: software_ad_group is not defined or software_ad_group == ''
- name: If AD group exists, add user to group
block:
- name: Add Windows jump host
ansible.builtin.add_host:
hostname: "{{ windows_server }}"
ansible_host: "{{ windows_server }}"
ansible_port: "5986"
ansible_connection: winrm
ansible_winrm_transport: kerberos
ansible_password: "{{ password }}"
ansible_user: "{{ username }}@DOMAIN.com"
ansible_winrm_scheme: https
changed_when: false
register: host_add_results
when: software_ad_group != ''
The example above shows why it can be hard to follow longer blocks or tasks if they use a when conditional. The example below moves the when to just below the block keyword. This makes it much easier to follow and troubleshoot.
tasks:
- name: End gracefully if software_ad_group is empty
when: software_ad_group is not defined or software_ad_group == ''
block:
- name: Print debug info for AD add
ansible.builtin.debug:
msg:
- "No AD group specified, skipping AD group add"
- name: If AD group exists, add user to group
when: software_ad_group != ''
block:
- name: Add Windows jump host
ansible.builtin.add_host:
hostname: "{{ windows_server }}"
ansible_host: "{{ windows_server }}"
ansible_port: "5986"
ansible_connection: winrm
ansible_winrm_transport: kerberos
ansible_password: "{{ password }}"
ansible_user: "{{ username }}@DOMAIN.com"
ansible_winrm_scheme: https
changed_when: false
register: host_add_results
Thanks for reading. Feel free to reach out to me with questions or feedback.