* [Topics](/en/topics "Topics")
* [Automation and management](/en/topics/automation "Automation and management")
* What is an Ansible Role—and how is it used?
What is an Ansible Role—and how is it used?
===========================================
Published  January 8, 2024•*7*-minute read
Copy URL
Jump to section
---------------
OverviewHow do Ansible Roles work?Why use a role instead of a playbook?Creating an Ansible RoleSharing Ansible RolesWhy Red Hat?
Overview
--------
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.
How do Ansible Roles work?
--------------------------
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](/en/topics/automation/what-is-an-ansible-module), 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](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html#role-directory-structure)
Recommended for you
Automate CyberArk activities with the Ansible Automation Platform’s Event-Driven Ansible
----------------------------------------------------------------------------------------
[Watch the webinar](https://www.redhat.com/en/events/webinar/automate-cyberaark-activities-ansible-automation-platforms-event-driven-ansible?percmp=RHCTG0250000455235)
Why use an Ansible Role instead of an Ansible Playbook?
-------------------------------------------------------
Ansible Roles and [Ansible Playbooks](/en/topics/automation/what-is-an-ansible-playbook) 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](https://galaxy.ansible.com/ui/standalone/roles/linux-system-roles/timesync/documentation/), 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.
Creating an Ansible Role
------------------------
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](/en/technologies/management/ansible/ansible-lightspeed), 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](/en/technologies/management/ansible/learn)
Sharing Ansible Roles
---------------------
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](/en/technologies/management/ansible/automation-hub) is a central repository for finding, downloading, and sharing [Ansible Content Collections](/en/technologies/management/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.
Why Red Hat?
------------
[Red Hat Ansible Automation Platform](/en/technologies/management/ansible) 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](/en/technologies/management/ansible/ansible-lightspeed) 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](/en/topics/automation/why-choose-red-hat-for-automation "article | Why choose Red Hat for automation?")
Recommended for you
E-book
The automation architect's handbook
-----------------------------------
Learn about how to lead your company's end-to-end automation journey.
[Read the e-book](https://www.redhat.com/en/engage/automation-architect-handbook-ebook?percmp=RHCTG0250000455234)
Recommended for you
Developing Advanced Automation with Red Hat Ansible Automation Platform and exam
--------------------------------------------------------------------------------
This course teaches you advanced Ansible skills, helping you design, operate, and scale your automation.
[View course with exam](https://www.redhat.com/en/services/training/developing-advanced-automation-red-hat-ansible-automation-platform-and-exam-au375?percmp=RHCTG0250000455236)
Keep reading
------------
### What is IT service management (ITSM)?
IT service management (ITSM) refers to the activities IT teams perform to ensure that IT services meet customer needs and contribute to business goals.
[Read the article](/en/topics/automation/what-is-it-service-management-itsm "article | what is IT service management (ITSM)?")
### What is Infrastructure as Code (IaC)?
Infrastructure as Code (IaC) is the managing and provisioning of infrastructure through code instead of through manual processes.
[Read the article](/en/topics/automation/what-is-infrastructure-as-code-iac "article | What is Infrastructure as Code?")
### What is a configuration management database (CMDB)?
A configuration management database (CMDB) is used to manage information about IT components, including their attributes and relationships between them.
[Read the article](/en/topics/automation/what-is-a-configuration-management-database-cmdb "article | what is a configuration management database (CMDB)?")
Automation and management resources
-----------------------------------
### Featured product
* #### [Red Hat Ansible Automation Platform](/en/technologies/management/ansible)
  A platform for implementing enterprise-wide automation, no matter where you are in your automation journey.
[See all products](/en/technologies/all-products "See all products")
### Related content
* Blog post
  [Introducing the Red Hat Ansible Lightspeed intelligent assistant](/en/blog/evolution-red-hat-ansible-lightspeed)
* Blog post
  [Slash VM provisioning time on Red Hat Openshift Virtualization using Red Hat Ansible Automation Platform](/en/blog/accelerate-it-service-delivery-red-hats-integrated-toolset)
* Blog post
  [Red Hat Ansible Automation Platform: Measuring Business Impact with Dashboard and Analytics](/en/blog/red-hat-ansible-automation-platform-measuring-business-impact-dashboard-and-analytics)
* Datasheet
  [Red Hat Ansible Automation Platform](/en/resources/ansible-automation-platform-datasheet)
### Related articles
* [What is DevOps automation?](/en/topics/automation/what-is-devops-automation)
* [What is IT service management (ITSM)?](/en/topics/automation/what-is-it-service-management-itsm)
* [What is Infrastructure as Code (IaC)?](/en/topics/automation/what-is-infrastructure-as-code-iac)
* [Ansible vs. Kubernetes: how they work together](/en/topics/automation/Ansible-vs-Kubernetes)
* [What is a configuration management database (CMDB)?](/en/topics/automation/what-is-a-configuration-management-database-cmdb)
* [What is cloud migration? And how can automation help?](/en/topics/automation/what-is-cloud-migration)
* [What is a software-defined data center (SDDC)?](/en/topics/automation/what-is-a-sddc)
* [What is IT automation?](/en/topics/automation/what-is-it-automation)
* [Why choose Red Hat Ansible Automation Platform as your AI foundation?](/en/topics/automation/automation-and-ai)
* [How to build an IT automation strategy](/en/topics/automation/build-an-automation-strategy)
* [What is access control?](/en/topics/security/what-is-access-control)
* [What is virtual infrastructure management? And how can automation help?](/en/topics/automation/virtual-infrastructure-management)
* [What is IT migration?](/en/topics/automation/what-is-it-migration)
* [How to automate migrations with Red Hat Ansible Automation Platform](/en/technologies/management/ansible/automate-migrations-with-red-hat-ansible-automation-platform)
* [Why use Red Hat Ansible Automation Platform with Red Hat OpenShift?](/en/technologies/cloud-computing/openshift/ansible-on-openshift)
* [What is CloudOps?](/en/topics/automation/what-is-cloudops)
* [Red Hat Satellite on Red Hat Enterprise Linux](/en/technologies/management/satellite/satellite-for-rhel)
* [What is role-based access control (RBAC)?](/en/topics/security/what-is-role-based-access-control)
* [Which Red Hat Ansible Automation Platform deployment option is right for you?](/en/technologies/management/ansible/ansible-deployment-options)
* [What is an Ansible module—and how does it work?](/en/topics/automation/what-is-an-ansible-module)
* [How to manage and automate applications at the edge](/en/topics/edge-computing/how-to-manage-automate-applications-edge)
* [How to build an automation Center of Excellence](/en/topics/automation/how-to-build-automation-center-of-excellence)
* [What is orchestration?](/en/topics/automation/what-is-orchestration)
* [How to adopt Automation as Code: Extending Infrastructure as Code into Policy as Code](/en/topics/automation/how-to-adopt-automation-as-code)
* [What is a webhook?](/en/topics/automation/what-is-a-webhook)
* [Learning Ansible basics](/en/topics/automation/learning-ansible-tutorial)
* [Red Hat Lightspeed data and application security](/en/topics/management/data-application-security)
* [What is data management?](/en/topics/data-services/what-is-data-management)
* [Gain security with Red Hat Ansible Automation Platform](/en/technologies/management/ansible/gain-security-with-red-hat-ansible-automation-platform)
* [What is NetOps?](/en/topics/automation/what-is-netops)
* [What is an Ansible Rulebook?](/en/topics/automation/what-is-an-ansible-rulebook)
* [What is an Ansible Playbook?](/en/topics/automation/what-is-an-ansible-playbook)
* [What is configuration management](/en/topics/automation/what-is-configuration-management)
* [What is event-driven automation?](/en/topics/automation/what-is-event-driven-automation)
* [Zero-Touch Provisioning and telco automation with Red Hat](/en/topics/telecommunications/zero-touch-provisioning-and-telco-automation-at-red-hat)
* [What is infrastructure automation?](/en/topics/automation/what-is-infrastructure-automation)
* [What is YAML?](/en/topics/automation/what-is-yaml)
* [What is provisioning?](/en/topics/automation/what-is-provisioning)
* [What is compliance management?](/en/topics/management/what-is-compliance-management)
* [Understanding Ansible, Terraform, Puppet, Chef, and Salt](/en/topics/automation/understanding-ansible-vs-terraform-puppet-chef-and-salt)
* [What is cloud orchestration?](/en/topics/automation/what-is-cloud-orchestration)
* [Ansible vs. Chef: What you need to know](/en/topics/automation/ansible-vs-chef)
* [What is security automation?](/en/topics/automation/what-is-security-automation)
* [Ansible vs. Salt: What you need to know](/en/topics/automation/ansible-vs-salt)
* [What is a configuration file?](/en/topics/linux/what-configuration-file)
* [Ansible vs. Puppet: What you need to know](/en/topics/automation/ansible-vs-puppet)
* [Ansible vs. Terraform, clarified](/en/topics/automation/ansible-vs-terraform)
* [Why choose Red Hat for automation?](/en/topics/automation/why-choose-red-hat-for-automation)
* [Ansible vs. Red Hat Ansible Automation Platform](/en/technologies/management/ansible/ansible-vs-red-hat-ansible-automation-platform)
* [What is cloud automation?](/en/topics/automation/what-is-cloud-automation)
* [What is network automation?](/en/topics/automation/what-is-network-automation)
* [What are managed IT services?](/en/topics/cloud-computing/what-are-managed-it-services)
* [What is business process management?](/en/topics/automation/what-is-business-process-management)
* [What is patch management (and automation)?](/en/topics/management/what-patch-management-and-automation)
* [What is the Red Hat Ansible Automation Platform automation controller?](/en/technologies/management/ansible/automation-controller-product-feature)
* [What is SOAR?](/en/topics/security/what-is-soar)
* [What is business process automation?](/en/topics/automation/what-is-business-process-automation)
* [What is IT process automation?](/en/topics/automation/what-is-it-process-automation)
* [Automating Microsoft Windows with Red Hat Ansible Automation Platform](/en/technologies/management/ansible/automate-microsoft-windows-with-ansible)
* [What is deployment automation?](/en/topics/automation/what-is-deployment-automation)
* [What is business optimization?](/en/topics/automation/business-optimization)
* [What is Kubernetes cluster management?](/en/topics/containers/what-is-kubernetes-cluster-management)
* [What is SRE?](/en/topics/devops/what-is-sre)
* [What is risk management?](/en/topics/management/what-is-risk-management)
* [What is robotic process automation (RPA?)](/en/topics/automation/what-is-robotic-process-automation)
* [What is network management?](/en/topics/management/what-is-network-management)
* [What is an SOE?](/en/topics/management/what-is-an-soe)
* [What is IT system life-cycle management?](/en/topics/management/it-system-life-cycle-management)
* [What is cloud management?](/en/topics/cloud-computing/what-is-cloud-management)
* [What's business automation?](/en/topics/automation/whats-business-automation)
[More about this topic](/en/topics/automation "More about this topic")