Configuring HAProxy on AWS Instances by using Ansible Dynamic Inventory

Sukesh Seth
3 min readDec 8, 2020

Ansible is an open-source automation tool, or platform, used for configuration management, application deployment, intra service setup, and provisioning. Automation is the need of today, with IT environments that are too complex and often need to scale too quickly for system administrators and developers to keep up if they had to do everything manually. Automation simplifies complex tasks. In other words, it frees up time and increases efficiency. And Ansible, as noted above, is rapidly rising to the top in the world of automation tools.

To configure Ansible refer to Ansible Configuration part of this article.

Creating Playbooks

  1. Edit the ansible.cfg file.

2. Install the boto and boto3 library of python.

pip3 install boto
pip3 install boto3

3. To perform actions on EC2 instances, we have to provide the key. Copy the key in the given location same as given in ansible.cfg file.

change the format of the key: # chmod 600 <keyname.pem>

Defining roles:

  • Ansible roles are basically a collection of files, tasks, templates, variables, and modules. It is used for breaking a playbook into multiple files. This will help you to write a complex playbook and make it easier to reuse.
  • If you have worked with any programming language or script you probably know that you could write a large script or a program in a single file or you can categorize into Packages, Modules, Classes, and Functions that way you code become more organized, reusable, and easy to read. This is implemented in Ansible with the help of roles.

To create a role:

# ansible-galaxy init <role_name>

To check the all roles, present in roles path:

# ansible-galaxy list

Here, we will be using four roles:

  1. ec2Launch: This one will launch the EC2 Instances.
  2. addHost: This role will add webservers’ & loadbalancer’s IPs to the host group dynamically.

2. webConfig: This role will configure the instances as webserver.

3. lbConfig: This role will configure one instance as a haproxy server which act as a load balancer.

All of the roles, I have uploaded on my GitHub.

The directory tree will look something like this:

To play these roles, I have created one driver playbook “driver.yml”:

After the successful working of the playbook, you can check running instances in your AWS account.

The webpage can be accessed from:

http://<lb_ip>:8080

--

--