Ansible/Jinja2如何将键追加到dict列表中

Ansible/Jinja2如何将键追加到dict列表中,ansible,jinja2,Ansible,Jinja2,我想把字典定义成这样 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 } 有些任务我只需要

我想把字典定义成这样

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 }
有些任务我只需要在dict键上循环,这很好

- name: "just debug"
  debug: msg={{ item }}
  with_items: "{{ vhosts.keys() }}"
但有些任务我想迭代每个键的列表,并将该键附加为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 }
在某些任务中,我只需要获取顶级域:

domains:
  - example.com
  - example.org

有没有办法,我如何用ansible set\u facts/jinja2表示法实现这一点,或者我必须用python为ansible编写一个自定义插件?

您可以用
set\u facts
实现这一点:

---
- 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\u fact
with


要获取所有域,您可以使用
json\u查询('*[].a')

这太好了!谢谢Постоянно натыкаюсь на твои ответы)