Deploy Webserver on AWS EC2 Instance Through Ansible

Hiteshkoolwal
4 min readSep 6, 2020

Ansible is an open-source software provisioning, configuration management, and application-deployment tool enabling infrastructure as code.

Task Description

🔹 Create a Dynamic Inventory.

🔹 Launch an AWS instance with the help of ansible.

🔹 Retrieve the public IP which is allocated to the launched instance.

🔹 With the help of the retrieved Public IP configure the web server in the launched instance.

🔹 Dynamically Termination of Ec2 instance and Remove IP of instance from inventory file.

In these task we are going to solve one use case based on configuring a web server on AWS cloud and launching one web application by automating all the setup using Integration of Ansible with AWS Cloud .

GitHub Code: https://github.com/hitk6/Ansible-task2-conf-webserver-dynamically

Launching AWS Instance with Ansible

Install Boto library.

pip3 install boto
pip3 install boto3
pip3 intall botocore

  • Give details to configure ansible and inventory

wget https://raw.githubusercontent.com/ansible/ansible/stable-2.9/contrib/inventory/ec2.py

  • Export aws_secret_key and aws_access_key of iam user.
  • In first line of ec2.py change python to python3.
Dynamic inventory for ec2 instance

Launch an AWS instance with the help of ansible.

Make a playbook, to launch aws instance

Make a new security group with port no 80,22 open
Refer to ansible ec2 security group module

  • Launch a new ec2 instance
    id keyword in task makes it idempotent.

Refer Ansible ec2 module for better understanding of the task

Running the role

ansible-playbook ec2prov.yml

With the help of the retrieved Public IP configure the web server in the launched instance.

Instance is launched above, now configure webserver on running ec2 instance

  • Install webserver
  • Sending Configuration file of httpd using template module
  • Downloading webpage from GitHub
  • Added condition if template task is changed then notify the handler “start httpd”

Handlers code

Vars used in role

“httpd.conf.j2” file used in Template directory

Running ansible playbook and calling aws_conf role

vim conf.yml

Terminate EC2 instance and delete IP from inventory file Dynamically

This part was bit tricky

  • Here ec2 module is run twice.
  • First to fetch the instance id.
  • Secondly using the instance id to terminate the instance.

This module terminates what has been previously done dynamically.

The variables used in termination module

  • The values of access_key and secret_key we have to give
  • “my_id” variable is dynamically added here when we create a instance using ec2.prov.yml playbook.

Final run Terminate everything :)

--

--