Selecting hosts based on variable

Hi all,
Is there a way to select hosts in inventory based on a variable ?
More specifically, I have a host file like :

[webservers]
web1.example.com location=room1
web2.example.com location=room1
web3.example.com location=room22

[dbservers]
db1.example.com location=room22
db2.example.com location=room1
db3.example.com

I would like to be able to select all computers with location=room1 (basically I want to shutdown all these machines because we have to cut the power in this room).
Thus a commande like :

ansible all --list-hosts --filter=location=room1

would be great.

Il could do that more or less in a playbook, but I also use ansible in shell scripts to run specific commands.

F.

in play:
hosts: “{{mytarget}}”

on command line:

-e ‘mytarget=myhost:myhost2’

though i you could also use --limit ‘room1’ (and have a room1 group for those hosts) or --limit ‘myhost:myhost2’

Thanks for your answer. I know that I could do another group based on location… but the point is that you get very fast a lot of groups… thus when you add/remove/update a new computer you have to do it at many places in the host file so it’s easy to forget to update a group !

You can create dynamic groups by using the group_by module:

  • name: Create groups based on location
    group_by: key={{ location }}

then use something to similar to what Brian had said earlier in the play:

ansible-playbook -e ‘mylocation=room1’

playbook should contain:

hosts: “{{ mylocation }}”

  • James

I have to say that group_by is a very useful module if you are trying to keep your inventory minimal, but want to be able to sleect servers based on common characteristics (networks, operating systems, hardware types and so on. I suspect that you could combine group_by and local facts to easily achieve what you want…

Create an /etc/ansible/local/facts.d with a location fact in it and then you can use that in your group_by quite happily…

Adam