Middle
How should a proper role be structured in Ansible?
sobes.tech AI
Answer from AI
The correct role structure in Ansible usually has the following layout:
my_role/
├── tasks/
│ ├── main.yml // Main file with the role's core tasks
│ └── another_task.yml // Additional task files (if needed)
├── handlers/
│ └── main.yml // Handlers file (for restarting services, etc.)
├── vars/
│ └── main.yml // Variables specific to the role
├── defaults/
│ └── main.yml // Default variables (low priority)
├── files/ // Directory for static files to copy
│ └── some_file.txt
├── templates/ // Directory for Jinja2 templates
│ └── some_template.conf.j2
├── meta/ // Directory with role metadata
│ └── main.yml // Role info, dependencies, platform compatibility
├── library/ // Directory for custom modules (rarely used)
├── module_utils/ // Utilities for custom modules (rarely used)
└── tests/ // Directory for role tests (e.g., with Molecule)
├── inventory
└── test.yml
Directory explanations:
- tasks: Contains main playbook files executing the role's tasks.
main.ymlis the entry point. - handlers: Contains tasks triggered only upon notification (
notify). Used for actions to perform after changes (e.g., restart a service). - vars: Variables specific to this role, which can change depending on the environment. They have higher priority than those in
defaults. - defaults: Variables with the lowest priority, applied by default if not overridden elsewhere.
- files: Contains static files to be copied as-is to target machines.
- templates: Contains template files processed with Jinja2 before copying to target machines, allowing dynamic content insertion.
- meta: Contains metadata such as dependencies, supported platforms, and author info.
main.ymlis mandatory if dependencies exist. - library/module_utils: Used for creating custom modules or utilities for them. Needed for complex, non-standard modules.
- tests: Directory for automated role tests, often using tools like Molecule.
Main principles:
- Modularity: Each role should be a self-contained block performing a single logical function.
- Idempotency: Tasks should be idempotent, so repeated runs do not cause unwanted side effects.
- Reusability: Roles should be easily reusable across different playbooks and projects, aided by variables.
- Readability: Proper structuring makes roles more understandable to others.