Search code examples
ansibleroles

Is there a way to run a role only if a tag is specified?


I have been asked to write two roles for the preproduction and production server that would install some programs (Memcached, its PHP extension, etc), and also configure them.

Well, yesterday, I messed up a bit, because there are two other roles that are used, while mine are not quite finished yet. And yesterday, the project our team is working on was put on production. On each of those, the playbook is run, with all the roles on it, and it began to run my roles too. Fortunately, my team's chief saw it on time and removed my roles from the playbook.

So here how looked my roles in the playbook before they got deleted:

- hosts: was
  roles:
    - { role: cron, become: yes, tags: [ was, cron ] }
    - { role: app, when: type == 'master', become: yes, become_user: "{{become_user}}", become_flags: '-i', tags: [ was ] }
    - { role: memcacheExtension, become: yes, become_user: ansible, tags: ['memcache'] }
    - { role: gitlabRunner, become: yes, become_user: "{{become_user}}", tags: ['gitlab'] }

My roles are the last two ones. I thought that with this configuration, they would only be triggered if the command ran was using one of the tags I set. Spoiler: I was wrong.

I've heard of the 'never' tag, but it only works within the tasks, so I would have to set it for each tasks, which is not what I'm looking for.

Is there any other possibility?

Thank you in advance


Solution

  • Yes there is the possibility to import_role, or include_role which is a task and can be tagged.

    - hosts: was
      roles:
        - { role: cron, become: yes, tags: [ was, cron ] }
        - { role: app, when: type == 'master', become: yes, become_user: "{{become_user}}", become_flags: '-i', tags: [ was ] }
      tasks:
        - import_role:
            name: memcacheExtension
          become: yes
          become_user: ansible
          tags: memcache
        - import_role:
            name: gitlabRunner
          become: yes
          become_user: "{{become_user}}"
          tags: gitlab