Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Ansible variables of another group

Tags:

ansible

Here is an example of inventory file:

[web_servers]
web_server-1 ansible_ssh_host=xxx ansible_ssh_user=yyy

[ops_servers]
ops_server-1 ansible_ssh_host=xxx ansible_ssh_user=zzz

Furthermore, web_servers group has specific vars in group_vars/web_servers:

tomcat_jmx_port: 123456

How can I access tomcat_jmx_port var when dealing with ops_servers ?

Some will probably say I need a commun ancessor group (like all) to put common vars, but this is just an example, in true life there are many vars I want to access from ops_servers, and I want to keep things clear so tomcat_jmx_port have to stay in web_servers group_vars file.

In fact, I need a kind of local lookup.

Any idee ?

Thanks for your help.

like image 938
pierrefevrier Avatar asked Oct 30 '15 14:10

pierrefevrier


People also ask

How do you pass multiple vars in Ansible?

To solve this issue, we can use the Ansible extra vars feature. We can define a variable representing the hosts' group and specify its value when running the playbook. Now that we have an example playbook as above, we can pass the value to the “group” variable using the –extra-vars option while running the playbook.

What is Host_vars and Group_vars in Ansible?

The host_vars is a similar folder to group_vars in the repository structure. It contains data models that apply to individual hosts/devices in the hosts. ini file. Hence, there is a YAML file created per device containing specific information about that device.


2 Answers

To access variables from an arbitrary group you'd use the global variable groups which gives you access to all the vars of the hosts in the group. So something like this would return the name of the first host in the web_servers group:

{{ groups['web_servers'][0] }}

To access the individual variables of a host you would do something like this:

{{ hostvars['somehost']['ansible_default_ipv4']['address'] }}

This would return the default IP address of the host named somehost.

You can easily combine hostvars & groups if you need something more complex:

{{ hostvars[groups['web_servers'][0]]['ansible_default_ipv4']['address'] }}

This one will give you the default IP address of the first host in your web_servers group.

like image 54
Bruce P Avatar answered Oct 05 '22 03:10

Bruce P


You can also "include" the variables in the run context using

- include_vars: group_vars/web_servers

Notice that if you have variables with the same name in the context they will be overwritten.

This will make your variable available as {{ tomcat_jmx_port }}

like image 26
Jefferson Girao Avatar answered Oct 05 '22 01:10

Jefferson Girao