Ansible/Jinja2如何将密钥附加到字典列表中 [英] Ansible/Jinja2 how to append key into list of dict
问题描述
我想像这样在ansible中定义字典
I would like to have dictionary defined in ansible like this
vhosts:
git_branch_1:
- { a: example.com, customer: a }
- { a: example.com, customer: b }
- { a: example.org, customer: a }
git_branch_2:
- { a: example.com, customer: x }
- { a: example.org, customer: y }
有些任务我只需要在字典键上循环,就可以了
Some tasks I need to loop only over dict keys, this works fine
- name: "just debug"
debug: msg={{ item }}
with_items: "{{ vhosts.keys() }}"
但是有些任务我想遍历每个键的列表,并将键作为dict的另一个属性附加,所以我想从这个原始dict组合/创建新的dict,如下所示:>
But some tasks I would like to iterate over list from each key, and append the key as another property of dict, so I would like to combine/create new dict from this original dict, that will look like this:
combined_vhosts:
- { a: example.com, customer: a, branch: git_branch_1 }
- { a: example.com, customer: b, branch: git_branch_1 }
...
- { a: example.com, customer: x, branch: git_branch_2 }
在某些任务中,我只需要获取顶级域:
And in some tasks I just need to get only the top level domain:
domains:
- example.com
- example.org
有没有办法,如何以ansible set_facts/jinja2表示法实现此功能,还是必须在python中为ansible编写自定义插件?
Is there a way, how can I achive this in ansible set_facts / jinja2 notation or do I have to write a custom plugin for ansible in python?
推荐答案
您可以通过set_fact
来实现:
---
- hosts: localhost
gather_facts: no
vars:
vhosts:
git_branch_1:
- { a: example.com, customer: a }
- { a: example.com, customer: b }
- { a: example.org, customer: a }
git_branch_2:
- { a: example.com, customer: x }
- { a: example.org, customer: y }
tasks:
- set_fact:
tmp_vhosts: "{{ item.value | map('combine',dict(branch=item.key)) | list }}"
with_dict: "{{ vhosts }}"
register: combined_vhosts
- set_fact:
combined_vhosts: "{{ combined_vhosts.results | map(attribute='ansible_facts.tmp_vhosts') | sum(start=[]) }}"
- debug:
msg: "{{ combined_vhosts }}"
set_fact和with_
的技巧的更多详细信息>这篇文章.
More details about this trick with set_fact
and with_
in this post.
要获取所有域,可以使用json_query('*[].a')
.
To fetch all domains, you can use json_query('*[].a')
.
这篇关于Ansible/Jinja2如何将密钥附加到字典列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!