Ansible Inventory with Regex

A particular customer has a naming scheme that’s just different enough to make me learn something new. They use a site code and the model number of the device. For example a 3650 in Appleton would be APL-IDF1-3650-01. I wrote some playbooks to push out a QoS configuration, but filtering the inventory was a pain. They have no grouping, just one huge inventory file. In rolling out the playbook, we only want a subset of devices (by location). In the playbook we can filter on the hosts: argument and use regular expressions:

hosts: ~(A|B|C|D).*(3650|3850|9300)

What this does is looks through the inventory file and grabs the hosts that start with the letter A, B, C and D. Then it filters on the rest of the hostname, requiring 3650, 3850 or 9300.

BRK-IDF5-3650-01
DIT-IDF4-3650-01
DML-IDF4-9300-01
BRK-IDF4-3650-01
BRK-MDF-3850-01
DZY-IDF2-3650-01
BRK-IDF2-3650-01
APL-IDF1-3650-01

You can also filter on the name with simple operators like:

All hosts that start with BRK-IDF
BRK-IDF*
All even IDF’s numbered 2-8
IDF(2|4|6|8)*
All hosts that start with BRK and have MDF in the name
~(BRK).* (MDF)

If you have IP’s or ansible_host= in your inventory you can filter on them too:

All hosts in a specific subnet
10.210.40.*