civicus030
civicus030

Reputation: 21

ansible include_tasks ignoring tags

I have been desperately trying selectively include tasks from a collection. According to the documentation at https://docs.ansible.com/ansible/latest/modules/include_tasks_module.html#include-tasks-module, tags can be passed along when including tasks, in two possible ways:

  1. Using the free-form
    - name: <whatever>
      include_tasks: tasks.yml
      args:
        apply:
          tags:
            - t1
  1. As a parameter
    - name: <whatever>
      include_tasks: 
        file: tasks.yml
        apply:
          tags:
            - t1

Based on the above, I prepared a small proof of concept, as presented below. The idea is to have a (play)book book.yml use tags to pick specific tasks from a catalogue tasks.yml. Unfortunately, invoking

ansible-playbook book.yml

will execute all the tasks every time tasks.yml is included, regardless of specifying the tags.

I have tried using Python 2.7 and Ansible 2.7, 2.8 and 2.9 on Mac OSX (Mojave).

What am I doing wrong?

Thank you in advance.

Code

  1. File book.yml

    ---
    - hosts: localhost
      vars:
        _task_file: tasks.yml
    
      tasks:
      - name: include_tasks "{{ _task_file }}" (free-form) with tag(s) pwd
        include_tasks: "{{ _task_file }}"
        args:
          apply:
            tags:
              - pwd
        tags:
          - pwd
    
      - name: include_tasks "{{ _task_file }}" with tag(s) dummy
        include_tasks:
          file: "{{ _task_file }}"
          apply:
            tags:
              - dummy
        tags:
          - dummy
    ...

  1. File tasks.yml

    ---
    
    - name: dummy
      command: echo -n
      tags: dummy
    
    - name: printenv
      command: bash -c "printenv | sort | grep -i ansible"
      register: _printenv
      tags: printenv
    
    - debug: var=_printenv.stdout_lines
      tags: debug
    
    - name: pwd
      command: pwd
      register: _pwd
      tags: pwd
    
    - debug: var=_pwd.stdout_lines
      tags: debug
    ...

Upvotes: 2

Views: 1973

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68034

Q: "The idea is to ... use tags to pick specific tasks from a catalog tasks.yml."

A: It's not possible to use tags "inside" a playbook this way. apply: tags will add the tags to the tasks not select them. The tags can select the tasks from "outside" of the playbook only:

  • on the command line. Options: --tags, --skip-tags
  • in the configuration section tags. Keys: run, skip
  • in the environment. Variables: ANSIBLE_RUN_TAGS, ANSIBLE_SKIP_TAGS

See:

The next option to consolidate tags is the concept of Ansible runner's project.

Upvotes: 1

Related Questions