ansible access list of dictionaries

15,024

I should have formatted the list of dictionaries differently. This is a duplicate question: Answer here: Ansible with_subelements

My vars should have looked like this:

groups_members:
  - groupname: FIRST_GROUP
    members:
      - name: memberx
        octet: "1"
        action: add
      - name: nostandardy
        octet: "3"
        action: add
      - name: memberz
        octet: "2"
        action: add
      - name: unexpected
        octet: "1"
        action: add
  - groupname: RHOST
    members:
      - member: other1
        octet: "1"
        action: add

Could then be accessed as item.1.action or item.0.value and task be with

    with_subelements:
  - "{{ groups_members }}"
  - members
Share:
15,024
Lasse A
Author by

Lasse A

Updated on June 04, 2022

Comments

  • Lasse A
    Lasse A almost 2 years

    I'm trying to create a bunch of groups and members for a custom module using an external var file. All I need to do is to access a list of dictionaries in a list. I have tried many things but the closest I might have for now is: vars.yml:

    groups_and_members:
      FIRST_GROUP:
        "memberx":
          octet: 1
          action: add
        "nostandardy":
          octet: 3
          action: add
        "memberz":
          octet: 5
          action: add
      OTHER_GROUP:
        "member1":
          octet: 7
          action: delete
        "unexpected":
          octet: 1
          action: add
    

    task.yml:

      - name: "add members"
        mymodule:
          cmd: "{{ item.value.action }}"
          parameters:
            name: "{{ item.key }}"
            octet: "{{ item.value.octet }}"
        with_items: "{{ groups_and_members }}"
    

    So the idea is to take from the list (groups_and_members).value(FIRST_GROUP in the first iteration). and use its members attribute in cmd. But because I don't know the name of the group nor the name of the member, I'm not sure how to access them. I will not know the name of the groups or the members beforehand. The dicts should be in a list, to not have to make a new task in case there's a new dict. How can I access the group, member and member attributes? I have tried with_dict, with_subelements etc. but can't seem to figure it out.