Ansible/Jinja2 how to append key into list of dict

蹲街弑〆低调 提交于 2021-02-07 09:13:03

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!