Make it Reusable with Ansible Roles

Make the code base reusable with Ansible roles.

As time goes on, your playbooks will grow to an unwieldy size, and you will need to refactor the code into separate logical groupings. At the same time, you’ll likely create additional Ansible repositories. Ansible roles are the solution.

Ansible roles simplify writing complex playbooks by breaking them into multiple files and providing a framework for developing a fully independent collection of variables, tasks, files, templates, and modules. The result is a reusable code base that can be shared among playbooks and repositories.

The directory structure will look like the one below:

Press + to interact
|-- roles/
| |-- chocolatey/
| | |-- tasks/
| | | |-- main.yml
| | |-- handlers/
| | | |-- main.yml
| | |-- files/
| | |-- templates/
| | |-- vars/
| | | |-- main.yml
| | |-- defaults/
| | | |-- main.yml
| | |-- meta

The highlighted lines represent the following:

  1. Name of the role.
  2. Ansible tasks and execution logic.
  3. Handlers for the role.
  4. Files required by the role, scripts, license key files, etc.
  5. Template files for Jinja2 templating.
  6. Non-overwritable variables localized to the role.
  7. Overwritable variables that provide defaults for the role.
  8. Metadata information about the role.

Roles expect files to be in specific directories. Each directory is optional. You can exclude any of the directories that are not in use.

Create an Ansible role

...

Get hands-on with 1400+ tech skills courses.