Creating Ansible Roles for haproxy and httpd

What is an Ansible role?

Ansible role is an independent component that allows the reuse of common configuration steps. It is a set of tasks to configure a host to serve a certain purpose like configuring a service. Roles are defined using YAML files with a predefined directory structure.

STEP1: Creating the role for Apache webserver.

We can create a new role by ansible-galaxy init httpd

Contents of a Role
---
# tasks file for httpd
- name: "installing the packages"
package:
name: "{{item}}"
state: present
loop:
- httpd
- php
- name: "Copying the webpage"
template:
src: index.php.j2
dest: "/var/www/html/index.php"
- name: "Copying essential"
template:
src: index.html.j2
dest: "/var/www/html/index.html"
- name: "Starting the service"
service:
name: httpd
state: started
index.html
index.php

STEP 2: Creating a role for haproxy server

We can initialize it by the command ansible-galaxy init haproxy

---
# tasks file for haproxy
- name: "Installing package"
package:
name: haproxy
state: present
- name: "Configuring the services"
template:
src: haproxy.cfg.j2
dest: "/etc/haproxy/haproxy.cfg"
- name: "Starting the service"
service:
name: haproxy
state: started
haproxy.cfg

STEP 3: Launching ec2 instances over AWS

Our final goal was to launch this setup over the AWS instance. So we can create instances either by ansible-playbook or by ansible roles. Here to make it simple I am using a playbook.

- hosts: localhost
vars_files: "/etc/ansible/aws_key.yml"
tasks:
- name: "Creating a new ec2"
ec2:
key_name: "[[ Key }}"
instance_type: "t2.micro"
image: "ami-0742b4e673072066f"
wait: yes
count: 1
instance_tags:
Name: aws_ansible_ec2
vpc_subnet_id: "{{ subent }}"
assign_public_ip: yes
region: "us-east-1"
state: present
group_id: "[[ sg }}"
aws_access_key: "{{ Access_key }}"
aws_secret_key: "{{ Secret_key }}"
register: ec2
- debug:
var: ec2.instances[0].public_ip
- blockinfile:
path: "/etc/ansible/NEW/ip"
block: |
[web]
"{{ ec2.instances[0].public_ip }}"

STEP 4: Final step

To run all the roles and the scripts we need one master script. By running that master script all the configuration will be done automatically.

- hosts: web
roles:
- httpd
- hosts: ec2
roles:
- haproxy
~

RESULT:

--

--

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