Tags as variable inside of playbook

Hello folks,

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.

Best regards

This is probably very terrible, but…

`
pre_tasks:

  • 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.

If I understand correctly what you want...

ansible-playbook myplaybook.yml --tags=myspecialtag is what you're looking for...

A tag can be use in more than one task...

The doc :
http://docs.ansible.com/ansible/playbooks_tags.html

Regards,

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

Best regards

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

class LookupModule(LookupBase):

def run(self, terms=‘’, **kwargs):
tags = cli.get_opt(‘tags’).split(‘,’)
return [ tags ]

`

file ./stuff.yml

`

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)'

A Magic var has been added, you can use ansible_run_tags now.
https://github.com/ansible/ansible/blob/stable-2.5/changelogs/CHANGELOG-v2.5.rst#minor-changes-4

Use the never tag:

tags: never, mytag

This ensures the task is never selected UNLESS you specifically target
a defined tag.