Home > Back-end >  Scrolling through a list with sublist in Ansible
Scrolling through a list with sublist in Ansible

Time:09-24

I need to simultaneously traverse a data structure to align the values, I get this structure with the code below :

- name: Set instances
  set_fact:
    instance_db:
      - 'db2inst1'
      - 'db2inst2'

- name: Get Dialog Path
  shell: db2 get dbm cfg | grep -i "Current member resolved DIAGPATH" | awk {'print $6'}
  become: true
  become_method: sudo
  become_flags: -i
  become_user: "{{ item }}"
  loop: "{{ instance_db }}"
  register: kud_path

- name: set_fact
  set_fact:
    db2_store: "[{{ instance_db | list }}]   [{{ kud_path.results|map(attribute='stdout')|list }}]"
  vars:
    db2_store: []

Result

{
    "changed": false,
    "ansible_facts": {
        "db2_store": [
            "db2inst1",
            "db2inst2",
            [
                "/db2home/db2inst1/sqllib/db2dump/DIAG0000/",
                "/home/db2inst2/sqllib/db2dump/DIAG0000/"
            ]
        ]
    },
    "_ansible_no_log": false
}

Now I need to automatically traverse these indexes where I put [*]. Because as it is, I can only access the data like this item[0][1]

- name: Creating silent config
  template:
    src: template.txt.j2
    dest: '/tmp/template{{ item[0][*] | lower }}.txt'
    mode: '0775'
  loop:
    - "{{ db2_store }}"

This workaround was necessary to be able to pass both values to the template

Template

################## Database connection config ##################
INSTANCE={{ item[0][*] }}
DIAGLOG_PATH={{ item[1][*] }}db2diag.log

Any suggestions on how to do this or a more elegant way to get the same result?

CodePudding user response:

Assuming the following:

instance_db = ["db2inst1", "db2inst2"]
kud_path.results|map(attribute='stdout')|list = ["/db2home/db2inst1/sqllib/db2dump/DIAG0000/", "/home/db2inst2/sqllib/db2dump/DIAG0000/"]

Then you can use the zip filter which will pair the Nth element of the first list with the Nth element of the second list.

- debug:
    msg: "{{ instance_db | zip(kud_path.results|map(attribute='stdout')|list) }}"

Outputs:

TASK [debug] ********************************************************************
ok: [localhost] => {
    "msg": [
        [
            "db2inst1",
            "/db2home/db2inst1/sqllib/db2dump/DIAG0000/"
        ],
        [
            "db2inst2",
            "/home/db2inst2/sqllib/db2dump/DIAG0000/"
        ]
    ]
}

This makes it easy for you to loop over:

- name: Creating silent config
  template:
    src: template.txt.j2
    dest: '/tmp/template{{ item[0] | lower }}.txt'
    mode: '0775'
  loop: "{{ instance_db | zip(kud_path.results|map(attribute='stdout')|list) }}"
################## Database connection config ##################
INSTANCE={{ item[0] }}
DIAGLOG_PATH={{ item[1] }}db2diag.log
  • Related