Ansible/Jinja: condition with an undefined stateme

2019-06-06 17:33发布

问题:

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'] %}

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 %}

回答1:

I think you're looking for the default filter:

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