【问题标题】:Ansible: compose list of facts in jinja templateAnsible:在 jinja 模板中编写事实列表
【发布时间】:2015-08-19 06:46:26
【问题描述】:

我正在使用 Ansible 1.9.2 设置集群服务,需要配置一个 JSON 配置文件,其中包含要加入的集群服务器列表。

目前,我的工作如下。它会产生正确的(如果丑陋的)输出。

{
    ...
    "join": [
{% for host in groups['cluster'] %}
        "{{ hostvars[host]['ansible_default_ipv4']['address'] }}{% if not loop.last %}, {% endif %}
{% endfor %}
],
    ...
}

Ansible 是否可以创建特定主机事实的列表,或者 Jinja 可以动态组合列表?我希望我可以在我的模板中留下这样的东西:

{
    ...
    "join": {{ list_of_cluster_ips|to_nice_json }},
    ...
}

我在模板文件的顶部尝试了一些 Jinja 魔法来生成如下列表:

{% set list_of_cluster_ips = [] %}
{% for host in groups['cluster'] %}
    {% do list_of_cluster_ips.append(host) %}
{% endfor %}
{
    ...
    "join": {{ list_of_cluster_ips|to_nice_json }},
    ...
}

但 Ansible 不支持 Jinja 的 'do' 功能,并以 fatal: [cluster-1] => {'msg': "AnsibleError: file: <template>, line number: 3, error: Encountered unknown tag 'do'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.", 'failed': True} 失败。

有没有办法让 Ansible 生成可以在模板中使用的列表?

【问题讨论】:

标签: templates jinja2 ansible


【解决方案1】:

试试这个:

{%- set list_of_cluster_ips = [] %}
{%- for host in groups['cluster'] %}
    {%- if list_of_cluster_ips.append(hostvars[host]['ansible_default_ipv4']['address']) %}
    {%- endif %}
{%- endfor %}
{
    ...
    "join": {{ list_of_cluster_ips|to_nice_json }},
    ...
}

【讨论】:

  • 我猜减号应该以不同的方式放置。 {% if ... -%} {%- endif %} 非常适合我。虽然很遗憾 do 不被支持,所以这看起来像是一个 hack。
猜你喜欢
  • 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
相关资源
最近更新 更多