Reputation: 461
I have a role in ansible that expects different variables. I want to apply this role to a host group but every host in the group needs different values for this role.
I tried to archive this with this configuration: Group Var:
host1:
var1: 'project a'
var2: 'some other'
host2:
var1: 'project b'
var2: 'some different'
hosts:
[myHosts]
host1
host2
But I have no clue how can I loop to the different hosts in a play
#something before
- hosts: myHosts
become: true
roles:
- docker
- docker-compose
- git
vars:
- var1: ??
# Something like this possible?
- var2: currentHost.var2
Or is my attempt wrong and I use the tool incorrect? This role is the last step for a deployment. So in the vars I want to say something like become project a or become project b. Would this be bad practice? Should I better have a role project a, project b and assign them to the specific host via playbook even if the only difference between the two roles are some env variables?
Upvotes: 3
Views: 3778
Reputation: 68189
If you want to keep the data in group_vars
put the variables into a dictionary. For example,
shell> cat group_vars/myhosts.yml
my_dict:
host1:
var1: 'project a'
var2: 'some other'
host2:
var1: 'project b'
var2: 'some different'
Then, the variables may be easily "assigned" to each host
- hosts: myhosts
vars:
var1: "{{ my_dict[inventory_hostname]['var1'] }}"
var2: "{{ my_dict[inventory_hostname]['var2'] }}"
However, the best practice is to put such variables into the host_vars
and let Ansible "assign" the variables to the hosts automatically. For example,
shell> cat host_vars/host1.yml
var1: 'project a'
var2: 'some other'
shell> cat host_vars/host2.yml
var1: 'project b'
var2: 'some different'
Notes
var*
also into the group_vars
. For example,shell> cat group_vars/myhosts.yml
my_dict:
host1:
var1: 'project a'
var2: 'some other'
host2:
var1: 'project b'
var2: 'some different'
var1: "{{ my_dict[inventory_hostname]['var1'] }}"
var2: "{{ my_dict[inventory_hostname]['var2'] }}"
Upvotes: 3