'How to get domain zone of the DNS A record using Ansible dig

Basically I have a simple server name ( non FQDN ) and im trying to identify in which DNS zone it has A record
We have multiple DNS zones in our environment.

As i cant rely on PTR records im trying to use DIG module to look for a A record with zone name as variable. Once the A record is found, i want to use that zone name. Unfortunately im not able to put all the above together in ansible code

i've tried following

- name:
      set_fact: 
        found: "{{found+[ lookup('dig', ('{{ dns_name }}.{{item.1}}'), 'qtype=A' , flat=0)] }}"
        domain: "{{ item.0 }}"
        with_indexed_items:
        - zone1.com
        - zone2.com
        - zone3.com
ok: [xxxxxxxxxxxxxxxxxxxx] => {
    "found": [
        "10.10.10.10",
        "NXDOMAIN",
        "NXDOMAIN"]}

This generates the list of items but i dont know how to match these items with the list of zones or how to add the index into this list.

Any help would be very welcome



Solution 1:[1]

It's possible to create a dictionary instead of the list and select valid records with json_query. The play below gives the list of the zones with the valid record

- set_fact:
    found: "{{ found|default({})|
               combine({ item: {
                        'rec_a': lookup('dig',
                                        dns_name ~ '.' ~ item,
                                        'qtype=A',
                                        flat=0)}}) }}"
  loop: "{{ zones }}"
- set_fact:
    dns_domains: "{{ found|
                     dict2items|
                     json_query('[?value.rec_a != `NXDOMAIN`].key') }}"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vladimir Botka