【问题标题】:How to use jinja2 loop index in ansible hostvars?如何在 ansible hostvars 中使用 jinja2 循环索引?
【发布时间】:2020-08-31 09:01:07
【问题描述】:

我正在尝试使用 hostvars 中的 jinja2 循环索引从库存中获取 ip 地址(来自 ansible):

库存是这样的:

all:
  hosts:
    host1:
      ansible_host: 192.168.1.1
    host2:
      ansible_host: 192.168.1.2
    host3:
      ansible_host: 192.168.1.3
    service_nodes:
      hosts:
        host1:
        host2:
        host3:

Template.yml 是这样的:

...
{% for host in service_nodes %}
  - {{ loop.index }}:{{ hostvars[groups.service_nodes[{{ loop.index }}]].ansible_host }}
...
{% endfor %}
...

我运行了剧本但遇到:{"changed": false, "msg": "AnsibleError: template error while templating string: expected token ':', got '}'. 检查了AnsibleError: template error while templating string: expected token 'end of statement block', got '{',但似乎这不是我的答案。

另外,我在模板上尝试了这些但失败了:

{% set idx = loop.index %}
  - {{ loop.index }}:{{ hostvars[groups.service_nodes[{{ idx }}]].ansible_host }}

  - {{ loop.index }}:{{ hostvars[groups.service_nodes["{{ loop.index }}"]].ansible_host }}

【问题讨论】:

    标签: ansible jinja2


    【解决方案1】:

    使用指令children 声明group of hosts service_nodes

    shell> cat hosts
    all:
      hosts:
        host1:
          ansible_host: 192.168.1.1
        host2:
          ansible_host: 192.168.1.2
        host3:
          ansible_host: 192.168.1.3
      children:
        service_nodes:
          hosts:
            host1:
            host2:
            host3:
    

    测试一下。查看命令的输出

    shell> ansible-inventory -i hosts --list
    

    然后是下面的剧本

    shell> cat playbook.yml
    - hosts: all
      tasks:
        - template:
            src: template.yml
            dest: hosts.txt
          delegate_to: localhost
          run_once: true
    

    和模板

    shell> cat template.yml 
    {% for host in groups.service_nodes %}
      - {{ loop.index }}:{{ hostvars[host]['ansible_host'] }}
    {% endfor %}
    

    shell> cat hosts.txt
      - 1:192.168.1.1
      - 2:192.168.1.2
      - 3:192.168.1.3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多