Role Structure
Ansible roles are the cornerstone of modular, reusable automation logic. By structuring roles with standardized directories and organizing them into logical groups, you enable teams to share, maintain, and scale automation across environments. This section explains how to create and organize Ansible roles effectively.
Standard Role Structure¶
A well-structured Ansible role follows a predictable directory layout, ensuring clarity and reusability. The core directories are:
my_role/
├── tasks/
│ └── main.yml
├── handlers/
│ └── main.yml
├── templates/
├── vars/
│ └── main.yml
├── defaults/
│ └── main.yml
├── meta/
│ └── main.yml
└── files/
- tasks/main.yml: Contains the primary automation logic (e.g., installing packages, configuring services).
- handlers/main.yml: Defines handlers for services or resources that require restarts.
- templates/: Stores Jinja2 templates for dynamic configuration files.
- vars/main.yml: Holds variables specific to the role.
- defaults/main.yml: Defines default values that can be overridden by playbooks or other roles.
- meta/main.yml: Specifies dependencies and metadata (e.g.,
dependenciesfor other roles). - files/: Stores static files to be copied to target systems.
Example: A role to install and configure Nginx might have a tasks/main.yml like this:
Organizing Roles into Collections¶
For larger projects, group related roles into a roles/ directory. For example:
- Role dependencies: Use
meta/main.ymlto declare dependencies between roles. For example: - Role inheritance: Use
roles/in playbooks to include roles, specifying parameters:
Best Practices for Role Organization¶
- Use consistent naming: Follow kebab-case (e.g.,
my-role) and avoid hyphens in role names. - Version control: Tag roles with semantic versions (e.g.,
1.0.0) in ameta/main.ymlor version control system. - Isolate logic: Avoid mixing unrelated tasks in a single role. Split into multiple roles if needed.
- Test thoroughly: Use tools like Molecule to test roles in isolated environments.
- Document metadata: Include
meta/main.ymlto describe dependencies, authors, and license information.
Key takeaways¶
- Standardize role structure to ensure consistency and reusability.
- Group related roles into a shared
roles/directory for easier management. - Declare dependencies explicitly in
meta/main.ymlto enforce role order. - Follow naming and versioning conventions to simplify collaboration and updates.
- Test roles in isolation to catch errors early and ensure reliability.