16

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.

sorin
  • 161,544
  • 178
  • 535
  • 806
  • I was trying to get my head around why an existing ansible playbook was using `some.thing | default() or omit` instead of simply `some.thing | default( omit )` and ended up here. However, best as I can tell, ansible 7 appears to happily accept the latter incantation now. – cueedee Feb 14 '23 at 08:12

2 Answers2

22

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

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

The benefit here is that there are no additional parentheses.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
14

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.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193