首页 > 解决方案 > 迭代 Jinja 模板中的变量

问题描述

我想遍历 ansible yaml 中的变量并在 jinja 模板中添加键和值

多变的:

my:
    variable:
        - name: test
          path: /etc/apt
          cert: key.crt

我的模板

{% for key, value in item() %}
      {{key}}: {{value}}
{% endfor %}

ansible yaml

- name: test
  template:
    force: yes
    src: test.conf.j2
    dest: /tmp/test.conf"
  become: yes
  with_items:
    - "{{ my.variable }}"

我的 yaml 应该是什么样子:

path: /etc/apt
cert: key.crt

标签: templatesansiblejinja2

解决方案


您的任务中实际上存在三个问题:

  1. 使用循环时,可能是loopwith_*访问当前使用变量循环的元素的方式item,所以不是您在任务中使用的函数(item()

  2. 你正在做一个多余的列表列表

    with_items:
      - "{{ my.variable }}"
    

    第一步是做with_items: "{{ my.variable }}".
    一个更好的步骤是使用文档中建议的语法loop替换with_*

    我们loop在 Ansible 2.5 中添加。它还不能完全替代with_<lookup>,但我们建议在大多数用例中使用它。

    所以你最终会得到

    loop: "{{ my.variable }}"
    
  3. 然后在 Jinja 中访问字典的属性是使用语法完成的

    {% for key, value in dict.items() %}
    

    来源:https
    ://jinja.palletsprojects.com/en/2.11.x/templates/#for 所以在你的情况下:

    {% for key, value in item.items() %}
    

总之,证明这一点的有效剧本将是:

- hosts: all
  gather_facts: no
      
  tasks:
    - debug:
        msg: |
          {% for key, value in item.items() %}
            {{key}}: {{value}}
          {% endfor %}
      loop: "{{ my.variable }}"
      vars:
        my:
          variable:
            - name: test
              path: /etc/apt
              cert: key.crt

这产生了结果:

PLAY [all] *******************************************************************************************************

TASK [debug] *****************************************************************************************************
ok: [localhost] => (item={'name': 'test', 'path': '/etc/apt', 'cert': 'key.crt'}) => {
    "msg": "  name: test\n  path: /etc/apt\n  cert: key.crt\n"
}

PLAY RECAP *******************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

现在你只需要在你的模板和循环中重用它,你应该得到你所期望的。


推荐阅读