Detailed Terraform or CloudFormation template to deploy AWS architecture

Here is a sample Terraform script to deploy the Enterprise Microservices Architecture in AWS, including VPC, ECS, RDS, API Gateway, and Cognito for authentication.

This script provides: ✅ VPC Setup
ECS Cluster with Fargate
API Gateway for API Management
Cognito User Pool for Authentication
RDS (PostgreSQL) for Storage
Auto-scaling and Monitoring with CloudWatch

provider “aws” {
region = “us-east-1” # Change as needed
}

#

VPC & Subnets

#

resource “aws_vpc” “main” {
cidr_block = “10.0.0.0/16”
}

resource “aws_subnet” “public_subnet” {
vpc_id = aws_vpc.main.id
cidr_block = “10.0.1.0/24”
map_public_ip_on_launch = true
}

resource “aws_subnet” “private_subnet” {
vpc_id = aws_vpc.main.id
cidr_block = “10.0.2.0/24”
}

#

ECS Cluster & Task Definition

#

resource “aws_ecs_cluster” “microservices_cluster” {
name = “microservices-cluster”
}

resource “aws_ecs_task_definition” “app” {
family = “microservices-task”
network_mode = “awsvpc”
requires_compatibilities = [“FARGATE”]
cpu = “256”
memory = “512”
execution_role_arn = aws_iam_role.ecs_task_execution_role.arn

container_definitions = jsonencode([
{
name = “app-container”
image = “nginx” # Replace with your app image
cpu = 256
memory = 512
essential = true
portMappings = [
{
containerPort = 80
hostPort = 80
}
]
}
])
}

#

API Gateway

#

resource “aws_apigatewayv2_api” “api” {
name = “microservices-api”
protocol_type = “HTTP”
}

resource “aws_apigatewayv2_stage” “default” {
api_id = aws_apigatewayv2_api.api.id
name = “$default”
auto_deploy = true
}

#

Cognito Authentication

#

resource “aws_cognito_user_pool” “user_pool” {
name = “microservices-user-pool”
}

resource “aws_cognito_user_pool_client” “app_client” {
user_pool_id = aws_cognito_user_pool.user_pool.id
}

#

RDS Database

#

resource “aws_db_instance” “postgres” {
allocated_storage = 20
engine = “postgres”
engine_version = “13”
instance_class = “db.t3.micro”
username = “admin”
password = “SecurePass123” # Change this!
publicly_accessible = false
skip_final_snapshot = true
}

#

IAM Roles & Permissions

#

resource “aws_iam_role” “ecs_task_execution_role” {
name = “ecsTaskExecutionRole”

assume_role_policy = jsonencode({
Version = “2012-10-17”
Statement = [
{
Action = “sts:AssumeRole”
Effect = “Allow”
Principal = {
Service = “ecs-tasks.amazonaws.com”
}
}
]
})
}

resource “aws_iam_role_policy_attachment” “ecs_execution_policy” {
role = aws_iam_role.ecs_task_execution_role.name
policy_arn = “arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy”
}

#

Outputs

#

output “api_gateway_url” {
value = aws_apigatewayv2_api.api.api_endpoint
}

output “cognito_user_pool_id” {
value = aws_cognito_user_pool.user_pool.id
}

output “database_endpoint” {
value = aws_db_instance.postgres.endpoint
}