简体   繁体   中英

ansible/jinja2 how to get dict from list of merged dicts

I'm trying to get a dictionary from list of dictionaries, where: key - it is value of all merged dictionaries items; value - list of items name included into some item.

Another words I need to get dictionary of all roles (as keys) and name of item that has this role (as values).

Example data yaml:

hostgroups:
  - name: a-node
    roles:
      - aaa
      - bbb
      - ccc
      - ddd
      - eee

  - name: b-node
    roles:
      - ccc
      - ddd

  - name: c-node
    roles:
      - ccc
      - ddd
      - zzz

  - name: d-node
    roles:
      - ccc
      - ddd

I'd like to get file like:

aaa:
  a-node
bbb:
  b-node
ccc:
  a-node
  b-node
  c-node
  d-node
ddd:
  a-node
  b-node
  c-node
  d-node
eee:
  a-node
zzz:
  c-node

It is easy on python, but very difficult on ansible. How to do that?

Is this the code that you're looking for?

vars:
  hostgroups:
      ...
  role_groups: {}
tasks:
  - set_fact:
      role_list: "{{ hostgroups|json_query('[].roles')|flatten|unique }}"
  - set_fact:
      role_groups: "{{ role_groups|combine( { item: hostgroups|json_query(query) } ) }}"
    vars:
      query: "[?roles.contains(@, '{{ item }}')].name"
    loop: "{{ role_list  }}"

Thank to everybody for the reply, but I found solution:

- name: step 1
  set_fact:
    temp_1: "{{ temp_1|default([]) + [{'role': item.1, 'hostgroup': item.0.name }] }}"
  with_subelements:
    - "{{ hostgroups }}"
    - roles

- name: Debug 2
  check_mode: no
  blockinfile:
    dest: hosts
    marker: "# {mark} Auto block {{ item[0] }}"
    block: |
           [{{ item[0]}}]
           {% for i in item[1] %}
           {{ i.hostgroup }}
           {% endfor %}
  with_items:
    - "{{ temp_1 | groupby('role') | list  }}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM