DevOps
Infrastructure as Code
Ansible: Mastering Roles

Ansible: Mastering Roles

Scale your infrastructure like a pro. As your automation grows, monolithic playbooks become difficult to manage. Ansible Roles allow you to break your automation into modular, reusable, and sharable components.


🏗️ The Anatomy of a Role

An Ansible role has a predefined directory structure. Each directory serves a specific purpose, allowing Ansible to automatically find and execute the correct files.

roles/
└── webserver/
    ├── tasks/       # Main list of tasks (main.yml)
    ├── handlers/    # Handlers for the role (main.yml)
    ├── templates/   # Jinja2 templates (.j2)
    ├── files/       # Static files to be deployed
    ├── vars/        # High-priority variables (main.yml)
    ├── defaults/    # Default low-priority variables (main.yml)
    └── meta/        # Role metadata and dependencies

Key Directories Explained:

  • tasks/: The heart of the role. Contains the main list of tasks to be executed.
  • handlers/: Used for tasks that should only run when notified by another task (e.g., restarting a service after a config change).
  • templates/: Store Jinja2 templates which can use variables to generate dynamic configuration files.
  • defaults/: The best place to store variables that users of the role might want to override.

🛠️ Creating and Using Roles

1. Create a New Role

You can manually create the folders, or use the built-in tool:

ansible-galaxy init roles/common

2. Consuming Roles in a Playbook

Instead of listing dozens of tasks, your playbook becomes a high-level orchestration of roles.

---
- name: Provision Production Environment
  hosts: all
  become: yes
  
  roles:
    - common      # Basic setup (users, packages, etc.)
    - webserver   # Nginx, SSL, and Configs
    - database    # MySQL/PostgreSQL setup

🔄 Reusability and Scaling

By using roles, you can:

  • Share: Use roles from Ansible Galaxy (opens in a new tab) created by the community.
  • Modularize: Update your "nginx" configuration in one place, and it applies to every project that uses that role.
  • Organize: Keep your repository clean and easy to navigate for team members.

⚖️ Defaults vs. Vars: Variable Precedence

Featuredefaults/main.ymlvars/main.yml
PurposeLow-priority "sane" defaults.High-priority role specifics.
OverrideEasily overridden by the user.Harder to override (stronger).
Use CasePort numbers, user names.Internal role logic values.

[!TIP] Keep Roles Simple! A good role does one thing well. If you find your "webserver" role is also installing a database and a monitoring agent, it's time to break it into three separate roles.