Ansible -- Part Three

Posted on Sun 30 December 2018 in linux

Based on the second part of the ansible series, in the third part, best practices are discussed. This encompasses mainly the structure of larger ansible projects.

Ansible Project Organization

Projects with several ansible playbooks can be organized in an arbitrary fashion. However, a good way to organize ansible playbooks is to group certain functionality into roles. This enables the reuse of existing functionality in different contexts as well as the sharing of certain roles with other users.

An example for a reasonable directory structure is as follows:

production.ini            # includes the hosts
webservers.yml            # playbook that makes use of one or more roles

roles/
    common/               # a role directory
        tasks/
            main.yml
        handlers/
            main.yml
        templates/
            mysite.conf.j2
        files/
            favicon.ico
            backup.sh
        vars/
            main.yml
        defaults/
            main.yml
        meta/
            main.yml
    monitoring/           # another role directory
    myapp/                # yet another role directory
    ...

Each role may contain one or multiple of the following subdirectories, e.g.:

  • tasks -- contains a list of tasks of the role
  • handlers -- contains the handlers of the role (can also be used outside the role)
  • defaults -- contains the default variables for the role
  • vars -- contains other variables for the role
  • files -- contains the files that are deployed via this role
  • templates -- contains the templates which are rendered via this role
  • meta -- defines some meta data for the role such as dependencies

Depending on the type of the role not all directories will be required. However, each directory that contributes to the logic of the ansible script must contain a main.yml file that will be read automatically.

The roles: option can be used to add multiple roles to the playbook. For example:

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

There are several advanced things you can do with roles. See the Ansible Roles documentation for more details.