【问题标题】:Iterate over Variable in Jinja Template迭代 Jinja 模板中的变量
【发布时间】:2020-12-07 20:46:07
【问题描述】:

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

【问题讨论】:

  • "msg": "ValueError: 要解压的值太多(预期为 2)"}
  • same... "msg": "ValueError: too many values to unpack (expected 2)"}

标签: templates ansible jinja2


【解决方案1】:

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

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

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

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

    第一步是做with_items: "{{ my.variable }}"
    更好的方法是使用 loop 替换 with_* 语法 as suggested in the documentation

    我们在 Ansible 2.5 中添加了loop。它还不能完全替代 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   

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    相关资源
    最近更新 更多