Reputation: 3
Is it possible to auto create a host group based on manually defined host variables?
This is my inventory:
[webserver]
web1 ansible_host=192.168.20.1 production=False
web2 ansible_host=192.168.20.2 production=False
web3 ansible_host=192.168.20.3 production=True
web4 ansible_host=192.168.20.4 production=True
...
I want to have a dynamic hostgroup, e.g., webserver_production
and use this as target.
Is there another way to do archive this? Thank you.
Upvotes: 0
Views: 93
Reputation: 68189
Use the inventory plugin constructed. See
shell> ansible-doc -t inventory constructed
shell> tree inventory/
inventory/
├── 01-webserver
└── 02-webserver_production.yml
0 directories, 2 files
shell> cat inventory/01-webserver
[webserver]
web1 ansible_host=192.168.20.1 production=False
web2 ansible_host=192.168.20.2 production=False
web3 ansible_host=192.168.20.3 production=True
web4 ansible_host=192.168.20.4 production=True
shell> cat inventory/02-webserver_production.yml
plugin: constructed
groups:
webserver_production: production
shell> ansible-inventory -i inventory --list --yaml
all:
children:
ungrouped: {}
webserver:
hosts:
web1:
ansible_host: 192.168.20.1
production: false
web2:
ansible_host: 192.168.20.2
production: false
web3:
ansible_host: 192.168.20.3
production: true
web4:
ansible_host: 192.168.20.4
production: true
webserver_production:
hosts:
web3: {}
web4: {}
shell> cat pb.yml
- hosts: webserver
gather_facts: false
tasks:
- debug:
var: ansible_play_hosts_all
run_once: true
- hosts: webserver_production
gather_facts: false
tasks:
- debug:
var: ansible_play_hosts_all
run_once: true
gives (abridged)
shell> ansible-playbook -i inventory pb.yml
PLAY [webserver] *****************************************************************************
TASK [debug] *********************************************************************************
ok: [web1] =>
ansible_play_hosts_all:
- web1
- web2
- web3
- web4
PLAY [webserver_production] ******************************************************************
TASK [debug] *********************************************************************************
ok: [web3] =>
ansible_play_hosts_all:
- web3
- web4
Notes:
The files in the directory inventory are evaluated in alphabetical order.
See Special Variables ansible_play_hosts, ansible_play_hosts_all, ...
Upvotes: 2