Reputation: 116
Ansible version : 2.4.2.0
I'm using a directory as my inventory which has 2 files - a , b
File a
[frontend]
hostname001
[frontend:vars]
envt=frontend
File b
[backend]
hostname001
[backend:vars]
envt=backend
The value of variable is overriden and only backend persists.
Playbook sample
- name: Sample play
hosts: '{{ group }}'
connection: local
tasks:
- name: "Do a demo"
debug:
msg: 'The envt is {{envt}}'
When i try to deploy frontend by passing group=frontend as extravar, output is as follows
ok: [hostname001] => { "msg": "The envt is backend" }
How can i make sure the right variable is picked.
Upvotes: 1
Views: 549
Reputation: 311721
The problem is that regardless of how you set the group
variable, your host hostname001
is still a member of both groups. You're going to need to approach this using a different method.
One option would be to simply move the variable out of your inventory and have a couple of separate variable files that you use with the -e
option. E.g., you might call ansible-playbook
like this:
ansible-playbook playbook.yml -e @config1.yml
Or:
ansible-playbook playbook.yml -e @config2.yml
Alternately, maybe you could set the variable per-play instead of per-group.
As a final option, you could given the target host a different name in each group. E.g., something like:
[backend]
hostname001-backend ansible_host=hostname001
[backend:vars]
envt=backend
[frontend]
hostname001-frontend ansible_host=hostname001
[frontend:vars]
envt=frontend
Using that inventory, we see:
$ ansible-playbook playbook.yml -e group=frontend
PLAY [Sample play] ***************************************************************************
TASK [Do a demo] *****************************************************************************
ok: [hostname001-frontend] => {
"msg": "The envt is frontend"
}
PLAY RECAP ***********************************************************************************
hostname001-frontend : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
$ ansible-playbook playbook.yml -e group=backend
PLAY [Sample play] ***************************************************************************
TASK [Do a demo] *****************************************************************************
ok: [hostname001-backend] => {
"msg": "The envt is backend"
}
PLAY RECAP ***********************************************************************************
hostname001-backend : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Upvotes: 4