Ansible - Making Variables Optional

Ansible - Making Variables Optional
In: Ansible, Palo Alto, NetDevOps

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.

  - name: create aggregate interfaces
      provider: '{{ provider }}'
      template: 'test-firewall'
      if_name: "{{ }}"
      ip: "{{ item.ip_address | default(omit) }}"
      vsys: vsys1
      - name: ae1
      - name: ae2

When the playbook runs, it iterates over the loop. On the first iteration, if_name becomes ae1 and ip becomes 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': ''})
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

Written by
Suresh Vina
Tech enthusiast sharing Networking, Cloud & Automation insights. Join me in a welcoming space to learn & grow with simplicity and practicality.
More from Packetswitch
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to Packetswitch.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.