Ansible/Jinja:带有未定义语句的条件 [英] Ansible/Jinja: condition with an undefined statement

查看:49
本文介绍了Ansible/Jinja:带有未定义语句的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历所有主机并为组somegroup中未包含的主机生成配置文件:

I need to iterate over all hosts and generate config file for hosts that are not contained in group somegroup:

{% for host in groups.all if host not in groups['somegroup'] %}

但是如果某组不存在,它将失败("StrictUndefined"类型的参数不可迭代).

But if somegroup does not exist, it fails (argument of type 'StrictUndefined' is not iterable).

如何正确编写此代码以避免两个不同的循环:

How do I write this correctly to avoid two different for cycles:

{% if groups['somegroup'] is defined %}
{% for host in groups.all if host not in groups['somegroup'] %}
...
{% endfor %}
{% else %}
{% for host in groups.all %}
...
{% endfor %}
{% endif %}

推荐答案

我认为您正在寻找 default 过滤器:

I think you're looking for the default filter:

{% for host in groups.all if host not in groups['somegroup'] | default([]) %}

这篇关于Ansible/Jinja:带有未定义语句的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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