Dive into my detailed guide on setting up a robust web infrastructure on AWS using Terraform. Walk through the step-by-step process, from VPC creation to launching an Ubuntu server.
# Configure the AWS Provider
provider "aws" {
region = "us-east-1"
access_key = "XXxxxxxxxxxxxxxxxX"
secret_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
#create VPC
resource "aws_vpc" "prod-vpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "production"
}
}
#create Internet gateway
resource "aws_internet_gateway" "gw" {
vpc_id = aws_vpc.prod-vpc.id
}
#Create a Route table
resource "aws_route_table" "prod-route-table" {
vpc_id = aws_vpc.prod-vpc.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.gw.id
}
route {
ipv6_cidr_block = "::/0"
egress_only_gateway_id = aws_egress_only_internet_gateway.eigw.id
}
tags = {
Name = "prod"
}
}
#Create an Egress Only Internet Gateway
resource "aws_egress_only_internet_gateway" "eigw" {
vpc_id = aws_vpc.prod-vpc.id
}
#Create a subnet
resource "aws_subnet" "subnet-1" {
vpc_id = aws_vpc.prod-vpc.id
cidr_block = "10.0.1.0/24"
availability_zone = "us-east-1a"
tags = {
Name = "prod-subnet"
}
}
#Associate subnet with route table
resource "aws_route_table_association" "a" {
subnet_id = aws_subnet.subnet-1.id
route_table_id = aws_route_table.prod-route-table.id
}
#Create a security group to allow port 22,80. 443
resource "aws_security_group" "allow_web" {
name = "allow_web_traffic"
description = "Allow web inbound traffic"
vpc_id = aws_vpc.prod-vpc.id
ingress {
description = "HTTPS"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
}
ingress {
description = "HTTP"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
}
ingress {
description = "SSH"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
}
tags = {
Name = "allow_web"
}
}
#Create Network interface
resource "aws_network_interface" "web-server-tosin" {
subnet_id = aws_subnet.subnet-1.id
private_ips = ["10.0.1.51"]
security_groups = [aws_security_group.allow_web.id]
}
resource "aws_eip" "one" {
domain = "vpc"
network_interface = aws_network_interface.web-server-tosin.id
associate_with_private_ip = "10.0.1.51"
depends_on = [ aws_internet_gateway.gw ]
}
#Create Ubuntu Server
resource "aws_instance" "web-server-instance" {
ami = "ami-0fc5d935ebf8bc3bc"
instance_type = "t2.micro"
availability_zone = "us-east-1a"
key_name = "training"
network_interface {
device_index = 0
network_interface_id = aws_network_interface.web-server-tosin.id
}
user_data = <<-EOF
#!/bin/bash
sudo apt update -y
sudo apt install apache2 -y
sudo systemctl start apache2
sudo bash -c 'echo "Tosin Web Server using Terraform" > /var/www/html/index.html'
EOF
tags = {
Name = "web-server"
}
}