Ansible Roles Best Practices

· Updated · 2 min read · Ansible Best Practices

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 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 role1, 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.

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.

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.

#Ansible