Provisioning an EC2 Instance with Terraform & Configuring a Web Server

Objective

1. Prerequisites

Before starting, ensure you have:

2. Project Structure

terraform-ec2/
│── main.tf
│── variables.tf
│── outputs.tf
│── provider.tf
│── user_data.sh
│── terraform.tfvars  # (Optional: Contains variable values)
    

3. Implementation

Step 1: Provider Configuration (provider.tf)

This file configures Terraform to use AWS as the provider.

provider "aws" {
  region = var.aws_region
}
    

Step 2: Define Variables (variables.tf)

variable "aws_region" {
  description = "AWS region for EC2 instance"
  default     = "us-east-1"
}

variable "instance_type" {
  description = "EC2 instance type"
  default     = "t2.micro"
}

variable "key_name" {
  description = "Name of the existing AWS key pair"
  default     = "my-key"
}

variable "ami_id" {
  description = "Amazon Machine Image (AMI) for EC2"
  default     = "ami-0c55b159cbfafe1f0"
}
    

Step 3: EC2 Instance Configuration (main.tf)

resource "aws_instance" "web_server" {
  ami             = var.ami_id
  instance_type   = var.instance_type
  key_name        = var.key_name
  security_groups = [aws_security_group.web_sg.name]
  
  user_data = file("user_data.sh")

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

# Security Group
resource "aws_security_group" "web_sg" {
  name        = "web-sg"
  description = "Allow SSH and HTTP"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"] # Allow SSH from anywhere (restrict in production)
  }

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"] # Allow HTTP from anywhere
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
    

Step 4: User Data Script for Web Server (user_data.sh)

This script installs Apache, enables it, and deploys a simple webpage.

#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "

Deployed using Terraform

" > /var/www/html/index.html

Step 5: Outputs (outputs.tf)

output "instance_id" {
  description = "The ID of the EC2 instance"
  value       = aws_instance.web_server.id
}

output "public_ip" {
  description = "Public IP of the EC2 instance"
  value       = aws_instance.web_server.public_ip
}
    

Step 6: Terraform Commands to Deploy

1. Initialize Terraform

terraform init

2. Validate the configuration

terraform validate

3. Plan the deployment

terraform plan

4. Apply the configuration

terraform apply -auto-approve

5. Access the Web Server Once the instance is deployed, get its public IP from the Terraform output.

curl http://

Step 7: Destroy the Infrastructure

To delete the EC2 instance and security group:

terraform destroy -auto-approve
    

Summary

Now you can deploy and manage infrastructure efficiently using Terraform! 🚀