Ansible - other host facts

Feb 4, 2015   #ansible 

Often in ansible it’s necessary to include information from other hosts (e.g. /etc/hosts). This is easy using the information from the magic variable section in the docs.

Unfortunately, something that is easy to forget is that ansible only knows information about hosts that it has connected to and run the setup module on (i.e. gather_facts: true). In other words, if you’re trying to access information for hosts in group A, but your playbook is only running against hosts in group B, then ansible won’t know anything about group A as it won’t have gathered the facts from them.

To rectify this, you can either add all relevant hosts/groups to your playbook, or add a play where you’re just gathering facts, e.g.

--- - hosts: dbservers gather_facts: true # I'm setting this to be explicit, it is the default # don't do anything here, just want to populate all the facts about the dbservers - hosts: webservers tasks: - name: do something with a db server fact debug: var=hostvars['db01.example.com']['ansible_default_ipv4']['address']

The other thing to remember is that facts are host specific. All facts are under the hostvars dict, so you need to access them using the full dict format (I think of it as a fully qualified var name, or fqvn). You can see this in the example above, where I’m calling hostvars['....']

You can use a fact caching mechanism, but then you need to handle populating and updating the cache.