Sample Header Ad - 728x90

Ansible convert dictionary to mix of dictionary/array

1 vote
1 answer
3904 views
I use following files: variable file: db.yml
x86_64:  
  alpine:
    version: 3.15.0
  debian:
    version: 11.3.0

aarch64:
  alpine:
    version: 3.15.0
  debian:
    version: 11.3.0
playbook: playbook.yml
---
- name: "Playbook" 
  hosts: localhost
  connection: local
  gather_facts: no

  tasks:
  - name: Import variables
    ansible.builtin.include_vars:
      file: db.yml
      name: db

  - name: DENUG >>> db
    debug:
      var: db


  - name: DENUG >>> db
    debug:
      var: db[item].alpine
    loop: "{{ db.keys()|list }}"
    when: db[item].alpine is defined
Output:
ok: [localhost] => (item=x86_64) => {
    "ansible_loop_var": "item",
    "db[item].alpine": {
        "version": "3.15.0"
    },
    "item": "x86_64"
}
ok: [localhost] => (item=aarch64) => {
    "ansible_loop_var": "item",
    "db[item].alpine": {
        "version": "3.15.0"
    },
    "item": "aarch64"
}
Now I have converted db.yml to new style as following:
x86_64:
  - distribution: alpine
    version: 3.15.0
  - distribution: debian
    version: 11.3.0

aarch64:
  - distribution: alpine
    version: 3.15.0
  - distribution: debian
    version: 11.3.0
Question:
How to run similar command as following:
- name: DENUG >>> db
    debug:
      var: db[item].alpine
    loop: "{{ db.keys()|list }}"
    when: db[item].alpine is defined
and get the same result as available in the output.
Basically how to loop through this new db.yml to get value for db.x86_64.alpine.version
Asked by Rafal Niznik (333 rep)
Apr 19, 2022, 01:25 PM
Last activity: Apr 19, 2022, 11:08 PM