Debakar Roy

Day 19: Ansible - Roles and best practices

1 min read

In this post: Ansible roles, why they help, how to use them in playbooks, and best practices for structuring Ansible projects.

Ansible roles: basics and creating

Roles give tasks, variables, handlers, metadata, templates, and files a standard directory structure. That makes automation reusable across projects instead of copy-pasted between playbooks, which keeps things maintainable.

A minimal example (see the official Ansible docs for the full layout):

---
- hosts: webservers
  roles:
    - common
    - webservers

Here the common and webservers roles are applied to the webservers host group.


Sharing roles with Ansible Galaxy

Ansible Galaxy is the public repository for community roles. Search for a role matching your use case instead of writing everything from scratch.

For example, to install a PostgreSQL server role:

ansible-galaxy install geerlingguy.postgresql

Then use it in a playbook:

---
- hosts: linux-host
  become: true
  roles:
    - role: geerlingguy.postgresql
      vars:
        postgresql_users:
          - name: debakarr


For best practices, these are worth reading: