Is it possible to use tags as a variable inside of playbook?
Specifically, I would like to have a condition to execute certain task
only if a tag has been defined.
I am aware this can be done with an --extra-vars option + checking for
variable instead, but I wanted to see if I could abuse the tags system
a bit to make the syntax less verbose/clearer.
name: set tag as fact
set_fact:
myvar = mytag
tags: mytag
`
I don’t think there is an ‘ansible_tags’ var passed to the playbook.
I haven’t looked, but It is possible that an action_plugin might have access to that (from main import cli), so you can create a module that sets ‘ansible_tags’ as an ansible fact.
Thanks for the input, but that is something that would solve my
requirement only partially.
What I wanted to do was more along the lines of (as someone has
already pointed out, tags do not seem to be exposed in a run):
- name: Run this only and only if the tag was defined
debug: msg="I am tagged, therefore I run"
when: myspecialtag in ansible_tags
tags:
- myspecialtag
For now I think I would need to stick to the --extra-vars in combination
with --tags.
Perhaps a better description of what I want to do is to be able to
rerun handlers only as needed in order to have a way to clean-up
certain broken runs ("meta"-code provided below):
- name: Run handlers only
include: ../handlers/main.yml
when: handlers in ansible_tags
tags:
- handlers
It sounds like you want to instruct a task to execute ONLY if a tag is present (skip if tag not set). I’ve seen that request before, but no idea if it may or may not be implemented.
I wonder if a vars_plugin or lookup_plugin might work…
would this work?
file ./lookup_plugins/get_tags.py
`
from future import (absolute_import, division, print_function)
from ansible.plugins.lookup import LookupBase
from main import cli
This looked promising, except that cli is not available on my ansible v 2.14.2 using python 3.11.2 Error was a <class ''ImportError''>, original message: cannot import name ''cli'' from ''__main__'' (/usr/bin/ansible-playbook)'