user_data.Before starting, ensure you have:
EC2FullAccessIAMFullAccessVPCFullAccess
terraform-ec2/
│── main.tf
│── variables.tf
│── outputs.tf
│── provider.tf
│── user_data.sh
│── terraform.tfvars # (Optional: Contains variable values)
provider.tf)This file configures Terraform to use AWS as the provider.
provider "aws" {
region = var.aws_region
}
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"
}
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"]
}
}
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
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
}
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://
To delete the EC2 instance and security group:
terraform destroy -auto-approve
user_dataNow you can deploy and manage infrastructure efficiently using Terraform! 🚀