Ansible: action only executed if tag set, avoiding ‘all’ behavior

Even if the actions in your playbook/role are tagged to separate their logic, this ability to selectively execute will not operate properly when called without any tags because then you will fallback to the special ‘all‘ behavior.

Consider a playbook with the following actions.

  tasks:

    - debug: msg="when tag 'run'"
      tags: run

    - debug: msg="when tag 'delete'"
      tags: delete

When run with explicit tags on the command line, it operates exactly as expected.  However, when run without tags it will use the default behavior, which is to set the internal ‘ansible_run_tags‘ to ‘all’.  This results in all the actions being executed.

# only displays message for run
ansible-playbook myplay.yml --tags run

# only displays message for delete
ansible-playbook myplay.yml --tags delete

# BUT call playbook without any tags, uses 'all' default behavior
# which executes all actions (run + delete)
ansible-playbook myplay.yml

However, you can avoid this behavior by adding the special ‘never‘ tag to your task.

    - debug: msg="only when tag is explicitly set to 'delete'"
      tags: ['delete','never']

Now the delete action will not ever be called unless we explicitly specify the tag.

# only displays message for run
ansible-playbook myplay.yml --tags run

# call playbook without any tags, uses 'all' behavior
# but now only executes only run action, and not delete
ansible-playbook myplay.yml


# we can still call delete, but only by explicitly setting tag
ansible-playbook myplay.yml --tags delete

 

REFERENCES

github fabianlee, playbook-never-tag.yml

ansible docs, special tags ‘always’ ‘never’ with –tags and –skip-tags

ansible docs, special variables

NOTES

Equivalent behavior can be achieved with ‘when’ and tags

when: "'delete' in ansible_run_tags"
tags: delete