Unable to parse through elements of dict and array in Ansible

Viewed 29

I have a yaml file and I would like to go through each of the element in the below yaml file using Ansible.

Can someone help me here?

---
hardwares:
- VM.Standard2.1:
  - Oracle Linux:
    - '7.9'
    - '8'
    CentOS:
    - '8'
    Canonical Ubuntu:
    - '20.04'
- VM.Standard.E4.Flex:
  - Oracle Linux:
    - '7.9'
    - '8'
    CentOS:
    - '8'
    Canonical Ubuntu:
    - '20.04'
- VM.Standard.E3.Flex:
  - Oracle Linux:
    - '7.9'
    - '8'
    CentOS:
    - '8'
    Canonical Ubuntu:
    - '20.04'
- VM.Standard.A1.Flex:
  - Oracle Linux:
    - '7.9'
    - '8'
    Canonical Ubuntu:
    - '20.04'
1 Answers

The design of the structure is wrong. Either use a dictionary

    Oracle Linux:
      - '7.9'
      - '8'
    CentOS:
      - '8'
    Canonical Ubuntu:
      - '20.04'

or a list

  - Oracle Linux:
      - '7.9'
      - '8'
  - CentOS:
      - '8'
  - Canonical Ubuntu:
      - '20.04'

Let's use dictionaries in the example below

    hardwares:
      VM.Standard2.1:
        Oracle Linux:
          - '7.9'
          - '8'
        CentOS:
          - '8'
        Canonical Ubuntu:
          - '20.04'
      VM.Standard.E4.Flex:
        Oracle Linux:
          - '7.9'
          - '8'
        CentOS:
          - '8'
        Canonical Ubuntu:
          - '20.04'
      VM.Standard.E3.Flex:
        Oracle Linux:
          - '7.9'
          - '8'
        CentOS:
          - '8'
        Canonical Ubuntu:
          - '20.04'
      VM.Standard.A1.Flex:
        Oracle Linux:
          - '7.9'
          - '8'
        Canonical Ubuntu:
          - '20.04'

Create a file

shell> cat loop_outer_item.yml
- debug:
    msg: "{{ outer_item.key }} {{ item.0.key }} {{ item.1 }}"
  with_subelements:
    - "{{ outer_item.value|dict2items }}"
    - value

and include it in the loop

    - include_tasks: loop_outer_item.yml
      loop: "{{ hardwares|dict2items }}"
      loop_control:
        loop_var: outer_item

gives (abridged)

  msg: VM.Standard2.1 Oracle Linux 7.9
  msg: VM.Standard2.1 Oracle Linux 8
  msg: VM.Standard2.1 CentOS 8
  msg: VM.Standard2.1 Canonical Ubuntu 20.04
  msg: VM.Standard.E4.Flex Oracle Linux 7.9
  msg: VM.Standard.E4.Flex Oracle Linux 8
  msg: VM.Standard.E4.Flex CentOS 8
  msg: VM.Standard.E4.Flex Canonical Ubuntu 20.04
  msg: VM.Standard.E3.Flex Oracle Linux 7.9
  msg: VM.Standard.E3.Flex Oracle Linux 8
  msg: VM.Standard.E3.Flex CentOS 8
  msg: VM.Standard.E3.Flex Canonical Ubuntu 20.04
  msg: VM.Standard.A1.Flex Oracle Linux 7.9
  msg: VM.Standard.A1.Flex Oracle Linux 8
  msg: VM.Standard.A1.Flex Canonical Ubuntu 20.04
Related