Ansible Roles Basics
Introduction
Ansible roles are a way to organize and modularize your Ansible playbooks. They allow you to define reusable components that can be shared across playbooks and projects. This lesson will cover the basics of Ansible roles, including their structure, how to create and use them, and best practices to follow.
What Are Roles?
Roles are a methodology for organizing Ansible content that simplifies the sharing of automation tasks. They encapsulate tasks, variables, files, templates, and handlers in a standardized way.
Creating Roles
You can create a new role using the Ansible command line tool. The command below will create a new role named `my_role`:
ansible-galaxy init my_role
This command creates a directory structure for your role, which we will explore in the next section.
Role Structure
A typical role directory structure looks like this:
my_role/
├── tasks/
│ └── main.yml
├── handlers/
│ └── main.yml
├── templates/
├── files/
├── vars/
│ └── main.yml
└── defaults/
└── main.yml
- tasks/: Contains the main tasks for the role.
- handlers/: Contains handlers that can be called by tasks.
- templates/: Holds Jinja2 templates.
- files/: Contains static files that can be deployed.
- vars/: Contains variables specific to the role.
- defaults/: Contains default variables that can be overridden.
Using Roles
To use a role in a playbook, you can include it as shown below:
- hosts: all
roles:
- my_role
Best Practices
- Keep roles self-contained: Each role should manage a single function.
- Use defaults for variables: This allows roles to be reusable with different variables.
- Document your roles: Include a README file with instructions on how to use the role.
- Use version control: Keep your roles in a version control system to track changes.
FAQ
What is the purpose of Ansible roles?
Ansible roles provide a way to organize tasks, handlers, files, templates, and variables in a way that is reusable and easy to manage.
How do I share roles with others?
You can share roles by packaging them into a tarball or by making them available on Ansible Galaxy.
Can I nest roles?
Yes, you can nest roles within other roles, allowing for complex configurations to be broken down into simpler, manageable components.