Here is a Terraform project that deploys a full stack web app on AWS:
# Configure the AWS Provider
provider "aws" {
region = "us-east-1"
}
# Create a VPC
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
}
# Create an ECS cluster
resource "aws_ecs_cluster" "main" {
name = "main"
}
# Create an ECS task definition for the backend
resource "aws_ecs_task_definition" "backend" {
family = "backend"
container_definitions = jsonencode([
{
name = "backend"
image = "backend:latest"
cpu = 256
memory = 512
essential = true
portMappings = [
{
containerPort = 8000
hostPort = 8000
}
]
}
])
}
# Create an ECS service for the backend
resource "aws_ecs_service" "backend" {
name = "backend"
cluster = aws_ecs_cluster.main.id
task_definition = aws_ecs_task_definition.backend.arn
desired_count = 3
}
# Create an Application Load Balancer to route traffic to the backend
resource "aws_alb" "main" {
name = "main"
internal = false
load_balancer_type = "application"
subnets = aws_subnet.public.*.id
security_groups = [
aws_security_group.lb.id
]
}
# Create a target group and listener for the backend
resource "aws_alb_target_group" "backend" {
name = "backend"
port = 8000
protocol = "HTTP"
vpc_id = aws_vpc.main.id
}
resource "aws_alb_listener" "backend" {
load_balancer_arn = aws_alb.main.id
port = "80"
protocol = "HTTP"
default_action {
target_group_arn = aws_alb_target_group.backend.id
type = "forward"
}
}
# Create an S3 bucket for frontend hosting
resource "aws_s3_bucket" "frontend" {
bucket = "frontend"
acl = "public-read"
}
# Create a CloudFront distribution for the S3 bucket
resource "aws_cloudfront_distribution" "s3_distribution" {
origin {
domain_name = aws_s3_bucket.frontend.bucket_regional_domain_name
origin_id = aws_s3_bucket.frontend.id
}
enabled = true
default_root_object = "index.html"
default_cache_behavior {
allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
cached_methods = ["GET", "HEAD"]
target_origin_id = aws_s3_bucket.frontend.id
forwarded_values {
query_string = false
cookies {
forward = "none"
}
}
viewer_protocol_policy = "allow-all"
min_ttl = 0
default_ttl = 3600
max_ttl = 86400
}
}
# Create an RDS Postgres database
resource "aws_db_instance" "postgres" {
engine = "postgres"
instance_class = "db.t2.micro"
}
This deploys:
- An ECS cluster running a backend service
- An Application Load Balancer routing traffic to the backend
- An S3 bucket hosting a frontend
- A CloudFront distribution serving the S3 bucket
- An RDS Postgres database
Let me know if you have any questions!