【问题标题】:Use an ansible fact in an if conditional - Jinja template在 if 条件中使用 ansible 事实 - Jinja 模板
【发布时间】:2021-08-12 12:44:43
【问题描述】:

目前我的 Ansible Jinja 模板中有以下内容

{% for key in filebeat.values() %}
{% for x in key.servers %}
{% if x in {{ ansible_hostname }} %}
text-goes-here
{% endif %}
{% endfor %}
{% endfor %}

执行 ansible playbook 时,显示以下错误:

AnsibleError: 模板化字符串时出现模板错误:预期标记 ':', got '}

似乎在 Jinja 中,我无法在 if 语句中使用 {{ ansible_hostname }}

有没有什么方法可以让我在 if 语句中获取 ansible_hostname 的值来解决这个问题?我尝试过使用查找和其他组合,但到目前为止没有运气。

提前致谢

【问题讨论】:

    标签: python linux ansible jinja2 ansible-template


    【解决方案1】:

    您永远不会嵌套 Jinja {{...}} 模板标记。如果您已经在模板上下文中,则可以按名称引用变量...

    {% if x in ansible_hostname %}
    text-goes-here
    {% endif %}
    

    您已经在 {% for ... %} 循环中使用了完全正确的语法。你写道:

    {% for key in filebeat.values() %}
    

    代替:

    {% for key in {{ filebeat.values() }} %}
    

    {% if ... %} 语句也不例外。

    【讨论】:

    • 如果我在我的 vars.yaml 文件中使用静态值定义 ansible_hostname ,这种方法似乎确实有效。我的想法是获取通过 Ansible 事实提供的 ansible_hostname 的动态值。当我尝试使用 {% if x in ansible_hostname %} 而没有在 vars.yaml 中定义 ansible_hostname 时,它​​不起作用。
    • 谢谢你,设法让它与你建议的方法一起工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多