I have a simple playbook that executes two roles. Tags are just used to limit the execution to some role or another (instead of executing them all):
- name: Install packages
hosts: backend
roles:
- {role: some_role, tags: ['some']}
- {role: another_role, tags: ['another']}
Now I want to introduce a third role, but regardless of tags, it should never be executed on env: production
. I did it like this:
- {role: third_role, tags: ['third'], when: env != 'production'}
While this works, Ansible prints out a whole lot of details regarding this role when the environment is set to production
, all tasks get marked as being skipped. For an execution on production, this is a lot of unnecessary noise and I’m wondering how to improve this.
An option I considered would be to create a separate playbook that is never executed on production. But that adds additional complexity and because the third role depends on the first two, it feels wrong to separate it out… any ideas on how to improve this?
Instead of specifying the role under roles
you can use include_role
instead.
After Ansible 2.4, you can use ansible.builtin.import_role for static behaviour and this action for dynamic one.
By using the dynamic behaviour, we can stop the role from ever being included.
- name: Install packages
hosts: backend
roles:
- {role: some_role, tags: ['some']}
- {role: another_role, tags: ['another']}
tasks:
- name: Don't run in production
include_role:
name: third_role
when: env != 'production'
Another approach might be to create a ‘wrapper’ role for the roles that you don’t want to run in production.
wrapper/meta/main.yaml
---
dependencies:
- role: third_role
- role: forth_role
main.yaml
...
tasks:
- name: Don't run in production
include_role:
name: wrapper_role
when: env != 'production'
You might want to experiment with some variations until you find something that works for you and is tidy.
At this point it becomes a matter of how you want to keep things organised, Ansible can be very flexible.
You could also consider using dependencies in meta.yaml
so that your third role explicitly runs the first two. Then if you separate them into other playbooks it won’t be so fragile.