[英]Ansible/Jinja2 how to append key into list of dict
I would like to have dictionary defined in ansible like this 我想像这样在ansible中定义字典
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() }}"
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: 但是有些任务我想遍历每个键的列表,并将键附加为dict的另一个属性,因此我想根据此原始dict组合/创建新的dict,如下所示:
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
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? 有没有办法,我如何以ansible set_facts / jinja2表示法实现此目标,还是必须在python中为ansible编写自定义插件?
You can achieve this with set_fact
: 您可以使用
set_fact
实现此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 }}"
More details about this trick with set_fact
and with_
in this post . 关于这一招用更多细节
set_fact
和with_
在这篇文章 。
To fetch all domains, you can use json_query('*[].a')
. 要获取所有域,可以使用
json_query('*[].a')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.