Ansible host patterns

Source: https://docs.ansible.com/ansible/latest/user_guide/intro_patterns.html

Groups

Description Pattern(s) Targets

All hosts

One host

Multiple hosts

One group

all (or *)

host1

host1,host2 (or host1:host2)

webservers

Multiple groups webservers,dbservers all hosts in webservers plus all hosts in dbservers
Excluding groups webservers,!atlanta all hosts in webservers except those in atlanta
Intersection of groups webservers,&staging any hosts in webservers that are also in staging

You can use either a comma (,) or a colon (:) to separate a list of hosts. The comma is preferred when dealing with ranges and IPv6 addresses.

Wildcards

You can use wildcard patterns with FQDNs or IP addresses, as long as the hosts are named in your inventory by FQDN or IP address:

192.0.\*
\*.example.com
\*.com

You can mix wildcard patterns and groups at the same time:

one*.com,dbservers

Regular expressions

You can specify a pattern as a regular expression by starting the pattern with ~:

~(web|db).*\.example\.com

List all matching ansible hosts

ansible-playbook <playbook> --list-hosts will list all hosts a playbook will target.

And here’s a convenient snippet Andreas Lutro shared to list all hosts, without any other data:

ansible-inventory -i inventory/ --list | jq -r '.. | .hosts? // empty | .[]' | sort | uniq