
Tags can be used to only play certain task or to not play certain tasks. For example, this playbook has two tasks, where one task is tagged "foo" and the other task is tagged "bar".
---
- hosts: all
tasks:
- name: foo task
ansible.builtin.debug:
msg: foo task
tags:
- foo
- name: bar task
ansible.builtin.debug:
msg: bar task
tags:
- bar
...
The -t or --tags command line option can be used to only play the "foo" task, like this.
ansible-playbook example.yml --tags "foo"
Which would only play the foo task, like this.
TASK [foo task]
ok: [server1.example.com] => {
"msg": "foo task"
}
Likewise, the --skip-tags command line option can be used to skip tasks that have a certain play. In this example, the "foo" task is skipped, like this.
ansible-playbook example.yml --skip-tags "foo"
Which would only play the bar task, like this.
TASK [bar task]
ok: [server1.example.com] => {
"msg": "bar task"
}
Tagging every task
Every task is a playbook can be tagged with the same tag.
---
- hosts: all
tasks:
- name: hello task
ansible.builtin.debug:
msg: hello task
tags:
- foo
- name: world task
ansible.builtin.debug:
msg: world task
tags:
- foo
...
However, the better way to do this is to create the tag before tasks, like this.
---
- hosts: all
tags: foo
tasks:
- name: hello task
ansible.builtin.debug:
msg: hello task
- name: world task
ansible.builtin.debug:
msg: world task
...
Or like this.
---
- hosts: all
tags:
- foo
tasks:
- name: hello task
ansible.builtin.debug:
msg: hello task
- name: world task
ansible.builtin.debug:
msg: world task
...
Or like this.
---
- hosts: all
tags: [ foo ]
tasks:
- name: hello task
ansible.builtin.debug:
msg: hello task
- name: world task
ansible.builtin.debug:
msg: world task
...
Tagging Roles
To run every task in a role, tags can be used with the role, like this. If you only want certain tasks in the role to be run, then you would apply tags to each task in the role.
---
- hosts: all
roles:
- role: foo
tags: bar
Tagging Blocks
Tags can be used with blocks. In this example, all of the tasks in the block will be run when the playbook is run with the foo or bar tag.
---
- hosts: all
tasks:
- block:
- name: hello task
ansible.builtin.debug:
msg: hello task
- name: world task
ansible.builtin.debug:
msg: world task
tags:
- foo
- bar
...
The --list-tasks command line option can be used to output the tasks that would have been invoked.
ansible-playbook example.yml --tags "foo" --list-tasks
Which should return something like this.
playbook: example.yml
play #1 (all): all TAGS: []
tasks:
name of your first task TAGS: [foo, bar]
name of your second task TAGS: [foo, bar]
name of your third task TAGS: [foo]
Did you find this article helpful?
If so, consider buying me a coffee over at