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.
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.
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.
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.
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With