My playbook runs a list of roles:
roles:
- common
- postgres
- nginx
- supervisord
- { role: deploy_app, app_name: myapp }
- { role: deploy_app, app_name: otherapp }
I have another role, celery
, that I only want to run when the app named myapp
is created using deploy_app
. I was thinking I should pass a parameter into the role like this:
- { role: deploy_app, app_name: myapp, celery: yes }
Then within my deploy_app
role, I would use a when
conditional:
- name: create celery worker for application
<RUN ROLE HERE>
when: '{{ celery }}' == 'yes'
How can I conditionally run a role from within a task list?
Ansible executes this pattern recursively when you use the roles keyword. For example, if you list role foo under roles: , role foo lists role bar under dependencies in its meta/main. yml file, and role bar lists role baz under dependencies in its meta/main. yml, Ansible executes baz , then bar , then foo .
This way, roles run in the order they are defined in plays. Check the official docs for achieving more fine-grained control of your role's task execution order. Even if we define a role multiple times, Ansible will execute it only once.
The easiest way to run only one task in Ansible Playbook is using the tags statement parameter of the “ansible-playbook” command. The default behavior is to execute all the tags in your Playbook with --tags all .
You can re-use tightly focused playbooks, but you can only re-use them statically, not dynamically. A role contains a set of related tasks, variables, defaults, handlers, and even modules or other plugins in a defined file-tree.
I think ansible depenencies would help here. Just create a
/meta/main.yml
inside your role with the following:
---
dependencies:
- { role: celery, tags: ["sometag"], when: "celery == 'yes'" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With