Arbitrary host name resolution in Ansible Arbitrary host name resolution in Ansible postgresql postgresql

Arbitrary host name resolution in Ansible


You can create a lookup plugin for this:

Ansible 1.x:

import ansible.utils as utilsimport ansible.errors as errorsimport socketclass LookupModule(object):    def __init__(self, basedir=None, **kwargs):        self.basedir = basedir    def run(self, terms, inject=None, **kwargs):        if not isinstance(terms, basestring):            raise errors.AnsibleError("ip lookup expects a string (hostname)")        return [socket.gethostbyname(terms)]

Ansible 2.x:

import ansible.utils as utilsimport ansible.errors as errorsfrom ansible.plugins.lookup import LookupBaseimport socketclass LookupModule(LookupBase):    def __init__(self, basedir=None, **kwargs):        self.basedir = basedir    def run(self, terms, variables=None, **kwargs):        hostname = terms[0]        if not isinstance(hostname, basestring):            raise errors.AnsibleError("ip lookup expects a string (hostname)")        return [socket.gethostbyname(hostname)]

Save this relative to your playbook as lookup_plugins/ip.py.

Then use it as {{ lookup('ip', 'www.google.com') }}


The lookup plugin udondan mentions is the "right" way to do this (though the API changes for 2.0, so be aware of what version you're targeting if you go that way). If you just want something quick and dirty though, the following should work:

- hosts: yourhosts  tasks:  - local_action: shell dig +short host-to-lookup-here.com    changed_when: false    register: dig_output  - set_fact:      looked_up_ips: "{{ dig_output.stdout_lines }}"  - debug: msg="found ip {{ item }}"    with_items: looked_up_ips

The fact looked_up_ips would then be a list of the mapped IPs accessible from a template or whatever you need to use it in...


For completeness' sake, apparently we've been shipping a dig lookup plugin in the box since around 1.9 that would wrap this up nicely (h/t Duncan Hutty):

https://github.com/ansible/ansible/blob/devel/lib/ansible/plugins/lookup/dig.py