Ansible Roles: Role Directory Structure
Introduction
Ansible roles are a way to organize playbooks and related files into reusable components. This lesson will focus on the directory structure of an Ansible role, which is crucial for maintaining order and ensuring high-quality automation.
Role Structure
The standard directory structure of an Ansible role is as follows:
Note: Understanding the role directory structure is essential for creating maintainable and reusable Ansible code.
my_role/
├── tasks/
│ └── main.yml
├── handlers/
│ └── main.yml
├── templates/
├── files/
├── vars/
│ └── main.yml
├── defaults/
│ └── main.yml
├── meta/
│ └── main.yml
└── README.md
Directory Components
- tasks/: Contains the main tasks for the role.
- handlers/: Contains handlers that can be called by tasks.
- templates/: Holds Jinja2 templates that can be deployed on managed nodes.
- files/: Contains static files that can be transferred to managed nodes.
- vars/: Contains variables for the role.
- defaults/: Holds default variables for the role.
- meta/: Contains metadata about the role (dependencies, author, etc.).
- README.md: Documentation for the role, explaining how to use it.
Best Practices
- Always define a
README.md
file to document the role. - Use descriptive names for directories and files.
- Keep role logic in
tasks/main.yml
and use includes to manage complexity. - Make use of
defaults/main.yml
to provide default values for variables. - Utilize
meta/main.yml
for defining role dependencies.
FAQ
What is an Ansible role?
An Ansible role is a way to group related tasks, variables, files, templates, and handlers into a reusable structure.
Why should I use roles?
Roles promote reuse and organization in your Ansible projects, making them easier to manage and share.
How do I create a role?
You can create a role using the ansible-galaxy init <role_name>
command, which sets up the standard directory structure automatically.