anlar
anlar

Reputation: 607

Import only tagged blocks from Ansible role

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.

Upvotes: 10

Views: 5547

Answers (4)

BartBiczBoży
BartBiczBoży

Reputation: 2672

---
- 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.

Upvotes: 0

Moon
Moon

Reputation: 3037

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

Upvotes: 6

deepanmurugan
deepanmurugan

Reputation: 2113

- 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

Upvotes: -2

Jack
Jack

Reputation: 6168

Never mind. THIS DOES NOT WORK. --Jack

Useful discussion in comments, so I'm leaving this up.

Never tried it, but give apply a shot with include_role:

---
- hosts: some_host
  tasks:
  - include_role:
      name: roles/some_role
    apply:
      tags:
      - tag1

https://docs.ansible.com/ansible/latest/modules/include_role_module.html

Upvotes: -2

Related Questions