π Terraform Series β Day 6
Deploy EC2 with VPC, Security Group & SSH Access (Full Hands-On)

π― Objective
In this hands-on, we will:
Generate SSH key
Create key pair using Terraform
Configure VPC & Security Group
Launch EC2 instance
Connect via SSH
Clean up resources
π This is your first real-world Terraform task
π§© Step 1: Generate SSH Key
ssh-keygen
β This creates:
terra-key-awsβ Private keyterra-key-ec2.pubβ Public key
π We will use this to access EC2
π Step 2: Create Terraform File
touch ec2.tf
π§± Step 3: Add Terraform Code
# Create Key Pair
resource "aws_key_pair" "my_key" {
key_name = "terra-key-aws"
public_key = file("terra-key-aws.pub")
}
# Default VPC
resource "aws_default_vpc" "default" {}
# Security Group
resource "aws_security_group" "my_groups" {
name = "my-group"
description = "Security group for EC2"
vpc_id = aws_default_vpc.default.id
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
description = "Allow SSH"
}
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
description = "Allow HTTP"
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
description = "Allow all outbound"
}
tags = {
Name = "automate-sg"
}
}
# EC2 Instance
resource "aws_instance" "my_instance" {
ami = "ami-0cb91c7de36eed2cb"
instance_type = "t2.micro"
key_name = aws_key_pair.my_key.key_name
vpc_security_group_ids = [aws_security_group.my_groups.id]
root_block_device {
volume_size = 10
volume_type = "gp3"
}
tags = {
Name = "terra-ec2"
}
}
βοΈ Step 4: Initialize Terraform
terraform init
β Downloads AWS provider
β Prepares working directory
β Step 5: Validate Configuration
terraform validate
β Ensures syntax is correct
π Step 6: Plan Execution
terraform plan
β Shows resources to be created:
Key Pair
VPC
Security Group
EC2 Instance
π Step 7: Apply (Create Infrastructure)
terraform apply
π Type yes to confirm
β Common Error: Not Authorized
π Reason:
- IAM user does not have required permissions
β Fix:
Go to AWS IAM β Attach Policy
AdministratorAccess(easy way)OR
EC2FullAccessVPCFullAccess
π₯ Step 8: Verify in AWS Console
Go to EC2 Dashboard:
β Instance running
β Security group attached
β Key pair created
π Step 9: Fix Key Permission
chmod 400 terra-key-aws
π Required before SSH
π Step 10: Connect to EC2
ssh -i terra-key-aws ubuntu@<your-public-ip>
π Now your server is live π
π§Ή Step 11: Destroy Resources (IMPORTANT)
terraform destroy
π Prevent unnecessary AWS charges πΈ
π¨βπ» About the Author
βA complete Terraform series covering everything from fundamentals to advanced real-world infrastructure automation in a DevOps environment.β
π¬ Let's Stay Connected
π§ Email: gujjarapurv181@gmail.com
π GitHub: github.com/ApurvGujjar07
πΌ LinkedIn: linkedin.com/in/apurv-gujjar





