Jinja: Iterate list to create array of yaml elemen

2019-04-15 17:56发布

问题:

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.

回答1:

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 }}"