Using default jinja values in Ansible playbooks
Have you ever had a fact that you set earlier in the playbook that can occasionally be empty? If you have, then you know it can sometimes derail tasks later in the playbook.
Luckily jinja offers a default filter that can be used to set a particular value.
Let’s look at an example and how it can be improved by using a default filter. In the example we’re checking to see if there is an IP address before kicking off some node removal tasks in SolarWinds. Note: I’m using my naming scheme here that I use for any include_tasks actions. I’ll cover this in a future post.
- name: Remove_sw - Extract IP address using dig command
ansible.builtin.command: dig +short {{ solarwindshost }}
changed_when: false
register: extracted_ip_result
- name: Remove_sw - Set extracted IP address fact
ansible.builtin.set_fact:
extracted_ip: "{{ extracted_ip_result.stdout_lines | first }}"
- name: Remove_sw - Debug - Print SW IP
ansible.builtin.debug:
msg:
- "{{ extracted_ip }}"
Let’s take a look at this. It’s likely to have an issue because if any of the nodes targeted for removal no longer return an IP the debug statement and set_fact tasks could fail. Rather than add several block and rescue statements, it’s simpler to set a default value that can be filtered on later in the playbook.
Using the default filter is a small but powerful tool.
- name: Remove_sw - Extract IP address using dig command
ansible.builtin.command: dig +short {{ solarwindshost }}
changed_when: false
register: extracted_ip_result
- name: Remove_sw - Set extracted IP address fact
ansible.builtin.set_fact:
extracted_ip: "{{ extracted_ip_result.stdout_lines | first | default('No IP address found') }}"
- name: Remove_sw - Debug - Print SW IP
ansible.builtin.debug:
msg:
- "{{ extracted_ip }}"
This improvement will keep the code from failing or requiring additional error handling. Setting a default value allows us to easily filter using a when conditional later.
Thanks for reading. Feel free to reach out to me with questions or feedback.