How to use omit with Ansible and avoid any errors?

守給你的承諾、 提交于 2019-12-09 00:43:04

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/41725555/how-to-use-omit-with-ansible-and-avoid-any-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!