为ansible模板

时间:2016-06-17 11:33:48

标签: ansible jinja2 ansible-template

Ansible模板中的Jinja2允许在模板中使用这种类型的表达式:

{% if foobar is defined %} foo_bar = {{foobar}} {% endif %}
{% if barfoo is defined %} bar_foo = {{barfoo}} {% endif %}

是否有更短的版本说'如果未定义其变量,请不要打印此行?

foo_bar = {{foobar | skip_this_line_if_undefined}}之类的东西?

2 个答案:

答案 0 :(得分:0)

您可以使用default(omit)过滤器。有关详细信息,请查看documentation

答案 1 :(得分:0)

You could use a macro.

{% macro line(key, value) -%}
    {% if not value|none  %}{{ key }} = {{ value }}{% endif %}
{%- endmacro %}

Then just call the macro for every key/value pair.

{{ line('foo_bar', foobar) }}
{{ line('bar_foo', barfoo) }}

Could be problematic in edge cases though. If foobar or barfoo are not defined it probably will raise an error. In the macro, value in any case would be defined, so the condition is defined doesn't make sense any more. But if null/none actually is a valid value for any of the variables, you hit the wall...

A bit longer but probably water proof:

{% macro line(key, value) -%}
    {% if value != omit  %}{{ key }} = {{ value }}{% endif %}
{%- endmacro %}

{{ line('foo_bar', foobar|default(omit)) }}
{{ line('bar_foo', barfoo|default(omit)) }}