Ansible: Execute task only when a tag is specified

Ansible tags can be used to run only a subset of tasks/roles. This means that by default all tasks are executed and we can only prevent some tasks to execute.

Can we limit a task to be exectued only when "foo" tag is specified? Can we use current tags in when section of a task?


Ansible 2.5 comes with special tags never and always. Tag never can be used exactly for this purpose. E.g:

tasks:
  - debug: msg='{{ showmevar}}'
    tags: [ 'never', 'debug' ]

In this example, the task will only run when the debug (or never) tag is explicitly requested. [Reference on ansible docs]


Although this is a roundabout solution, it works.

Inside the task list register a variable when normal execution runs. Then, add a when condition that checks that variable to the tagged task.

- shell: /bin/true
  register: normal_task_list

- name: Only run when tag is specified
  shell: /bin/echo "Only running because of specified tag"
  when: normal_task_list is not defined
  tags: specified

I don't have enough reputation to upvote or comment on the answer suggesting the use of command-line variables (--extra-vars), but I have this to add to it:

The caveat to this method is that the play will error and fail if you do not define that extra variable.

You can prevent play failure in the absence of an --extra-vars definition by defining a default value in the playbook itself:

---
- hosts: ...
# ↓↓↓
  vars:
    thorough: false
# ↑↑↑
  tasks:
  - name: apt - install nfs-common only when thorough is true
    when: thorough | bool
    apt:
      cache_valid_time: 86400
      force: yes
      pkg:
        - nfs-common

Overriding via --extra-vars will still work because variables defined on the command line take precedence over all other definitions.

The result is that the play runs without error when thorough is not changed to true on the command line.