Ansible course
CHAPTER 06
Roles
Reusable, shareable automation
10 min read3 sections
In this chapter
What is a role?Role structureUsing a role
01What is a role?
A role is a reusable package of tasks, variables, files, and templates. Instead of one giant playbook, you split your automation into roles: webserver, database, monitoring. Each role can be shared, versioned, and tested independently.
Why this exists
Roles make playbooks readable and reusable. A role for nginx can be used in 10 different playbooks without copying code.
02Role structure
A role has a standard directory structure. Ansible looks for tasks/main.yml automatically.
roles/
webserver/
tasks/
main.yml # the tasks
handlers/
main.yml # restart service, etc.
templates/
nginx.conf.j2 # Jinja2 templates
files/
app.conf # static files
vars/
main.yml # role variables
defaults/
main.yml # default variables (lowest priority)
meta/
main.yml # dependencies, author, license03Using a role
Reference roles in your playbook. Ansible Galaxy is a repository of community roles.
---
- name: Configure web servers
hosts: webservers
become: yes
roles:
- webserver
- monitoring
- security
# Ansible Galaxy commands:
# ansible-galaxy search nginx
# ansible-galaxy install geerlingguy.nginx
# ansible-galaxy list
# ansible-galaxy init my_roleCheck your understanding
0 / 1 correct
What is a role in Ansible?