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

问题描述

我试图对以下表达式使用省略:

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中使用省略并避免任何错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 18:42