Creating and Using Roles in Ansible

Creating and Using Roles in Ansible

Introduction

In Ansible, roles are a powerful way to organize and reuse automation logic in a modular and structured manner. Let's explore the process of creating and using roles with examples to understand their functionality better.

Creating a Role

To create a role, we'll follow a specific directory structure and define tasks, handlers, and variables within the role directory.

Example: Let's create a role named web_server to install and configure Apache web server.

  1. Role Directory Structure:

     roles/
     └── web_server/
         ├── tasks/
         │   └── main.yml
         ├── handlers/
         │   └── main.yml
         ├── vars/
         │   └── main.yml
         └── defaults/
             └── main.yml
    
  2. Defining Tasks and Handlers:

    tasks/main.yml:

     ---
     - name: Install Apache
       apt:
         name: apache2
         state: present
    
     - name: Start Apache service
       service:
         name: apache2
         state: started
    

    handlers/main.yml:

     ---
     - name: Restart Apache service
       service:
         name: apache2
         state: restarted
    
  3. Managing Variables:

    vars/main.yml:

     ---
     apache_port: 80
    
  4. Defining Defaults:

    defaults/main.yml:

     ---
     apache_default_index: index.html
    

Using the Role

Once the role is created, we can use it in a playbook by including its name under the roles key.

Example: Let's create a playbook web_server_playbook.yml to use the web_server role.

web_server_playbook.yml:

---
- name: Configure Web Server
  hosts: web_servers
  become: yes
  roles:
    - web_server

In this example:

  • The playbook includes the web_server role.

  • It specifies that the role should be applied to hosts in the web_servers group.

  • The become: yes statement ensures that tasks within the role are executed with elevated privileges.

Conclusion

Creating and using roles in Ansible follows a structured approach, allowing for modular and reusable automation logic. By defining tasks, handlers, variables, and defaults within a role directory, users can encapsulate related automation logic and apply it to different playbooks and projects efficiently.