---
title: "Understanding and Setting up Ansible Roles [Tutorial]"
description: "Learn how Ansible Roles can help eliminate the struggle of deploying multiple sets of configuration in this tutorial!"
canonical: "https://adamtheautomator.com/ansible-roles/"
---

# Understanding and Setting up Ansible Roles [Tutorial]

> Learn how Ansible Roles can help eliminate the struggle of deploying multiple sets of configuration in this tutorial!

Source: https://adamtheautomator.com/ansible-roles/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Understanding and Setting up Ansible Roles \[Tutorial\]](https://adamtheautomator.com/wp-content/uploads/2021/09/Understanding-and-Setting-up-Ansible-Roles-Tutorial.jpg)

# Understanding and Setting up Ansible Roles \[Tutorial\]

[![](https://secure.gravatar.com/avatar/2beb65fca997135120ed98dc6a2e57dcdf1a7d7d2f5ff687b5d91dc7ccd7a6b5?s=192&d=mm&r=g)Sagar](https://adamtheautomator.com/author/shanky-mendiratta/)16 September 20217 min. read

Categories: [DevOps](/category/devops/)

Tags:[Ansible](/tag/ansible/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Ansible Roles: High Level](#ansible-roles-high-level)
*   [Setting up the Tomcat Ansible Role File Structure](#setting-up-the-tomcat-ansible-role-file-structure)
*   [Configuring the Tomcat Ansible Role](#configuring-the-tomcat-ansible-role)
*   [Running the Ansible Playbook with the Tomcat Ansible Role](#running-the-ansible-playbook-with-the-tomcat-ansible-role)
*   [Verifying Apache Tomcat Web Page](#verifying-apache-tomcat-web-page)
*   [Conclusion](#conclusion)

If you’re looking for a way to deploy a standard set of configurations to multiple nodes using [Ansible](https://en.wikipedia.org/wiki/Ansible_\(software\)), [Ansible roles](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html#roles) are a great choice. Ansible roles allow you to re-use standard configurations and make the deployment pretty quick and easier.

In this tutorial, you’re going to learn everything about Ansible Roles and how to set them up!

## Prerequisites

This post will be a step-by-step tutorial on Ansible roles. If you’d like to follow along, be sure you have the following in place:

*   An [Ansible controller host](https://docs.ansible.com/ansible/latest/installation_guide/index.html) – This tutorial will be using Ansible v2.9.24 on an [Ubuntu](https://adamtheautomator.com/install-ansible/) 18.04.5 LTS machine. You can confirm your Ansible version by running `Ansible --version`.

Related:[How to Setup Ansible (Ubuntu, RHEL, CentOS, macOS)](https://adamtheautomator.com/install-ansible/)

*   A [user account](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks.html) on the Ansible controller host will allow you to create [playbooks](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_intro.html#running-playbooks) and run them on a managed node.
*   A remote computer to run commands on.

## Ansible Roles: High Level

When organizations find themselves with dozens of applications or sets of configurations to manage, they soon start to see the need to make the process easier. Ansible roles can help.

Roles allow you to load related vars, files, tasks, handlers automatically, and other packages according to a common application or group. [Ansible stores roles in different directories](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html#role-directory-structure), and each role contains standard directories depending on the application’s requirements.

Below, you can see a diagram of the `APP1` Ansible role file structure containing the standard directories such as tasks, handlers, etc.

![Viewing Ansible Role Structure's Diagram](https://adamtheautomator.com/wp-content/uploads/2021/09/image-110.png)

Viewing Ansible Role Structure’s Diagram

## Setting up the Tomcat Ansible Role File Structure

Enough theory! Let’s now dive into the demo to set up an Ansible role. For this example, you’ll deploy the [Apache Tomcat](https://tomcat.apache.org/) on a remote server using the [ansible-playbook](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks.html) command.

Related: [Creating and Running Ansible Windows Playbooks](https://adamtheautomator.com/ansible-on-windows/#Creating_and_Running_Ansible_Windows_Playbooks)

1\. SSH into your Ansible controller host.

2\. Create a directory named _~/ansible\_role\_demo_ in your home directory and change to that folder as the working directory. The _~/ansible\_role\_demo_ directory will hold this tutorials’ demo files.

```bash
mkdir ~/ansible_role_demo
cd ~/ansible_role_demo
```

3\. Next, run the command below to create another directory named _roles_ inside the _~/ansible\_role\_demo_ directory. The _~/ansible\_role\_demo/roles_ directory will contain the Tomat role that you need to deploy.

> _By default, Ansible looks for roles in two locations in a directory called roles/ within the directory where playbook resides or in the /etc/ansible/roles. If you wish to store roles at different paths, [declare the paths using the `- role:` parameter in the playbook](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html)._

```bash
mkdir -p roles
```

4\. Run the commands below to change the directory to the _~/ansible\_role\_demo/roles_ directory (`cd roles`), and create the folders required by the role.

The `p` flag tells the `mkdir` command to create the parent directory (`tomcat`) and the folders such as tasks, handlers, defaults, vars, and templates. Each of these folders is common for every Ansible role. These folders will eventually contain a _main.yml_ to deploy the Tomcat role.

> _You can create the role with any name within the role directory._

```bash
	cd roles
  mkdir -p tomcat/{tasks,handlers,defaults,vars,templates}
```

Each folder has a specific purpose:

*   **tasks**: The _task_ directory contains the list of tasks that a role needs to execute. All the tasks should be defined within the _main.yml_ file inside the task directory.
*   **handlers**: Handlers are like normal tasks in an Ansible playbook, but they run only if the task contains a “notify” directive. Handlers are used within a particular role or even anywhere outside this role and are defined in the _main.yml_ file.
*   **library**: If you need to declare any plugins or modules such as Python code, you must store them in the _main.yml_ file of the _library_ directory.
*   **files**: If you need to copy any files from the Ansible controller host to other nodes, you must place all your files inside the _files_ folder.
*   **templates**: [Templates](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_module.html) that the role deploys. A template is a file that contains all your configuration parameters, but the dynamic values are given as variables in the Ansible.

Related:[How to Create Ansible Templates to Save Configuration Time](https://adamtheautomator.com/ansible-template/)

*   **vars**: The _vars_ directory contains all the variables you need to use in the _main.yml_ file in the _tasks_ directory. Variables are also declared in the _main.yml_ file within the _vars_ directory.
*   **defaults:** The _defaults_ directory stores the variables that are required by the role to execute.
*   **meta**: If there are any role dependencies, then they are declared within the _meta_ directory.

5\. Finally, run the `tree` command to verify all of the required folders in the roles directory.

![Verifying the files under the roles folder](https://adamtheautomator.com/wp-content/uploads/2021/09/image-111.png)

Verifying the files under the roles folder

## Configuring the Tomcat Ansible Role

Next, let’s add all the files and code that you will need for the Tomcat Ansible role that will be used to deploy Tomcat on the destination node.

1\. Create the _~/ansible\_role\_demo/roles/tomcat/tasks/main.yml_ file and copy/paste the below code.

The playbook below installs the Tomcat Java dependency, downloads, installs, and configures Tomcat to start up automatically on the node it’s run on.

```yaml
---
# Installing the Java (Open Jdk) 
- name: Install Java 1.8
  apt: name=openjdk-8-jdk

# Adding the group tomcat
- name: add group "tomcat"
  group: name=tomcat

# Adding the user tomcat
- name: add user "tomcat"
  user: name=tomcat group=tomcat home=/usr/share/tomcat createhome=no
  become: True
  become_method: sudo

# Downloading the tomcat package
- name: Download Tomcat
  get_url: 
     url:  "{{ tomcat_download_url }}"
     dest: "{{ tomcat_download_location }}"

# Creating the tomcat directory
- name: Create a tomcat directory
  file:
    path: /usr/share/tomcat
    state: directory
    owner: tomcat
    group: tomcat

# Extracting the tomcat archive 
- name: Extract tomcat archive
  unarchive:
    src: "{{ tomcat_download_location }}"
    dest: /usr/share/tomcat
    owner: tomcat
    group: tomcat
    remote_src: yes
    extra_opts: "--strip-components=1"
    creates: /usr/share/tomcat/bin

# Copying the tomcat template file to the destination node
- name: Copy tomcat service file
  template:
    src: templates/tomcat.service.j2
    dest: /etc/systemd/system/tomcat.service
  when: ansible_service_mgr == "systems"

# Starting and Enabling the tomcat service on the destination node.
- name: Start and enable tomcat
  service:
    daemon_reload: yes
    name: tomcat
    state: started
    enabled: yes
  when: ansible_service_mgr == "systemd"
```

2\. Similarly, create another file named _~/ansible\_role\_demo/roles/tomcat/vars/main.yml_ and copy/paste the below code.

The code below contains the variables `tomcat_download_url` and `tomcat_download_location` with assigned values that Ansible role picks from _~/ansible\_role\_demo/roles/tomcat/tasks/main.yml_ while running the playbook.

```yaml
tomcat_download_url: http://archive.apache.org/dist/tomcat/tomcat-7/v7.0.61/bin/apache-tomcat-7.0.61.tar.gz
tomcat_download_location: /usr/share/tomcat/apache-tomcat-7.0.61.tar.gz
```

3\. Lastly, create a template file _~/ansible\_role\_demo/roles/tomcat/templates/tomcat.service.j2_ and copy/paste the below code.

The below template contains multiple sections:

*   `Unit` – Unit defines the name of the service you need to deploy, which is Tomcat.
*   `Service` – In the service section, you need to define the type of service which is forking. Forking allows you to start the tomcat service as a system start-up and keeps the service running in the background.
*   `Environment` – Environment contains the list of environment variables, such as `JAVA_HOME`, etc., that Tomcat requires to run.
*   `Install` – The Install section defines if the specified Unit is enabled or disabled. `WantedBY`enables the defined unit, which automatically starts the Tomcat at boot up.

Below, the _tomcat. service.j2_ template is rendered when you execute the playbook. The data from the template is then copied to the destination node in the _/etc/systemd/system/tomcat.service_ directory.

```bash
[Unit]
Description=Tomcat
After=network.target

[Service]
Type=forking

User=tomcat
Group=tomcat

Environment=JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
Environment=CATALINA_HOME=/usr/share/tomcat
Environment=CATALINA_BASE=/usr/share/tomcat
Environment=CATALINA_PID=/usr/share/tomcat/temp/tomcat.pid

ExecStart=/usr/share/tomcat/bin/startup.sh
ExecStop=/usr/share/tomcat/bin/shutdown.sh

[Install]
	WantedBy=multi-user.target
```

## Running the Ansible Playbook with the Tomcat Ansible Role

You’ve managed to set up and configure the Ansible role file structure, and files/folder within the Tomcat Ansible role. But unless you run the playbook, the role that you created previously is not doing anything.

Let’s quickly deploy the Ansible role!

1\. Create a YML file with a name you prefer, and copy/paste the below code. For this example, the file is named _~/ansible\_role\_demo/tomcat-setup.yml._

The code below deploys the Ansible role (`tomcat`) that you configured earlier to the destination server address (`192.168.1.5`) with the remote user (`ubuntu`) that has admin access.

> _You can use roles in [three ways](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html#using-roles): [At the play level](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html#using-roles-at-the-play-level) with the `roles` option. At the [tasks level](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html#including-roles-dynamic-reuse) with the [include\_role](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html#including-roles-dynamic-reuse) and with [import\_role](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_reuse_roles.html#importing-roles-static-reuse) options._

```bash
- name: Tomcat deployment playbook
  hosts: 192.168.1.5
  remote_user: ubuntu
  roles:
    - tomcat
```

2\. Run the `tree` command as you did earlier to verify all required files are in the _~/ansible\_role\_demo/_ directory.

In the below image, you should see all the _main.yml_ files are in the _handlers_, _tasks_, and _vars_ folders.

![Verifying the files under the ansible\_role\_demo folder](https://adamtheautomator.com/wp-content/uploads/2021/09/image-112.png)

Verifying the files under the _ansible\_role\_demo_ folder

3\. Finally, execute the [`ansible-playbook`](https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_intro.html#running-playbooks) command below to deploy the Tomcat Ansible role to the destination server address defined in the `hosts` section of the playbook (`192.168.1.5`).

```bash
ansible-playbook tomcat-setup.yml
```

Notice below that the Tomcat Ansible role has successfully been deployed on the remote host.

![Executing the Ansible Playbook](https://adamtheautomator.com/wp-content/uploads/2021/09/image-113.png)

Executing the Ansible Playbook

## Verifying Apache Tomcat Web Page

How do you know that Apache Tomcat is actually running? A default web page is available to verify that the Tomcat is correctly running with the service started.

To access the Apache Tomcat default web interface, open a web browser and navigate to <_Remote-server:8080>._ You’ll see a similar page to the one shown below.

![Verifying Apache Tomcat Web Page is Running](https://adamtheautomator.com/wp-content/uploads/2021/09/image-114.png)

Verifying Apache Tomcat Web Page is Running

## Conclusion

In this tutorial, you learned how to set up an example Ansible roles and deploy them with Ansible. Ansible roles can prevent code duplication and allow you to deploy sets of configurations rather than reinventing the wheel each time.

With this newfound knowledge, which application do you plan to deploy next using an Ansible Role?

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fansible-roles%2F&text=Understanding%20and%20Setting%20up%20Ansible%20Roles%20%5BTutorial%5D)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fansible-roles%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fansible-roles%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2021/04/A-Step-by-Step-Guide-to-Getting-Started-with-Ansible-on-Windows.jpg)

### [Mastering Ansible on Windows: Your Go-To Expert Guide](/ansible-on-windows/)

Ansible on Windows made simple. A complete guide to hassle-free installation and configuration, perfect for users seeking quick and effective mastery.

![](https://adamtheautomator.com/wp-content/uploads/2022/10/How-to-Manage-Python-Libraries-with-Ansible-Pip.jpg)

### [How to Manage Python Libraries with Ansible Pip](/ansible-pip/)

Learn how to effectively manage Python libraries with the Ansible Pip module and take control of your Python dependencies!

![](https://adamtheautomator.com/wp-content/uploads/2022/06/Highly-Effective-Automation-with-Ansible-AWX.jpg)

### [Highly Effective Automation with Ansible AWX](/ansible-awx/)

Learn how Ansible AWX can take your Ansible playbooks to the next level and automate all the things with this ATA Learning tutorial!

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
