问题
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() }}"
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
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?
回答1:
You can achieve this with 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.
To fetch all domains, you can use json_query('*[].a')
.
来源:https://stackoverflow.com/questions/43202825/ansible-jinja2-how-to-append-key-into-list-of-dict