Reputation: 9313
How can I access the tags and skip-tags passed via command line to an ansible playbook at run time?
I am trying to achieve a with_items
loop that can skip or include items based on tag/skip-tag using a when
clause. This previous SO question touches on the same topic but takes a different approach.
I would evaluate the existence of a tag per iteration.
For example:
- name: Build docker images
docker_image:
name: "{{item.name}}"
path: "{{build_folder}}/dockerfiles/{{item.name}}"
dockerfile: "{{item.name}}.Dockerfile"
state: build
tag: "{{private_docker_registry}}/{{item.name}}"
when: "{{ansible_host_vars['tags'][image1]}}" is defined
with_items:
- image1
- image2
- image3
Upvotes: 5
Views: 6554
Reputation: 1046
Since 2.5, ansible added some magic variables to access at runtime. Some of them is ansible_run_tags
. It seems to be what you needed.
Upvotes: 10
Reputation: 60029
Tags are not available at runtime. Tags define what tasks will be executed. You can use this to translate tags to facts:
- set_fact:
image1: True
tags: image1
- set_fact:
image2: True
tags: image2
- set_fact:
image3: True
tags: image3
Now you have facts corresponding to your tags and can use them in your condition:
...
when: hostvars[inventory_hostname][item] == True
with_items:
- image1
- image2
- image3
But for me this feels wrong. This is not the purpose of tags. Tags should not define what software is installed on a host. This should be defined in your group/host vars. Tags then should simply limit the play to a subset of tasks, for example to update packages, to restart services, etc.
Beside tags you could archive the same with extra-vars. This also gives you more control. If you call your playbook without any tags provided, all tasks will be executed.
Upvotes: 2