【问题标题】:Trouble passing Ansible dictionary to template将 Ansible 字典传递给模板时遇到问题
【发布时间】:2019-11-20 20:53:57
【问题描述】:

不知道是否有人可以在这里帮助我。

我在 host_vars 中有一个数组,因此我想将它传递到我的模板中。

network:
  igb0:
      - address: x.x.x.x
        netmask: 255.255.255.0
      - address: x.x.x.x
        netmask: 255.255.255.0
      - address: x.x.x.x
        netmask: 255.255.255.0

我正在尝试将它放在 vars 部分,但我无法确定它需要在任务的 vars 部分中采用什么格式。

vars:
    network: "{{ network }}"

在模板中添加以下内容:

{% for net in network %}
{% endfor %}

导致错误:

失败了! => {"changed": false, "msg": "AnsibleError: An unhandled exception occurred while templating '{{ network }}'. Error was a , original message: ...

提前感谢您的帮助。

【问题讨论】:

    标签: ansible


    【解决方案1】:

    使用dict2items 来“将字典变成项目列表,适合循环播放”。比如剧中

      vars:
        network:
          igb0:
            - address: x.x.x.x
              netmask: 255.255.255.0
            - address: y.y.y.y
              netmask: 255.255.255.0
            - address: z.z.z.z
              netmask: 255.255.255.0
      tasks:
        - template:
            src: test.j2
            dest: test.txt
    

    使用模板

    $ cat test.j2
    {% for ifc in network|dict2items %}
    {{ ifc.key }}
    {% for ip in ifc.value %}
    {{ ip.address }} {{ ip.netmask }}
    {% endfor %}
    {% endfor %}
    

    给予

    $ cat test.txt 
    igb0
    x.x.x.x 255.255.255.0
    y.y.y.y 255.255.255.0
    z.z.z.z 255.255.255.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 2018-07-26
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      相关资源
      最近更新 更多