I have a dummy doubt that keeps me stuck for a long time. I have a very banal inventory file with hosts and variables:
[lb] 10.112.84.122 [tomcat] 10.112.84.124 [jboss5] 10.112.84.122 ... [tests:children] lb tomcat jboss5 [default:children] tests [tests:vars] data_base_user=NETWIN-4.3 data_base_password=NETWIN data_base_encrypted_password= data_base_host=10.112.69.48 data_base_port=1521 data_base_service=ssdenwdb data_base_url=jdbc:oracle:thin:@10.112.69.48:1521/ssdenwdb
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:
{{ lb }} "{{ hostvars[lb] }}" "{{ hostvars['lb'] }}" {{ hostvars[lb] }}
To access a host variable I tried:
"{{ hostvars[tests].['data_base_host'] }}"
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?
EDIT:
Ok. 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:
[db] 10.112.83.37
In the group:vars/all file I want to use that IP to build a variable.
group_vars/all file:
data_base_url=jdbc:oracle:thin:@{{ db }}:1521/ssdenwdb
In a template I use the variable built in the group_vars/all file.
Template file:
oracle_url = {{ data_base_url }}
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.
Ansible uses a combination of a hosts file and a group_vars directory to pull variables per host group and run Ansible plays/tasks against hosts. group_vars/all is used to set variables that will be used for every host that Ansible is ran against.
You can use the option --list-hosts. It will show all the host IPs from your inventory file.
TL;DR: Inventory can be a folder. Create a folder, add as many inventory files inside this folder and instruct Ansible to use this folder as the inventory (with -i folder_name or in your ansible. cfg file). All inventory files inside the folder will be merged into one (including scripts like ec2.py).
- name: host debug: msg="{{ item }}" with_items: - "{{ groups['tests'] }}"
This piece of code will give the message:
'10.112.84.122' '10.112.84.124'
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
.
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