ansible roles

www.igif‮oc.aedit‬m

Ansible roles are a way to organize tasks, variables, files, and templates into a reusable package that can be easily shared and applied to different playbooks. Roles provide a way to simplify the organization of tasks and allow for easier sharing and reuse of configurations.

A role is a directory structure that contains the following subdirectories:

  1. defaults: This directory contains default variables for the role. These variables can be overridden in the playbook.

  2. vars: This directory contains variables specific to the role.

  3. tasks: This directory contains the main set of tasks that the role will perform.

  4. files: This directory contains files that the role will copy to the remote hosts.

  5. templates: This directory contains templates that the role will use to generate files that will be copied to the remote hosts.

  6. meta: This directory contains metadata about the role, such as dependencies on other roles.

Here's an example of a simple Ansible role:

roles/
└── webserver
    ├── defaults
    │   └── main.yml
    ├── files
    │   └── index.html
    ├── meta
    │   └── main.yml
    ├── tasks
    │   └── main.yml
    ├── templates
    │   └── nginx.conf.j2
    └── vars
        └── main.yml

In this example, we have a role called webserver. The role contains directories for defaults, files, meta, tasks, templates, and vars.

The defaults directory contains a file called main.yml, which contains default variables for the role.

The files directory contains a file called index.html, which will be copied to the remote hosts.

The meta directory contains a file called main.yml, which specifies any dependencies for the role.

The tasks directory contains a file called main.yml, which contains the main set of tasks for the role.

The templates directory contains a file called nginx.conf.j2, which is a Jinja2 template that will be used to generate a configuration file for the remote hosts.

The vars directory contains a file called main.yml, which contains variables specific to the role.

Once a role has been created, it can be easily included in a playbook by using the roles keyword:

- hosts: web_servers
  roles:
    - webserver

This will apply the webserver role to all hosts in the web_servers group. Any variables or tasks defined in the role will be applied to the hosts as specified in the role directory structure.