Search code examples
ansibleansible-inventoryansible-template

Ansible use inventory host inside template


I'm trying to get the IP of my server in a template, to set up a monitoring process with a single defined IP.

Configuration example

The inventory file

prod_srv_mqtt:
  hosts:
    mqtt-broker-01:
      ansible_host: 10.10.10.10
    mqtt-broker-02:
      ansible_host: 10.10.10.11

Then I use this ansible_host as a target in my template file to configure my monitoring :

my-template.json.j2

ping {{ groups.prod_srv_mqtt.mqtt-broker-01.ansible_host }}

with the result on the target:

ping 10.10.10.10

The final objectif is to have only one variable with the IP set in my inventory and use this variable elsewhere.

Errors

I have test most of the syntaxes I can think of :

{{ groups.prod_srv_mqtt.mqtt-broker-01 }}
or
{{ hostvars['prod_srv_mqtt'][mqtt-broker-01] }}
or 

...

Some tests results :

{{ groups['prod_srv_mqtt'][0] }} -> return mqtt-broker-01
{{ groups['prod_srv_mqtt'][0].ansible_host }} -> return an error

{{ hostvars[groups['prod_srv_mqtt'][0]].ansible_host }} -> return the IP (but with an index as ref)
{{ hostvars[groups['prod_srv_mqtt']['mqtt-broker-01]].ansible_host' }} --> return An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ansible.errors.AnsibleUndefinedVariable: 'list object' has no attribute 'mqtt-broker-01'

Note: the playbook run on another host than the mqtt-broker-01


Solution

  • The answer was given by Zeitounator and obvious... hostvars['mqtt-broker-01'].ansible_host.