Ansible – read inventory hosts and variables to group_vars/all file

Question:

I have a dummy doubt that keeps me stuck for a long time. I have a very banal inventory file with hosts and variables:

The problem is that I need to access all these hosts and variables, in the inventory file, from the group_vars/all file.

I’ve tried the following manners to access the host IP:

To access a host variable I tried:

All of them are wrong!!! Can anyone help me find out the best practice to access hosts and variables, not from a playbook but from a variables file?

Let’s clarify.

Problem: Use a host declared in the inventory file in a variable file, let’s say: group_vars/all.

Example: I have a DB host with IP:10.112.83.37.

Inventory file:

In the group:vars/all file I want to use that IP to build a variable.

group_vars/all file:

In a template I use the variable built in the group_vars/all file.

Template file:

The problem is that the {{ db }} variable in the group_vars/all file is not replaced by the DB host IP. The user can only edit the inventory file.

Answer:


This piece of code will give the message:

as groups['tests'] basically return a list of unique ip addresses ['10.112.84.122','10.112.84.124'] whereas groups['tomcat'][0] returns 10.112.84.124.

Leave a Reply