If you have a large playbook, it make sense to run certain parts of it instead of running the entire playbook especially in troubleshooting time. You can do this with Ansible tags. With tags, you don’t have to write a separate playbook just with those  tasks that you want to run. Instead you run the entire playbook but with tags and only tasks with those tags will be run.

you can add one or more tags to a single task. You can also apply the same tag to more than one individual task. one tag can be added to multiple tasks at once by defining them at the level of a play. In other word, when you add a tag in play level, it will be applied to all task within the play.

root@debian:~/ansible-project1# cat tags.yaml
---
- hosts: csr1
  gather_facts: false
  connection: network_cli
  tags:
    - config

  tasks:
    - name: eigrp config
      ios_config:
        src: "eigrp_template.j2"
        match: none
      tags:
        - eigrp
        - template
        - tag1

    - name: hostname config
      ios_config:
        lines: hostname {{ inventory_hostname }}
      tags:
        - hostname
        - tag1

access ansible codes of this course in github

this is a video-based training therefore the output of running commands are not show in the text.

ansible tags in ansible website

To list all tasks with their tags, use –list-task

# ansible-playbook tags.yaml --list-tasks

! to check the ouptut of commands, pleas watch the video

To list all tags, use –list-tags

# ansible-playbook tags.yaml --list-tags

When you run a playbook, by default all tasks will be run

# ansible-playbook tags.yaml

To run tasks with specific tags, use –tag in the running playbook

# ansible-playbook tags.yaml --tag hostname
# ansible-playbook tags.yaml --tag eigrp
# ansible-playbook tags.yaml --tag “eigrp, hostname”

To run tasks that do not contain specific tags, use –skip-tags keyword

# ansible-playbook tags.yaml --skip-tags eigrp
# ansible-playbook tags.yaml --skip-tags “eigrp, hostname”

 

Back to: Ansible for Network Engineers > Ansible other Features

Leave a Reply

Your email address will not be published. Required fields are marked *


Post comment