Import only tagged blocks from Ansible role

Viewed 2433

I want to import into playbook (and execute) only part of Ansible role defined in tagged block.

E.g. I have role some_role containing 3 blocks of tasks tagged as tag1, tag2 and tag3. I could create playbook that imports whole role:

---
- hosts: some_host
  roles:
    - role: roles/some_role

And then execute it from command line specifying single tag:

$ ansible-playbook -i hosts.yml playbook.yml --tags tag1

But I want to move --tags tag1 part into playbook itself to be able to run that single block without providing tags to ansible-playbook.

4 Answers

I couldn’t find any easy way to execute part of a role with specific tag from the playbook.

An way could be to break the tasks in multiple files and use a file from playbook using import_role or include_role. Say, if you create two files in role’s task directory named main.yml and other.yml then you can use other tasks like below.

- import_role:
     name: myrole
     tasks_from: other
- import_role: 
      name: myrole 
  tags: [ web, foo ] 

- import_tasks: foo.yml 
  tags: [ web, foo ]

You can achieve it using the above code block.

Reference: ansible doc

---
- hosts: some_host
  tasks:
    - include_role:
        name: some_role
      tags: tag1

some_role has to have tag1 defined in its tasks naturally. But you also need to execute it using tag1, just like you did in the question:

ansible-playbook -i hosts.yml playbook.yml --tags tag1

I've just tested it with ansible 2.10.6 following docs. Make sure you use include instead of import.

Related