Search code examples
ansibleansible-inventoryansible-facts

Get IP from inventory which defined FQDN only


In the inventory file, I define FQDN values only. These domains point to the server IPs (used in DNS). I'd like to render the template file (Jinja) with the list of IPs. Do we have any solution?

Inventory file:

[example_instance]
example1.com
example2.com

Desired output of template file

address=10.10.10.10,10.10.10.11

Solution

  • You can use the dig lookup for that. But, mind that you also need the dnspython library installed on your controller for it to work.

    So, given the two tasks:

    - pip:
        name: dnspython
      delegate_to: localhost
      run_once: yes
    
    - debug:
        msg: "{{ lookup('dig', inventory_hostname) }}"
    

    This would give you two IPs in return, in your case:

    ok: [example1.com] => 
      msg: 10.10.10.10
    ok: [example2.com] => 
      msg: 10.10.10.11
    

    In order to get a list of IPs from Ansible facts, given that you are targeting the group example_instance in your playbook, simply do, in your template:

    address={{ hostvars
      | dict2items
      | selectattr('value.ansible_facts.default_ipv4', 'defined')
      | map(attribute='value.ansible_facts.default_ipv4.address')
      | join(',')
    }}