How to use omit with Ansible and avoid any errors?

sorin picture sorin · Jan 18, 2017 · Viewed 8.7k times · Source

I tried to use omit with an expression like this:

id: "{{ openstack_networks.id | default(omit) }}"

But it seems that it keeps failing with an exception when openstack_networks variable is not defined.

What is the correct way to write this jinja2 filter?

I want to omit the parameter in case openstack_networks.id does not exists.

Answer

Interestingly enough, Ansible will take something that reads like plain English:

id: "{{ omit if openstack_networks.id is not defined or openstack_networks.id }}"

The benefit here is that there are no additional parentheses.