DEV Community

Shankar Thejaswi
Shankar Thejaswi

Posted on

Automating EC2 Deployment with Terraform, Ansible, and Shell Script

Introduction

Infrastructure automation is key to efficient DevOps practices. Two of the most powerful tools for Infrastructure as Code (IaC) are Terraform and Ansible. Terraform is great for provisioning infrastructure, while Ansible excels at configuration management. In this blog, we'll see how to deploy an EC2 instance using Terraform and then configure it using Ansible—all orchestrated by a simple shell script.

Prerequisites

Before we begin, ensure you have the following installed on your local machine:

  • AWS CLI (configured with necessary credentials)
  • Terraform
  • Ansible
  • SSH Key Pair (for connecting to EC2 instance)

Step 1: Writing the Terraform Script

Terraform will be used to provision the EC2 instance.

main.tf

provider "aws" {
  region = "us-east-1"
}

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0" # Example AMI (Change as per requirement)
  instance_type = "t2.micro"
  key_name      = "your-key-pair"

  tags = {
    Name = "Terraform-EC2"
  }
}

output "instance_ip" {
  value = aws_instance.web.public_ip
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Writing the Ansible Playbook

Once the EC2 instance is up, Ansible will configure it.

playbook.yml

- name: Configure EC2 instance
  hosts: all
  become: yes
  tasks:
    - name: Install Apache
      apt:
        name: apache2
        state: present

    - name: Start Apache
      service:
        name: apache2
        state: started
Enter fullscreen mode Exit fullscreen mode

Step 3: Writing the Shell Script

A shell script will automate Terraform execution and Ansible deployment.

deploy.sh

#!/bin/bash

# Initialize Terraform
terraform init

# Apply Terraform and capture instance IP
terraform apply -auto-approve > output.txt

# Extract IP address
INSTANCE_IP=$(grep -oP '(?<=instance_ip = )[^ ]+' output.txt)

echo "EC2 Instance IP: $INSTANCE_IP"

# Wait for instance to be ready
sleep 30

# Add instance to Ansible inventory
echo "[web]" > inventory
echo "$INSTANCE_IP ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/your-key.pem" >> inventory

# Run Ansible playbook
ansible-playbook -i inventory playbook.yml
Enter fullscreen mode Exit fullscreen mode

Step 4: Running the Script
Make the script executable and run it:

chmod +x deploy.sh
./deploy.sh
Enter fullscreen mode Exit fullscreen mode

Conclusion
This setup automates EC2 provisioning with Terraform and configuration management with Ansible using a shell script. It eliminates manual intervention, ensuring a smooth, repeatable, and scalable deployment process. Happy automating!

Top comments (0)