There are more options:
- Put the logic into the expression of hosts:
shell> cat pb.yml
- hosts: "{{ (map_value == 'single')|ternary('STG', 'LIVE') }}"
tasks:
- debug:
var: ansible_play_hosts
run_once: true
gives what you want
shell> ansible-playbook pb.yml -e map_value=single
PLAY [single] ********************************************************************************
TASK [debug] *********************************************************************************
ok: [node1] =>
ansible_play_hosts:
- node1
PLAY RECAP ***********************************************************************************
node1: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
shell> ansible-playbook pb.yml -e map_value=distributed
PLAY [distributed] ***************************************************************************
TASK [debug] *********************************************************************************
ok: [app_node] =>
ansible_play_hosts:
- app_node
- db_node
- gateway_node
PLAY RECAP ***********************************************************************************
app_node: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
- Create children (group aliases)
shell> cat hosts
[STG]
node1
[single:children]
STG
[LIVE]
app_node
db_node
gateway_node
[distributed:children]
LIVE
Then, the playbook gives the same results
shell> cat pb.yml
- hosts: "{{ map_value }}"
tasks:
- debug:
var: ansible_play_hosts
run_once: true
If you can't change the inventory file put the aliases into a separate file. For example,
shell> tree inventory/
inventory/
├── 01-hosts
└── 02-aliases
shell> cat inventory/01-hosts
[STG]
node1
[LIVE]
app_node
db_node
gateway_node
shell> cat inventory/02-aliases
[single:children]
STG
[distributed:children]
LIVE
Then, the playbook gives the same results
shell> ansible-playbook -i inventory pb.yml -e map_value=single
...
shell> ansible-playbook -i inventory pb.yml -e map_value=distributed
...
- Use the inventory plugin constructed. See
shell> ansible-doc -t inventory constructed
For example, the inventory
shell> tree inventory
inventory
├── 01-hosts
└── 02-constructed.yml
shell> cat inventory/01-hosts
[STG]
node1
[STG:vars]
map_group_value=single
[LIVE]
app_node
db_node
gateway_node
[LIVE:vars]
map_group_value=distributed
shell> cat inventory/02-constructed.yml
plugin: constructed
use_extra_vars: true
compose:
map_group: map_value
groups:
map_group: map_group == map_group_value
Then, the playbook
- hosts: map_group
tasks:
- debug:
var: ansible_play_hosts
run_once: true
gives the same results
shell> ansible-playbook -i inventory pb.yml -e map_value=single
...
shell> ansible-playbook -i inventory pb.yml -e map_value=distributed
...
If you insist on testing the use case with a role create one
shell> cat roles/setup/tasks/main.yml
- debug:
var: ansible_play_hosts
run_once: true
and use it in the playbook with any tags you like
shell> cat pb.yml
- hosts: map_group
roles:
- role: setup