Ansible - Making Variables Optional
By default, Ansible requires values for all variables in a templated expression. If a variable is not defined, it throws an error.
FAILED! => {"msg": "The task includes an option with an undefined variable.
However, there are situations where you want to make specific variables optional. For example, let's say you create multiple aggregate interfaces on the Palo Alto firewall via a single task and don't want to assign IP addresses to some of the interfaces.
To make a variable optional, you can set the default value to the special variable omit
as shown below.
tasks:
- name: create aggregate interfaces
panos_aggregate_interface:
provider: '{{ provider }}'
template: 'test-firewall'
if_name: "{{ item.name }}"
ip: "{{ item.ip_address | default(omit) }}"
vsys: vsys1
with_items:
- name: ae1
ip_address: 1.1.1.1/24
- name: ae2
When the playbook runs, it iterates over the loop. On the first iteration, if_name
becomes ae1
and ip
becomes 1.1.1.1/24
. On the second iteration, if_name
becomes ae2
and the second variable ip
gets ignored as it is not defined.
TASK [create aggregate interfaces] *******************************************************************************************************************************************
ok: [test-panorama-01] => (item={'name': 'ae1', 'ip_address': '1.1.1.1/24'})
ok: [test-panorama-01] => (item={'name': 'ae2'})
As you can see below, interface ae1
gets an IP whereas ae2
doesn't as we wanted.
You can learn more about Ansible filters here https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html