在Jinja模板中迭代变量

3
我想在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

1
"msg": "ValueError: 期望解包的值过多(应为2个)"} - sokolata
"msg": "数值错误:拆包的值过多(期望 2 个)"} - sokolata
1个回答

2

You actually have three issues in your task:

  1. When using a loop, may it be loop or all the flavour of with_* you access the element currently looped in with the variable item, so not a function like you used in your task (item())

  2. You are doing a superfluous list of list in

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

    A first step would be to do with_items: "{{ my.variable }}".
    An ever better step would be to use the loop replacement of the with_* syntax as suggested in the documentation

    We added loop in Ansible 2.5. It is not yet a full replacement for with_<lookup>, but we recommend it for most use cases.

    So you will end up with

    loop: "{{ my.variable }}"
    
  3. Then accessing properties of a dictionary in Jinja is done using the syntax

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

    Source: https://jinja.palletsprojects.com/en/2.11.x/templates/#for
    So in your case:

    {% 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   

现在,您只需要在模板中重用它并进行循环操作,就能得到您所期望的结果。请保留HTML标签。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接