Ansible/Jinja2如何将密钥附加到字典列表中

adr*_*ive 2 jinja2 ansible

我想在这样的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 }
Run Code Online (Sandbox Code Playgroud)

我需要在dict键上循环的一些任务,这很好

- name: "just debug"
  debug: msg={{ item }}
  with_items: "{{ vhosts.keys() }}"
Run Code Online (Sandbox Code Playgroud)

但是我想在每个键的列表中迭代一些任务,并将键作为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 }
Run Code Online (Sandbox Code Playgroud)

在某些任务中,我只需要获得顶级域名:

domains:
  - example.com
  - example.org
Run Code Online (Sandbox Code Playgroud)

有没有办法,我怎样才能在ansible set_facts/jinja2表示法中实现这一点,或者我是否必须在python中为ansible编写自定义插件?

Kon*_*rov 6

你可以用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 }}"
Run Code Online (Sandbox Code Playgroud)

关于这个技巧的更多细节set_fact以及with_这篇文章中.

要获取所有域,您可以使用json_query('*[].a').