Sobes.tech
Junior — Middle

What is the difference between roles and groups in Ansible and how to use them correctly?

sobes.tech AI

Answer from AI

In Ansible, roles and groups serve different purposes and are used for organizing infrastructure and code.

  • Roles are a way to structure and reuse Ansible code. A role contains a set of tasks, files, templates, variables, and handlers grouped by functional aspect. Roles allow dividing configuration into logical blocks, which simplifies maintenance and scaling.

    Example of a role structure:

    roles/
      webserver/
        tasks/
        handlers/
        templates/
        files/
        vars/
    
  • Groups are a way to organize hosts in the inventory file. Groups allow applying settings, variables, and roles to specific sets of servers. For example, you can create a db_servers group for all databases and assign appropriate variables.

Proper usage:

  • Use groups for logical grouping of servers by functions, environments, or other criteria.
  • Use roles for organizing and reusing configurations and tasks.

For example, in a playbook, you can apply a role to a group of hosts:

- hosts: webservers
  roles:
    - webserver

Thus, groups control which machines have what applied, and roles define what exactly is applied.

What is the difference between roles and groups in… - sobes.tech