Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a role from within another role in Ansible?

Tags:

ansible

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?

like image 355
Tanner Semerad Avatar asked Feb 27 '14 19:02

Tanner Semerad


People also ask

How do you call roles in Ansible?

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 .

Does Ansible execute roles in order?

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.

How do I run a specific part of my playbook in Ansible?

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 .

Can Ansible roles be reused by playbooks in a different directory?

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.


1 Answers

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'" }
like image 89
TomDotTom Avatar answered Oct 05 '22 04:10

TomDotTom