[英]ansible - create list of dict using jinja2
I need to create list of dicts using only jinja2 from an array input.我需要从数组输入中仅使用 jinja2 创建字典列表。
One key/value pair is static and always the same, the other changes value.一个键/值对是 static 并且始终相同,另一个更改值。
Input:输入:
targets: ["abc", "qwe", "def"]
I know that the server will always be xyz
.我知道服务器将永远是
xyz
。
Final最后
connections:
- { "target": "abc", "server": "xyz" }
- { "target": "qwe", "server": "xyz" }
- { "target": "def", "server": "xyz" }
I tried this:我试过这个:
"{{ dict(targets | zip_longest([], fillvalue='xyz')) }}"
But that just takes one for key and the other for value.但这只需要一个作为关键,另一个作为价值。
just use set_fact with the right loop:只需将 set_fact 与正确的循环一起使用:
- name: testplaybook jinja2
hosts: localhost
gather_facts: no
vars:
targets: ["abc", "qwe", "def"]
tasks:
- name: DEFINE VARIABLE SPINE
set_fact:
connections: "{{ connections | d([]) + [ {'target': item, 'server': _server} ] }}"
loop: "{{ targets }}"
vars:
_server: xyz
- name: display
debug:
var: connections
result:结果:
connections:
- server: xyz
target: abc
- server: xyz
target: qwe
- server: xyz
target: def
You were quite close.你非常接近。
But you'll need a product
rather than a zip_longest
to have the same element repeating for all the element of your targets
list.但是你需要一个
product
而不是一个zip_longest
来为你的targets
列表的所有元素重复相同的元素。
You were also missing a dict2items
to close the gap and have the resulting list out of your dictionary.您还缺少一个
dict2items
来缩小差距并将结果列表从您的字典中删除。
Which gives the task:这给出了任务:
- set_fact:
connections: >-
{{
dict(targets | product(['xyz']))
| dict2items(key_name='target', value_name='server')
}}
Given the playbook:鉴于剧本:
- hosts: localhost
gather_facts: no
tasks:
- set_fact:
connections: >-
{{
dict(targets | product(['xyz']))
| dict2items(key_name='target', value_name='server')
}}
vars:
targets:
- abc
- qwe
- def
- debug:
var: connections
This yields:这产生:
ok: [localhost] =>
connections:
- server: xyz
target: abc
- server: xyz
target: qwe
- server: xyz
target: def
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.