Ansible roles provide a method for grouping related tasks, files, variables and handlers into a single self-contained package. They can be used to organize roles and facilitate reuse and shareable components across multiple playbooks. When a role is performed, Ansible will execute the tasks, copy files, set variables and apply handlers within the specified context.
Roles are organized with a top-level directory that contains subdirectories for tasks, files, templates, vars, defaults, meta and possibly library. The Roles directory (default directory named “roles”) is where all of the individual roles are stored and it is located in the same directory as the Ansible playbook.
Tasks are written in YAML format and are placed in the “tasks” directory of the role. Tasks allow you to automate any kind of work that needs to be done on the managed nodes. The tasks should be organized in a meaningful order such that when the role is called, the tasks are run in the proper order.
Files are stored in the “files” directory and are static files that should be copied from the managing node to the managed nodes during the execution of the role.
Templates are Jinja2 based .j2 files that contain values that should be replaced upon execution of the role. Templates should be placed in the “templates” directory and can contain any kind of data.
Vars and defaults are used to set variables and defaults for the role. These are placed in the “vars” and “defaults” directories in the role structure and should use the same names as the global variables they are intended to override.
Meta is used to specify external dependencies, such as other roles that need to be installed prior to using this role as well as other parameters that may effect the workings of the role.
In addition, roles can have their own variables, defaults and tasks. This allows for creating reusable components that can be used in multiple playbooks.
Overall, Ansible roles provide a way for automating common tasks and sharing them across multiple playbooks, making it easier to manage and maintain the infrastructure.