Skip to main content
AWS beginner Lesson 1 of 1

Deploying and Configuring AWS EC2 Instances

Launch virtual machines, configure security groups, assign IAM roles, and SSH into instances.

Amazon Elastic Compute Cloud (EC2) provides resizable computing capacity in the AWS Cloud. In this tutorial, we will learn how to launch and secure an EC2 instance.

Step 1: Security Groups (Firewall Configuration)

A Security Group acts as a virtual firewall that controls inbound and outbound traffic. By default, all inbound traffic is blocked.

We must open:

  • Port 22 (SSH) — restricted to our specific IP address.
  • Port 80 (HTTP) — open to the world.
  • Port 443 (HTTPS) — open to the world.

Step 2: Configuring the Instance via Terraform

Instead of using the AWS Console manually, write infrastructure as code (IaC) to launch instances reliably.

# main.tf
resource "aws_security_group" "web_sg" {
  name        = "web-server-sg"
  description = "Allow inbound SSH and HTTP traffic"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["203.0.113.50/32"] # Replace with your IP
  }

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

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

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0" # Ubuntu 20.04 LTS
  instance_type = "t3.micro"
  key_name      = "my-ssh-key"

  vpc_security_group_ids = [aws_security_group.web_sg.id]

  tags = {
    Name = "WebServer"
  }
}

Step 3: Accessing the Instance via SSH

Ensure the private key file has secure permissions (chmod 400), then log in:

# Secure the key file permissions
chmod 400 my-ssh-key.pem

# SSH into the server using the public IP
ssh -i "my-ssh-key.pem" ubuntu@ec2-54-210-45-12.compute-1.amazonaws.com