Sobes.tech
Junior — Middle

What steps should be followed when creating and managing a role in Ansible?

sobes.tech AI

Answer from AI

Creating and managing a role in Ansible usually involves the following steps:

  1. Creating the role structure — you can use the command ansible-galaxy init <role_name>, which creates a standard directory structure (tasks, handlers, defaults, vars, files, templates, meta).

  2. Defining tasks — in the tasks folder, describe the main tasks of the role in the main.yml file.

  3. Handlers — in the handlers folder, describe actions triggered by events (e.g., restarting a service).

  4. Variables — in the defaults and vars folders, set variables with different priorities.

  5. Templates and files — place Jinja2 templates and static files in the templates and files folders, which the role can use.

  6. Metadata — in meta/main.yml, specify role dependencies and other information.

  7. Using the role — include the role in a playbook via the roles key.

  8. Testing and debugging — run the playbook with the role and check for correct execution.

Example of including a role in a playbook:

- hosts: all
  roles:
    - my_role

Thus, roles help structure configuration, reuse code, and simplify maintenance.