Getting Started with Ansible Roles

Inshiya Nalawala
3 min readApr 16, 2021

If you are familiar with Ansible — the amazing configuration management tool but haven’t yet played around Ansible roles, I must tell you that you are missing out the fun.

To help yourself overcome the struggle of managing huge tasks files with variables, handlers and templates, I recommend you reading this till end.

This blog will give a brief introduction to Ansible Roles and walk you through a simple yet elegant demonstration.

Ansible roles is the way you can separate your tasks, variables and related files in a nice file structure. The tasks for the end configuration to achieve is written in a separate file, associated variables in a separate file, the handlers to notify in a separate file and the files to copy in a different file. All of these are isolated but eventually make up a single transferable entity.

This is how the file structure looks like of any role (here ‘miao.emacs’)

Fig 1

In this blog, we will create a role to configure a webserver and subsequently configure a load balancer to balance the load between the web servers.

Note: Update the roles_path variable in your ansible.cfg file to point to the directory where you want to keep your roles.

To begin, create two roles.

ansible-galaxy role init myapache

ansible-galaxy role init myloadbalancer

You will see two folders in your roles_path named ‘myapache’ and ‘myloadbalancer’. You will also see that the file structure inside these is same as shown in Fig 1.

Now, in the myapache/tasks/main.yml file and myloadbalcer/tasks/main.yml, write your tasks.

Here, I am copying a file(index.php) to managed nodes from the controller node, so that has to be kept in the files folder under corresponding role directory.

Similarly, using a jinja template(haproxy.cfg.j2), I am also updating the configuration file of the load balancer. hence, that file must be kept in the templates folder under corresponding role directory.

Also, the handlers are defined in a separate file.

Finally, create a setup.yml file to use the two roles and configure everything in one playbook run.

Doesn’t this look cleaner and readily understandable? Definitely, yes!

Do Clap for this article, if you found it interesting and helpful.

Thank you!

--

--