task 5.2 · chapter 5 of 8: handlers, tags, errors · 15 min
Tags
objective
Tag the interface tasks so you can run just the descriptions, or just the MTU.
playbooks/interfaces.ymlopen a file in VS Code: Ctrl+P (Cmd+P on a Mac), type its name, Enter
| Tags | descriptions on the first task, mtu on the second |
|---|
What are Ansible tags for?
Playbooks grow. Sometimes you only want to run part of one: just fix the descriptions, without touching the MTU.
Tags are labels on tasks, and --tags on the command line runs only the tasks with that label.
The opposite exists too: --skip-tags mtu runs everything except the tasks tagged mtu.
Tag tasks by what they configure, like descriptions, mtu, ntp. Then the tag names read like the change
you’re making.
Where does a tag go, and how do you check it?
- name: Description and no shutdown, one port at a time
cisco.ios.ios_interfaces:
config: [...]
loop: "{{ interfaces }}"
tags: [descriptions] # a task keyword, like loop: and when:
Before running a tag, check what it selects. --list-tasks prints the tasks a run would include, and touches
nothing:
ansible-playbook playbooks/interfaces.yml --tags descriptions --list-tasks
Tag the descriptions
Add
tags:to the first task, lined up withloop::editplaybooks/interfaces.ymlCtrl+P → interfaces.yml- name: Description and no shutdown, one port at a time cisco.ios.ios_interfaces: config: - name: "{{ item.name }}" description: "{{ item.description }}" enabled: true loop: "{{ interfaces }}" loop_control: label: "{{ item.name }}" tags: [descriptions]See what the tag selects:
run in the terminalansible-playbook playbooks/interfaces.yml --tags descriptions --list-tasksOne task listed, with
TAGS: [descriptions]. The MTU task isn’t there.Run just that part:
ansible-playbook playbooks/interfaces.yml --tags descriptions.
Tag the MTU
Tag the second task mtu. Then use --list-tasks to prove that --tags mtu selects only the MTU task, and
that --skip-tags mtu selects only the descriptions.
hint
Same line, same place, on the second task.
show the solutionplaybooks/interfaces.yml
or pull it into your lab: make solve T=5.2, then git diff --staged shows what changed
- name: Jumbo MTU on uplinks only
cisco.ios.ios_interfaces:
config:
- name: "{{ item.name }}"
mtu: 9100
loop: "{{ interfaces }}"
loop_control:
label: "{{ item.name }}"
when: item.uplink | default(false)
tags: [mtu]
5 check: run it, then prove it
$ ansible-playbook playbooks/interfaces.yml --tags descriptions
$ make check T=5.2when it's right, you'll see
╭─ task 5.2 · tags
│ ✓ --tags descriptions selects 1 task(s)
│ ✓ and leaves the others out
│ ✓ playbooks/interfaces.yml runs cleanly
│ ✓ the challenge: --tags mtu selects the MTU task, and only that (1)
╰─ 4/4 checks passed verified
background: part 5, Tags