Ansible Roles

Girish Yadav
4 min readDec 31, 2020

Roles provide a framework for fully independent or interdependent collections of files, tasks, templates, variables, and modules.

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

Each role is limited to a particular functionality or desired output, with all the necessary steps to provide that result either within the same role itself or in other roles listed as dependencies.

Roles are not playbooks. Roles are small functionality that can be used within the playbooks independently. Roles have no specific setting for which hosts the role will apply.

Top-level playbooks are the bridge holding the hosts from your inventory file to roles that should be applied to those hosts.

Reusability Of Ansible Roles

Ansible Roles are independent of each other. Execution of one role doesn’t depend on others and hence they can be reused. You can even modify and personalize these roles according to your requirements. This reduces our task to rewrite an entire section of code every time we need it, thus simplifying our work.

Let’s get started…

Task Description📄

🔅Create an ansible role myapache to configure Httpd WebServer.

🔅Create another ansible role myloadbalancer to configure HAProxy LB.

🔅We need to combine both of these roles controlling webserver versions and solving challenge for host ip’s addition dynamically over each Managed Node in HAProxy.cfg file.

Role for Webserver :-

Step 1: Create role for webserver

#ansible-galaxy role init myapache

Step 2: Update the path of role in the ansible.cfg file

Role Directory:

Step 4: Now we have to write in the files directory what we want to use.

Creating index.php in the files directory

Step 5: Writing tasks in main.yml in the tasks directory

Step 6: Writing variables in main.yml in the vars directory

Role for Load Balancer:-

Step 1: Create role for Load Balancer

#ansible-galaxy role init loadbalancer

Step2: For configuring the Load Balancer, We need to configure the file (haproxy.cfg ) of haproxy. So, we have to put the template of haproxy.cfg in the template directory.

Step:3 Adding tasks

Step4: Adding Handlers

Now,

Combining both roles (myapache and loadbalancer) by creating setup.yml playbook

Running the playbook named setup.yml

#ansible-playbook setup.yml

Playbook runs successfully..

Lets check…..

Its working Great !!!

Thank you for reading !!!

--

--