Jinja:迭代列表以创建 yaml 元素数组 [英] Jinja: Iterate list to create array of yaml elements

查看:19
本文介绍了Jinja:迭代列表以创建 yaml 元素数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 ansible playbook 中有以下变量

I have the following variable in ansible playbook

var1: "string"
variable:
  - name: "{{ var1 }}-xxx"
    sshKey: "{{ lookup('file', 'temp/xxx.pub') }}"
  - name: "{{ var1 }}-yyy"
    sshKey: "{{ lookup('file', 'temp/yyy.pub') }}"
  - name: "{{ var1 }}-zzz"
    sshKey: "{{ lookup('file', 'temp/zzz.pub') }}"

这显然需要循环.然而,我尝试创建一个循环是徒劳的.

which, obviously begs for a loop. however, my attemps at creating a loop were futile.

list: [ 'zzz', 'xxx', 'yyy' ]
loop: [
{% for item in list %}
- name: "{{ item }}"
  sshKey: "{{ lookup('file', 'temp/{{ item }}.tmp') }}"
{% endfor %}
]

有什么办法吗?我有点失落.

Any way to do this? I'm a bit lost.

推荐答案

据我所知,要使其正常工作,您应该将第二个 var 设计为 python-repr/JSON:

From my knowledge, for this to work, you should craft second var to be python-repr/JSON:

---
- hosts: localhost
  gather_facts: no
  vars:
    my_list: [aaa, bbb, ccc]
    my_loop: >
             [ {% for i in my_list %}
               {
                 'name':'prefix-{{ i }}',
                 'sshKey':'{{ lookup('file','/tmp/'+i) }}'
               }
               {% if not loop.last %},{% endif %}
               {% endfor %}
             ]
  tasks:
    - debug:
        msg: "{{ my_loop }}"

这篇关于Jinja:迭代列表以创建 yaml 元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆