populating dictionary from lookup

41 views
Skip to first unread message

gregory....@gmail.com

unread,
Sep 29, 2022, 11:02:16 AM9/29/22
to Ansible Project
Hello
As a part of another project, I have written a playbook:

---
- hosts: localhost
  vars:
    tdict:
    zones:
      - example.com
      - example.org
      - example.net
    soafields:
      - nameserver
      - admin
      - serial
      - refresh
      - retry
      - expire
      - ttl
    soarecords_dict:
  tasks:
    - name: read soa record into dict
      set_fact:
        tdict: "{{ tdict | combine( {item : lookup('dig',item,'qtype=SOA')|split } )}}"
      loop:
        "{{ zones }}"

    - debug:
        msg: "{{ tdict.keys() | list }}"

    - set_fact:
        soarecords_dict: "{{ soarecords_dict | combine ({item : dict(soafields| zip(tdict[item]))}) }}"
      loop:
        "{{ tdict.keys() |list }}"

    - name: output soa records
      debug:
        var: soarecords_dict

this works, but if possible, I want to get rid of temporary tdict part, meaning that I will set soarecords_dict variable directly from oneliner. 

doable?

Vladimir Botka

unread,
Sep 29, 2022, 5:04:28 PM9/29/22
to gregory....@gmail.com, ansible...@googlegroups.com
Create it in Jinja. For example,

soarecords: |
{% for zone in zones %}
{{ zone }}:
{% for field in lookup('dig', zone, 'qtype=SOA')|split %}
{{ soafields[loop.index0] }}: {{ field }}
{% endfor %}
{% endfor %}
soarecords_dict: "{{ soarecords|from_yaml }}"

--
Vladimir Botka

Vladimir Botka

unread,
Sep 29, 2022, 5:18:16 PM9/29/22
to gregory....@gmail.com, ansible...@googlegroups.com
The next option is putting the iteration into one task. For example,

- set_fact:
soarecords_dict: "{{ soarecords_dict|d({})|
combine({item: _dict}) }}"
loop: "{{ zones }}"
vars:
_dict: "{{ dict(soafields|
zip(lookup('dig', item, 'qtype=SOA')|split)) }}"


--
Vladimir Botka

Gregory Edigarov

unread,
Sep 30, 2022, 5:18:11 AM9/30/22
to Vladimir Botka, ansible...@googlegroups.com
Thank you, Vladimir. I've completely forgotten that ansible allows vars to be defined for a single task.  
Reply all
Reply to author
Forward
0 new messages