RH294 Ch 8: Host Patterns, Imports, Includes and Tags

A single file with every task in it works until it does not. Ansible gives you three tools to keep projects manageable: host patterns, reusable files and tags.

Host patterns. The hosts: line accepts more than a group name. all, dev,test (union), webservers:&prod (intersection), prod:!node3 (exclusion), wildcards such as node or .lab.example.com. Quote patterns that start with or !. Test before you run: ansible 'prod:!node3' --list-hosts.

Importing and including. A task file is a plain list of tasks, no hosts: line. Pull it into a play with either:

yaml tasks: - name: Static, processed when the playbook is parsed ansible.builtin.importtasks: tasks/motd.yml - name: Dynamic, processed when execution reaches it ansible.builtin.includetasks: tasks/web.yml

Imports are static: tags and when are copied onto every imported task, and --list-tasks shows them. Includes are dynamic: they can use loops and variables computed at run time, but their tasks are invisible to --list-tasks and --start-at-task. Whole playbooks are combined with importplaybook at the top level of a file — there is no includeplaybook:

yaml - name: Users ansible.builtin.importplaybook: users.yml - name: Web ansible.builtin.importplaybook: web.yml

Tags. Add tags: users to a task, block, role or play, then run a subset with --tags users or skip with --skip-tags users. ansible-playbook site.yml --list-tags shows what exists. Two special tags: always runs unless explicitly skipped, never runs only when asked for.

Useful checks: --syntax-check, --list-hosts, --list-tasks, --list-tags — all fast and change nothing.

Common exam mistakes - Indenting importplaybook under tasks: (it must be a play-level item). - Writing hosts: in a task file. - Using when on a group instead of a host pattern when the task asks for a pattern. - Expecting --tags to select tasks inside an includetasks that itself has no tag.