Search code examples
ansiblejinja2ansible-2.x

How to use omit with Ansible and avoid any errors?


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.


Solution

  • Not super elegant, but 100% working solution to handle keys of possibly undefined parent dicts:

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

    This will give you omit if openstack_networks is defined but has no id key or if openstack_networks is undefined.