Warning:
This article related to ansible 2.5.0. The behaviour of tags in ansible has
changed over the last few releases.
See part-1 for the previous
version relating to ansible 2.4.3.
The main motivation of learning about tags and dynamic includes, is that during
debugging of a complex configuration, where you have a nested structure of roles
and tasks, it’s useful to be able to run one or more tasks in isolation, without
having to make lots of changes to the code to achieve that.
The code for this example makes use of a playbook, which includes a role (using
include_role, which itself includes some tasks (using include_tasks)., The
aim of this endeveaour is to be able to run only tagged tasks in nested
task_files. You can checkout the code and follow along. The playbook writes out
some files out in your /tmp directory.
The ansible version I am using is as follows;
If you checkout the example repo, the code looks like this;
So the first thing to do is to run the first playbook with no tags specified and
see what the tasks look like;
And from that we can see that all the tasks are run. Whether they are tagged or
not.
The next thing to try, is to pass the tag run-me, and see what happens.
Obviously we hope that only the single task tagged run-me will run. But lets
not get our hopes up;
So nothing ran.. hardly surprising given the ansible docs say this with reference
to tags;
The above information does not apply to include_tasks or other dynamic
includes, as the attributes applied to an include, only affect the include
itself.
So how about tagging the include_role and include_tasks like so;
Great! our tagged task, ran as expected.
In playbook-3 I switched to tags: always so you don’t have to duplicate your
tags up to all the include_role and include_tasks modules.
For the next trick, we are going to test that we can run a tagged tasks in
a tasks file that was included in a loop like so;
and great! that seems to work as well;
Final Thing
So one other thing to note, is that you can also indent your tasks into a block
like so, which allows marking a series of tasks with tags, without a lot of
duplication.
So tags are pretty neat, if you update to the most recent version of ansible,
and read the docs.