Ansible apply tags from a playbook (not command line)

Viewed 321

I run my playbook a.yaml, and in a.yaml I want to include one or more tasks from b.yaml.
First, I tried put following on a.yaml:

import_playbook: b.yaml --tags "tag1"

But this errors out saying the --tags doesn't apply to import_playbook. Based on latest Ansible include_tasks documentation, I tried with following: a.yaml:

- include_tasks:
    file: b.yaml
    apply:
      tags: tag1

b.yaml:

- shell: echo $HOSTNAME
  register: hostname
  tags: tag1

- debug:
    msg: "task2"
  tags: tag2

But both tasks in b.yaml got invoked though I only expected the first as tag indicated.

Questions:

  • How to have tags passed from a.yaml to b.yaml and get recognized? I don't mind to use something else if include_tasks is not the solution.
  • How to pass the result (the hostname, or any result) from b.yaml back to caller a.yaml?
1 Answers

What you try to do is - sadly - not possible.
Tags that are to be executed can only be specified on the cli.

apply does not specify which tags to include, but applies the tag to each task in the included file. That means that it adds the tag, the same way as if you added tags: tag1 to all your tasks in b.yaml.

If you want to only include certain tasks of a file, they need to have that tag in that file, and then you can use --tags "tag1" on the cli.
I would advise you not to do that excessively, as it will get very hard to find out what is actually going to happen for anybody who reads the code later, including you.

Meta: Please only ask one question per post on Stackoverflow.

I do not get your second question. If you include tasks from a different file, they are executed the same way as if they were directly there, so you do not need to pass anything. You can just access it.

E.g. like this:

main.yml:

- hosts: localhost
  tasks:
    - include_tasks:
        file: i.yml
    - debug:
        msg: "{{ tvar.stdout }}"

i.yml:

- shell: date -u
  register: tvar

Result:

TASK [include_tasks] **********************************************************************************
included: /home/.../test/i.yml for localhost

TASK [shell] **********************************************************************************
changed: [localhost]

TASK [debug] **********************************************************************************
ok: [localhost] => {
    "msg": "ons 14 apr 2021 05:34:25 UTC"
}
Related