What is an Ansible Role—and how is it used?

Copy URL

An Ansible® Role is a self-contained, portable unit of Ansible automation that serves as the preferred method for grouping related tasks and associated variables, files, handlers, and other assets in a known file structure. While automation tasks can be written exclusively in an Ansible Playbook, Ansible Roles allow you to create bundles of automation content that can be run in 1 or more plays, reused across playbooks, and shared with other users in collections.

Ansible Roles are expressed in YAML—a human-readable data serialization language used to write configuration files. When a role is included in a task or a play, Ansible looks for a main.yml file in at least 1 of 8 standard role directories. These directories—depicted below with explanatory comments—include role tasks, handlers, modules, defaults, variables, files, templates, and meta.

roles/
    common/               # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
        handlers/         #
            main.yml      #  <-- handlers file
        templates/        #  <-- files for use with the template resource
            ntp.conf.j2   #  <------- templates end in .j2
        files/            #
            bar.txt       #  <-- files for use with the copy resource
            foo.sh        #  <-- script files for use with the script resource
        vars/             #
            main.yml      #  <-- variables associated with this role
        defaults/         #
            main.yml      #  <-- default lower priority variables for this role
        meta/             #
            main.yml      #  <-- role dependencies
        library/          # roles can also include custom modules
        module_utils/     # roles can also include custom module_utils
        lookup_plugins/   # or other types of plugins, like lookup in this case

    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""

You can use an Ansible Role by calling it in a playbook, either by listing it with the roles option or adding it in the role tasks section with the include_role or import_role commands. Roles listed with the roles option or added with import_role are run before any other tasks in a play, while roles added with include_role run in the order in which they are defined within the task list.

Learn more about Ansible Roles and how they're used

Red Hat resources

Ansible Roles and Ansible Playbooks are both tools for organizing and executing automation tasks, but each serves a different purpose. Whether you choose to create Ansible Roles or write all of your tasks in an Ansible Playbook depends on your specific use case and your experience with Ansible.

Most automation developers and system administrators begin creating automation content with individual playbooks. A playbook is a list of automation tasks that execute for a defined inventory. Tasks can be organized into a play—a grouping of 1 or more tasks mapped to a specific host and executed in order. A playbook can contain 1 or more plays, offering a flexible mechanism for executing Ansible automation in a single file.

While playbooks are a powerful method for automating with Ansible, writing all of your tasks in a playbook isn’t always the best approach. In instances where scope and variables are complex and reusability is helpful, creating most of your automation content in Ansible Roles and calling them within a playbook may be the more appropriate choice.

The following example illustrates the use of a role, linux-systemr-roles.timesync, within a playbook. In this instance, over 4 tasks would be required to achieve what the single role accomplishes. 

- name: Manage timesync with 3 servers
  hosts: targets
  vars:
     timesync_ntp_servers:
        - hostname: foo.example.com
          iburst: true
        - hostname: bar.example.com
          iburst: true
        - hostname: baz.example.com
          iburst: true
  roles:
     - linux-system-roles.timesync

There are several benefits to using Ansible Roles instead of writing all of your automation content in a single playbook:

Reusability and sharing

Roles are designed to be reusable units of automation. Since roles help you separate logical groupings of automation tasks from the context of a single play or playbook, you can reuse them in multiple plays or across playbooks and share them for reuse in other projects.

Modularity

Using roles encourages a modular approach to automation, where each role is responsible for a specific piece of functionality. This approach makes it easier to understand, maintain, and troubleshoot automation code.

Organization

Ansible Roles provide a structured way to organize tasks, templates, files, and variables. This structure makes it easier to manage complex automation setups, as everything related to a specific role is contained within its directory.

Parameterization

Roles allow you to define default variables that can be overridden when the role is used in an Ansible Playbook. This makes it easier to tailor a role’s behavior to different environments or use cases without modifying the role itself.

Versioning and dependency management

Roles can be versioned, and you can specify role dependencies in a meta/main.yml file within a role. As a result, you can manage versions and dependencies explicitly, ensuring stability and consistency across different environments.

Testing

The structure of roles makes it easier to apply testing methodologies. You can write tests specific to a role, ensuring that it behaves as expected before integrating it into larger playbooks.

Simplicity

For larger or more complex projects, roles simplify the use of Ansible Playbooks. Instead of having a large playbook that includes all tasks, handlers, and templates, you can write a much more concise playbook that people can easily read and understand. This also makes it easier to identify roles for reuse in new projects—speeding up the time it takes to write automation content and simplifying workflows. 

You can create a new role with the ansible-galaxy role init role_name command, which will build   a directory that follows the standard role directory structure. Once you’ve verified the directory, you can define tasks, default variables, and other components. While not required for the role to function, you can also add documentation to a README.md file and in meta/main.yml.

Creating a new role may require more advanced experience with Ansible—and can be a challenge for teams still learning how to build automation content. To facilitate the creation of content, new and experienced automation developers can take advantage of Red Hat® Ansible Lightspeed with IBM watsonx Code Assistant, a generative AI service that provides code recommendations based on Ansible best practices. Using natural language prompts, you can describe the automation you wish to achieve, and receive single-task and multi-task content suggestions from Ansible Lightspeed with watsonx Code Assistant. The generated tasks can then be included within an Ansible Role or playbook.

Ansible Lightspeed with watsonx Code Assistant reduces the effort required to create, maintain, and improve the quality of Ansible code—leading to improved productivity and faster time to adoption. 

Explore learning resources to get started with Ansible Automation Platform

The ease of sharing Ansible Roles allows you to incorporate well-maintained, tested roles into your automation. Roles can be shared using these repositories:

  • Ansible Galaxy- A free repository for sharing roles and other Ansible content with the larger Ansible community. Roles can be uploaded to Ansible Galaxy via the command-line (CLI), whereas collections can be shared from the web interface. Since Ansible Galaxy is a community site, content is not vetted, certified, or supported by Red Hat.
  • Ansible automation hub- Included with a Red Hat Ansible Automation Platform subscription, Ansible automation hub is a central repository for finding, downloading, and sharing Ansible Content Collections. Ansible automation hub is hosted by Red Hat and contains both certified and validated content from Red Hat and our independent software vendor (ISV) partners.
  • Private automation hub- An on-premise repository, private automation hub allows organizations to manage, share, and curate content internally—just for your organization. You can share roles and other automation content within your enterprise, allowing teams to simplify workflows and accelerate automation. 

Red Hat Ansible Automation Platform is a unified platform engineered to help organizations accelerate, orchestrate, and innovate with automation. With your Red Hat subscription, you get access to Red Hat Certified Content Collections and Ansible validated content—all available in Ansible automation hub.

Also included with your subscription, Red Hat Ansible Lightspeed with IBM watsonx Code Assistant streamlines the process of writing and improving the tasks included in your Ansible Roles to help automation teams create content more efficiently. Fully integrated into Visual Studio Code, Ansible Lightspeed meets automation developers where they are—you can create Ansible Roles and playbooks aligned to best practices without ever needing to switch between development environments.

Ansible Lightspeed also offers content source matching capabilities, allowing you to check the source training data for the suggestions it provides and make better decisions when creating roles for your users. And with models trained on thousands of roles from the Ansible community and data points provided by Red Hat, Ansible Lightspeed helps you create and improve Ansible code with accuracy and transparency—allowing you to meet organizational demands and accelerate adoption.

Learn more about choosing Red Hat for automation

Hub

The official Red Hat blog

Get the latest information about our ecosystem of customers, partners, and communities.

All Red Hat product trials

Our no-cost product trials help you gain hands-on experience, prepare for a certification, or assess if a product is right for your organization.

Keep reading

What is access control?

Access control is a security authorization technique that determines what specific resources a user or system can view or engage with in an IT infrastructure.

Why choose Red Hat Ansible Automation Platform as your AI foundation?

Red Hat® Ansible® Automation Platform establishes a solid foundation for AI implementations by simplifying the deployment, management, configuration, and lifecycle of AI models and infrastructure components.

What is virtual infrastructure management? And how can automation help?

Virtual infrastructure management is the coordination of software, IT resources, and other tools to manage virtual machines and related IT environments throughout their entire lifecycle.

Automation and management resources

Featured product

Related articles