Creating ansible roles for configuring web server and load balancer and use them for dynamic update of IPs of new servers added

First add a role path in your config file of ansible. I have added /ws20. so, this folder would contain all the roles that i would create.

Now, first step is to initialize the role. command for this is given below👇

ansible-galaxy role init role_name_you_want_to_give

similarly initialize one more role for web server

Both roles would come in the directory that you gave in the roles path as shown below. Infact all roles that you create comes here👇

✨Now let’s configure myapache role so that when it is run, it will configure all the IPs present in inventory with apache web server✨

You have to put index.html file or any file you want to put to be in your web server in the files folder of role.

Now lets configure the myloadbalancer role

configure the main.yml file as shown above

As you can see that you need haproxy.cfg file also. how to get it ?

Easy! Just manually install haproxy in your system using command yum install haproxy. Then go to folder /etc/haproxy and here you can find your file.

Now, copy this file in the templates folder of your role so that we can upload it in the managed nodes.

Now write in your main file of tasks as shown below👇

Now one important thing. since we want that new IPs that we have automatically get added in cfg file of haproxy, so we have to fetch them from the inventory.

For this we will take help of jinja and do some changes in the haproxy.cfg file which you can see as below👇

🎇This loop would fetch all the IPs that you have in the myweb group of your ip database. whenever you want to add a new server, just update the ip in this group and it would be added in the cfg file before it uploads to managed node.🎇

Also, i have added the load balancer ip in mylb group.

Now, create an ansible playbook including both these roles as shown below. I have made it with the name setup.yml👇

Now time to run the playbook

(ip 109 is not reachable as i randomly added to show)

Now see your haproxy file in the system and you can find out the IPs that you put in your ip database👇

Now if you add more IPs and again run playbook, it would automatically come in your haproxy file dynamically🔥

I have also made collection of these roles present on ansible galaxy on the below link. you can check the code take reference or directly use it👇

Below is the github link for reference👇


Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store