Ansible Roles - Role Dependencies
1. Introduction
In Ansible, roles are a way to organize playbooks and manage configurations. Role dependencies allow you to build modular, reusable roles by specifying other roles that must be executed before the current role.
2. What are Role Dependencies?
Role dependencies are a mechanism to define relationships between roles in Ansible. By declaring dependencies, you ensure that certain roles are executed before others, which can be critical for setups where one role relies on the resources or configurations provided by another.
3. Defining Dependencies
Dependencies are defined in the meta/main.yml
file of a role. Here’s how you can specify dependencies:
dependencies:
- role: common
- role: database
vars:
db_name: example_db
In this example:
- The role depends on a role named
common
. - It also depends on another role named
database
, with a variabledb_name
defined for its execution.
4. Best Practices
When working with role dependencies, consider the following best practices:
- Keep dependencies minimal to avoid tight coupling.
- Document role dependencies clearly within
meta/main.yml
. - Test roles independently to ensure they function correctly without dependencies.
- Use version constraints for dependencies to avoid breaking changes.
5. Example
Here’s a complete example of how a role might look with dependencies:
---
# meta/main.yml
dependencies:
- role: common
- role: database
vars:
db_name: example_db
# tasks/main.yml
- name: Ensure the application is installed
apt:
name: myapp
state: present
6. FAQ
What happens if a dependency fails?
If a role dependency fails, the playbook will stop execution, and no further tasks from the dependent role will be executed.
Can I use conditions with role dependencies?
No, role dependencies are executed unconditionally. You can manage conditions inside the roles themselves, but dependencies cannot be conditionally included.