Ansible Roles: Directory Structure

Hi readers, in this blog we will be discussing about Ansible roles and the directory structure used in Ansible. Above all, we will be looking at what different directories in a role do and how they can be created.

What are Ansible Roles?

The role is the primary mechanism for breaking a playbook into multiple files. Therefore, this simplifies writing complex playbooks, and it makes them easier to reuse. The breaking of playbook allows you to logically break the playbook into reusable components.

Directory Structure:

To create a role using the ansible-galaxy command, we can simply use the below syntax in our terminal:

ansible-galaxy init <ROLE_NAME>

Running this command will give us a basic directory structure in our current working directory and this directory structure will be like the one below:

├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── tasks
│ └── main.yml
├── templates
├── tests
│ ├── inventory
│ └── test.yml
└── vars
└── main.yml

These many number of files and directories may appear to be difficult to work with, but they are fairly easy to understand. Above all, we always have the freedom to write our tasks and variable into other files but we must include directives into the directory’s main.yml file. Let us look into the use of these different directories in our role.









Creating a Simple Ansible Role:

Setting Up Our Ansible Role:

ansible-galaxy init apt_update

We will then get the following as our console output:

- Role apt_update was created successfully

Creating Our Tasks:

# tasks file for apt_update
- apt:
name: "*"
state: latest

We will be adding the above information to our tasks/main.yml file.

Since, we are looking to make a simple role, we are going to skip adding any variables, templates or files for now. We will move on to creating a playbook which will include this role.

Creating Our Playbook:

- hosts: something
become: yes
- /full_path_to_role/galaxy/apt_update

Note that this playbook can be anywhere on our system and does not necessarily have to be in the same directory where our role is situated.

Running Our Playbook:

ansible-playbook apt_update_playbook.yml


Group of smart Engineers with a Product mindset who partner with your business to drive competitive advantage |