# Create VPC
resource "aws_vpc" "example" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
tags = {
Name = "example-vpc"
}
}
# Create public subnets
resource "aws_subnet" "public" {
count = 2
vpc_id = aws_vpc.example.id
cidr_block = "10.0.${count.index}.0/24"
availability_zone = "us-west-2a"
map_public_ip_on_launch = true
tags = {
Name = "example-public-${count.index+1}"
}
}
# Create private subnets
resource "aws_subnet" "private" {
count = 2
vpc_id = aws_vpc.example.id
cidr_block = "10.0.${count.index+2}.0/24"
availability_zone = "us-west-2a"
map_public_ip_on_launch = false
tags = {
Name = "example-private-${count.index+1}"
}
}
# Create security group for public subnets
resource "aws_security_group" "public" {
name = "public"
description = "Allow HTTP and HTTPS traffic"
vpc_id = aws_vpc.example.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
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"]
}
}
# Create security group for private subnets
resource "aws_security_group" "private" {
name = "private"
description = "Allow all traffic"
vpc_id = aws_vpc.example.id
ingress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
# Create Application Load Balancer
resource "aws_alb" "example" {
name = "example-alb"
internal = false
security_groups = [aws_security_group.alb.id]
subnets = [aws_subnet.public.id]
tags = {
Name = "example-alb"
}
}
# Create target group
resource "aws_alb_target_group" "example" {
name = "example-target-group"
port = 80
protocol = "HTTP"
vpc_id = aws_vpc.example.id
}
resource "aws_alb_target_group_attachment" "example" {
target_group_arn = aws_alb_target_group.example.arn
target_id = aws_instance.example.id
port = 80
}
resource "aws_alb_listener" "example" {
load_balancer_arn = aws_alb.example.arn
port = "80"
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_alb_target_group.example.arn
}
}