如何在 Ansible 中使用 omit 并避免任何错误? [英] How to use omit with Ansible and avoid any errors?

查看:25
本文介绍了如何在 Ansible 中使用 omit 并避免任何错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将 omit 与这样的表达式一起使用:

I tried to use omit with an expression like this:

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

但是当 openstack_networks 变量未定义时,它似乎一直失败并出现异常.

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

编写这个 jinja2 过滤器的正确方法是什么?

What is the correct way to write this jinja2 filter?

如果 openstack_networks.id 不存在,我想省略该参数.

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

推荐答案

不是超级优雅,但 100% 工作解决方案来处理可能未定义的父字典的键:

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

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

如果 openstack_networks 已定义但没有 id 键,或者 openstack_networks 未定义,这将为您提供 omit.

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

这篇关于如何在 Ansible 中使用 omit 并避免任何错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆