Jonatan Matajonmatum.com
conceptsnotesexperimentsessays
© 2026 Jonatan Mata. All rights reserved.v2.1.1
Experiments

Terraform AWS Serverless Modules

Collection of 13 Terraform modules published on the Terraform Registry for deploying serverless architectures on AWS, with 12 examples covering basic ECS to full-stack CRUD with DynamoDB and AgentCore with MCP.

evergreen#terraform#aws#serverless#ecs#lambda#api-gateway#dynamodb#well-architected#fargate#mcp#cloudfront#waf#sqs#sns

What it is

A collection of 13 reusable Terraform modules for deploying serverless architectures on AWS. Published on the Terraform Registry and available as open source on GitHub.

The project includes 12 complete examples — each with its own deploy.sh, architecture documentation, and ready-to-run Terraform code. Modules follow AWS Well-Architected Framework best practices: security, reliability, operational excellence, performance, and cost optimization.

Modules

The 13 modules cover the infrastructure needed for serverless and container-based applications:

ModuleDescriptionKey features
vpcMulti-AZ VPCNAT gateways, VPC endpoints, flow logs
ecrContainer registryEncryption, lifecycle policies, image scanning
ecsFargate serviceAuto-scaling, Container Insights, Spot
lambdaLambda functionsContainer images, DLQ, retry policies, alarms
albApplication Load BalancerAccess logs, HTTPS, health checks
sqsSQS message queuesFIFO, DLQ, encryption, long polling
snsSNS pub/subEmail, SQS, Lambda subscriptions, filtering
dynamodbDynamoDB NoSQLEncryption, PITR, auto-scaling
api-gatewayHTTP API (v2)Throttling, logging, X-Ray
api-gateway-v1REST API (v1)OpenAPI/Swagger, VPC Link
cloudfront-s3CDN + static hostingSPA routing, OAC, custom domains
wafWeb Application FirewallRate limiting, IP filtering, managed rules
cloudwatch-alarmsMonitoringCPU, memory, response time, error rates

Examples

The 12 examples are organized as a progressive learning path:

Foundations

ExamplePatternComponentsLink
ecs-appALB → ECSVPC, ALB, ECS, ECRcode
lambda-functionLambda Function URLLambda, ECR, CloudWatch, SNS, SQScode

API Gateway

ExamplePatternComponentsLink
rest-api-serviceREST API + VPC LinkAPI Gateway v1, NLB, ALB, ECScode
openapi-rest-apiREST API + SwaggerAPI Gateway v1, OpenAPI 3.0 → Swagger 2.0, ECScode
openapi-http-apiHTTP API + OpenAPIAPI Gateway v2, OpenAPI 3.0, ECScode

Full-stack CRUD

ExamplePatternComponentsLink
crud-api-restREST API + DynamoDB + ReactAPI Gateway v1, ECS, DynamoDB, CloudFront, WAFcode
crud-api-httpHTTP API + DynamoDB + ReactAPI Gateway v2, ECS, DynamoDB, CloudFrontcode

Messaging

ExamplePatternComponentsLink
sqs-queueLambda + SQS + DLQSQS FIFO, Dead Letter Queue, Lambdacode
sns-fanoutSNS → multiple SQSSNS Topic, attribute filtering, multiple queuescode

Advanced

ExamplePatternComponentsLink
api-gateway-multi-serviceMulti-serviceAPI Gateway, VPC Link, FastAPI + Node MCPcode
mcp-agent-runtimeMCP Server + AgentCoreECS, ALB, Bedrock AgentCore Gatewaycode
agentcore-fullFull AgentCoreECS, Lambda, SQS, SNS, OpenSearch, Bedrock Agentcode

Example: ECS with ALB

The most basic example — a FastAPI application behind an ALB on ECS Fargate:

Loading diagram...
module "vpc" {
  source = "jonmatum/serverless-modules/aws//modules/vpc"
 
  name               = "my-app-vpc"
  cidr               = "10.0.0.0/16"
  azs                = ["us-east-1a", "us-east-1b"]
  private_subnets    = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets     = ["10.0.101.0/24", "10.0.102.0/24"]
  enable_nat_gateway = true
  single_nat_gateway = true
}
 
module "alb" {
  source = "jonmatum/serverless-modules/aws//modules/alb"
 
  name              = "my-app-alb"
  vpc_id            = module.vpc.vpc_id
  subnet_ids        = module.vpc.public_subnet_ids
  target_port       = 8000
  health_check_path = "/health"
}
 
module "ecr" {
  source = "jonmatum/serverless-modules/aws//modules/ecr"
 
  repository_name = "my-app"
  scan_on_push    = true
}
 
module "ecs" {
  source = "jonmatum/serverless-modules/aws//modules/ecs"
 
  cluster_name              = "my-app-cluster"
  service_name              = "my-app-service"
  container_name            = "my-app"
  container_image           = "${module.ecr.repository_url}:latest"
  container_port            = 8000
  subnet_ids                = module.vpc.private_subnet_ids
  target_group_arn          = module.alb.target_group_arn
  enable_autoscaling        = true
  enable_container_insights = true
}

Example: CRUD API with HTTP API (v2)

Full-stack application with React, FastAPI, DynamoDB, and API Gateway HTTP API:

Loading diagram...
module "dynamodb" {
  source = "jonmatum/serverless-modules/aws//modules/dynamodb"
 
  table_name                    = "my-app-items"
  hash_key                      = "id"
  billing_mode                  = "PAY_PER_REQUEST"
  enable_point_in_time_recovery = true
  enable_encryption             = true
}
 
module "api_gateway" {
  source = "jonmatum/serverless-modules/aws//modules/api-gateway"
 
  name                        = "my-app-api"
  vpc_link_subnet_ids         = module.vpc.private_subnet_ids
  vpc_link_security_group_ids = [aws_security_group.vpc_link.id]
 
  integrations = {
    proxy = {
      method          = "ANY"
      route_key       = "ANY /{proxy+}"
      connection_type = "VPC_LINK"
      uri             = module.alb.listener_arn
    }
  }
 
  enable_access_logs  = true
  enable_xray_tracing = true
}
 
module "cloudfront" {
  source = "jonmatum/serverless-modules/aws//modules/cloudfront-s3"
 
  name           = "my-app-web"
  enable_logging = true
}

REST API vs HTTP API

A key decision when using API Gateway — the modules support both versions:

FeatureHTTP API (v2)REST API (v1)
Cost$1.00/million requests$3.50/million requests
VPC integrationDirect to ALBRequires intermediate NLB
LatencyLowerHigher (extra hop)
OpenAPIYesYes
CORSBuilt-inManual configuration
API Keys / Usage PlansNoYes
Request validationLimitedFull

Recommendation: use HTTP API (v2) unless you need API keys or usage plans. It is 71% cheaper with lower latency.

Well-Architected Framework

Every module implements AWS Well-Architected Framework best practices. The full document details each decision.

PillarImplementation
SecurityEncryption at rest/transit, IAM least-privilege, VPC endpoints, WAF
ReliabilityMulti-AZ, auto-scaling, health checks, DLQ, alarms
Operational excellenceContainer Insights, access logs, CloudWatch, pre-commit hooks
PerformanceFargate compute, VPC endpoints, CloudFront CDN
Cost optimizationFargate Spot, lifecycle policies, VPC endpoints, single NAT for dev

Production vs development configuration

# Production: Multi-AZ, On-Demand, auto-scaling
module "vpc" {
  source             = "jonmatum/serverless-modules/aws//modules/vpc"
  single_nat_gateway = false  # Multi-AZ NAT
  enable_vpc_endpoints = true
}
 
module "ecs" {
  source                   = "jonmatum/serverless-modules/aws//modules/ecs"
  enable_fargate_spot      = false
  enable_autoscaling       = true
  autoscaling_min_capacity = 2
  autoscaling_max_capacity = 10
  autoscaling_target_cpu   = 70
}
# Development: Single NAT, Spot, minimal capacity
module "vpc" {
  source             = "jonmatum/serverless-modules/aws//modules/vpc"
  single_nat_gateway = true
}
 
module "ecs" {
  source              = "jonmatum/serverless-modules/aws//modules/ecs"
  enable_fargate_spot = true
  desired_count       = 1
}

Estimated costs

EnvironmentMonthly costConfiguration
Development$70–90Single NAT, Fargate Spot, 1 task
Staging$150–200Single NAT, On-Demand, 2 tasks
Production$200–400Multi-AZ NAT, auto-scaling 2–10 tasks

Production breakdown: NAT Gateways (2×) ~$65/month, Fargate (2–10 tasks) ~$50–200/month, ALB ~$20/month, DynamoDB on-demand variable.

Deployment

Each example includes idempotent deployment scripts:

cd examples/ecs-app
./deploy.sh          # Initial deployment (Terraform + Docker build + push)
./redeploy.sh        # Redeploy after code changes
terraform destroy    # Destroy infrastructure

Modules support idempotent deployments — terraform apply && terraform destroy && terraform apply works without errors.

Why it matters

These modules solve a concrete problem: deploying serverless applications on AWS requires coordinating dozens of resources (VPC, subnets, NAT, ALB, ECS, IAM roles, security groups, CloudWatch) with configurations that must follow security and reliability best practices. Without reusable modules, every team reinvents these configurations — and frequently omits encryption, health checks, or auto-scaling. The collection reduces a production deployment from hundreds of lines of IaC to compositions of 5–10 modules with secure defaults.

References

  • GitHub Repository — Source code for all 13 modules and 12 examples.
  • Terraform Registry — Modules published on the official Terraform registry.
  • Well-Architected Documentation — Decision mapping to the Well-Architected Framework.
  • Examples Guide — Progressive learning path with 12 examples.
  • Terraform Modules — HashiCorp, 2024. Official Terraform modules documentation.
  • AWS Well-Architected Framework — AWS, 2024. Cloud architecture best practices framework.
  • AWS Fargate — AWS, 2024. Fargate documentation for ECS.
  • Amazon API Gateway HTTP APIs — AWS, 2024. HTTP API (v2) documentation.

Related content

  • Infrastructure as Code

    Practice of defining and managing infrastructure through versioned configuration files instead of manual processes. Foundation of modern operations automation.

  • Serverless

    Cloud computing model where the provider manages infrastructure automatically, allowing code execution without provisioning or managing servers, paying only for actual usage.

  • Terraform

    HashiCorp's Infrastructure as Code tool that enables defining, provisioning, and managing multi-cloud infrastructure through declarative HCL files.

  • AWS ECS

    AWS container orchestration service that runs and scales Docker applications without managing the underlying cluster infrastructure.

  • AWS Fargate

    Serverless compute engine for containers that eliminates server management, allowing Docker container execution paying only for consumed resources.

  • AWS API Gateway

    AWS managed service for creating, publishing, and managing REST, HTTP, and WebSocket APIs that act as entry points to Lambda functions and other backend services.

  • AWS Lambda

    AWS serverless compute service that runs code in response to events without provisioning or managing servers, automatically scaling from zero to thousands of concurrent executions.

  • AWS DynamoDB

    AWS serverless NoSQL database with single-digit millisecond latency at any scale, ideal for applications requiring high performance and automatic scalability.

  • AWS Well-Architected Framework

    AWS framework with six pillars of best practices for designing and operating reliable, secure, efficient, and cost-effective cloud systems.

  • AWS SQS

    AWS fully managed message queue service that decouples distributed application components, guaranteeing message delivery with unlimited scalability.

  • AWS SNS

    AWS pub/sub messaging service that distributes messages to multiple subscribers simultaneously, enabling fan-out patterns and notifications at scale.

  • Container Registries

    Repositories for storing, versioning, and distributing container images, from public registries like Docker Hub to private registries like ECR.

Experiments