Tagging included tasks

When including task files, it is possible to tag all the tasks within the file. The tags key is used to define one or more tags to apply to all the tasks within the include hierarchy. The ability to tag at include time can keep the task file itself un-opinionated about how the tasks should be tagged and can allow for a set of tasks to be included multiple times but with different data and tags passed along.

Tags can be defined at the include statement or at the play itself to cover all includes (and other tasks) in a given play.

Let's create a simple demonstration to illustrate how tags can be used. We'll start by editing our includer.yaml file to create a playbook that includes a task file twice, each with a different tag name and different variable data:

---
- name: task inclusion
hosts: localhost
gather_facts: false

tasks:
- include: more-tasks.yaml
vars:
data: first
tags: first

- include: more-tasks.yaml
vars:
data: second
tags: second

Now we'll update more-tasks.yaml to do something with the data being provided:

---
- name: included task
debug:
msg: "My data is {{ data }}"

If we run this playbook without selecting tags, we'll see this task run twice:

Now if we select which tag to run, say, the second tag, by altering our ansible-playbook arguments, we should see only that occurrence of the included task being run:

Our example used the --tags command-line argument to indicate which tagged tasks to run. A different argument, --skip-tags, allows the expressing of the opposite, which tagged tasks to not run.