Ansible Roles
Ansible roles are one of the most important building blocks for organizing automation in a scalable and reusable way. They let you take a large playbook and break it into modular, reusable components. A role is a standardized directory structure that automatically organizes:
- tasks (what to do)
- variables (inputs/config)
- handlers (restart services, etc.)
- templates (Jinja2 config files)
- files (static files to copy)
- defaults (lowest-priority variables)
- meta (dependencies)
Instead of writing one giant playbook, you call the roles.
Let’s create a sample role.
Let’s take a look at what that did.
You’ll see that it created a directory structure for all components with a main.yml in each directory. Now, let’s populate some details into our role.
Edit vars/main.yml and add the following
Create templates/motd.j2 and add the following content:
Edit tasks/main.yml and add the following:
Edit handlers/main.yml and add the following:
Back in the playbooks directory (up two levels) create a playbook named myplaybook.yml and add the following:
Now execute the playbook that calls the role.
Verify the results.