# provider block - create resources in AWS provider "aws" { region = "us-east-1" } # VPC (virtual private cloud) - private network inside AWS module "vpc" { source = "terraform-aws-modules/vpc/aws" version = "5.0.0" name = "ecommerce-vpc" cidr = "10.0.0.0/16" azs = ["us-east-1a", "us-east-1b"] public_subnets = ["10.0.1.0/24", "10.0.2.0/24"] private_subnets = ["10.0.3.0/24", "10.0.4.0/24"] } # RDS - PostgreSQL module "db" { source = "terraform-aws-modules/rds/aws" identifier = "ecom-db" engine = "postgres" instance_class = "db.t3.micro" # CPU / memory class allocated_storage = 20 # 20 GB disk username = var.db_username password = var.db_password vpc_security_group_ids = [module.vpc.default_security_group_id] # place db into private subnet subnet_ids = module.vpc.private_subnets } # ECS (Elastic Container Service) Fargate cluster for running containers # (managed container orchestrator) resource "aws_ecs_cluster" "ecommerce" { name = "ecom-cluster" } # task definition resource "aws_ecs_task_definition" "frontend" { family = "frontend-app" requires_compatibilities = ["FARGATE"] network_mode = "awsvpc" cpu = "256" memory = "512" container_definitions = jsonencode([ { name = "frontend" image = "myshop/frontend:latest" portMappings = [ { containerPort = 80, hostPort = 80 } ] } ]) } # service definition resource "aws_ecs_service" "frontend_service" { name = "frontend-service" cluster = aws_ecs_cluster.ecommerce.id task_definition = aws_ecs_task_definition.frontend.arn desired_count = 2 # number of container instances running launch_type = "FARGATE" network_configuration { subnets = module.vpc.public_subnets security_groups = [aws_security_group.ecs_sg.id] assign_public_ip = true } } resource "aws_security_group" "ecs_sg" { name = "ecs-sg" vpc_id = module.vpc.vpc_id description = "Allow HTTP traffic to ECS" 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"] } }