Definition
Host patterns allow you to specify exactly which nodes require tasks to be performed
Patterns with example:
allor*— all hostsstage:dev— union/logical ORstage:&dev— intersection/logical ANDstage:!dev— exclusion*.example— wildcarddev[5:10]— host range (counting starts from zero)~web\d+\.example— regular expressions
Instead of the : separator, you can use , which is preferable when working with IPv6 networks or ranges
The processing order is as follows:
:and,&!
You can use combinations of patterns:
hosts: dev:staging:&database:!queque(all hosts from thedevandstaginggroups if they are also in thedatabasegroup, but excluding hosts from thequequegroup)
You can also use variables to pass groups via -e, --extra-vars, for example: hosts: webservers:!{{ excluded }}:&{{ required }}
You can use it in playbooks and ad-hoc commands, but when using a playbook file, you need to use the -l, --limit flag:
Examples for ansible-playbook and ansible binaries (don’t forget to escape patterns with special bash characters with quotes)
ansible-playbook -l hosts main.yml
ansible-playbook -l 'staging:&database' main.yml
ansible-playbook -l 'staging,&database' main.yml
ansible all:localhost -m setup
ansible all,localhost -m setup
ansible 'staging:&database' -m reboot
ansible 'staging,&database' -m reboot
Playbook example:
- name: Play this on all hosts except db group
hosts: all:!db
tasks:
- name: Change hostname
ansible.builtin.file:
use: systemd
name: "{{ inventory_hostname }}"
- name: Play this on all host that are also in a backup group but not in a web one
hosts: all:&backup:!web
tasks:
- name: Add host record to /etc/hosts
ansible.builtin.lineinfile:
path: /etc/hosts
line: "{{ ansible_host }} {{ inventory_hostname }}"
state: present
insertbefore: BOF