# Ansible Roles Best Practices

> How granular Ansible roles should be: highly reusable by configuration, but pragmatic for stateful applications that are not cloud native.

- Source: https://www.itwonderlab.com/ansible-roles-best-practices/
- Published: 2023-09-07
- Updated: 2026-10-05
- Author: Javier Ruiz Jiménez (https://www.javierruizjimenez.com/)
- Site: IT Wonder Lab (https://www.itwonderlab.com/)

---

## Ansible Roles Granularity

We recommend building **Ansible roles that are highly reusable by configuration**, but we also recommend **pragmatism** as our highest priority.

Systems and applications designed to be standalone, or created before the cloud existed, are sometimes called “non-cloud-native applications”. They are often stateful, cannot be clustered without sharing the underlying storage and, in general, are not designed to be recreated or to distribute the load between servers.

### Be pragmatic

For these applications, be pragmatic and do not spend a lot of effort creating reusable roles. Instead, create a single role that makes all the necessary changes and configurations for the application even if some of its actions are available in other roles. It is better to have a working role than to spend a huge amount of time fixing complicated dependencies.

You can find an example of such a role in the installation of WordPress. That role configures Nginx, PHP, and WordPress and adds [Let’s Encrypt – Free SSL/TLS Certificates](https://letsencrypt.org/) by requesting a certificate and automating the necessary renewal tasks.

Using a single role instead of three or four roles avoids the complexity of a generic Nginx role, which would need to support too many configurations to be reusable for WordPress, and it also allows a high degree of specialization.

### Role dependency (meta folder)

An example of a role defined for re-usability is the add\_packages role<sup>1</sup>, it was designed to install default packages defined in all **group\_vars** and it is also used as a dependency for the WordPress role used in the [How to use Ansible and Terraform together tutorial](https://www.itwonderlab.com/terraform-aws-ansible/).

By defining a dependency with parameters inside the meta folder, we add other roles that must be executed before.

The add\_packages role is used at the beginning of the playbook installing common software in all machines, and later on by using dependencies to add the specific packages needed for the role.

```json title="roles/linux/wordpress/meta/main.yml"
dependencies:
  - { role: add_packages,
    linux_add_packages_repositories: "{{ wordpress_add_packages_repositories }}",
    linux_add_packages_keys: "{{ wordpress_add_packages_keys }}",
    linux_add_packages_names: "{{wordpress_add_packages_names }}"
    }
```

1.  [Download the source code for the How to use Ansible and Terraform together tutorial](https://github.com/itwonderlab/ansible-aws-ec2-terraform-tags).
