Terraform blueprint with an internal Application Load Balancer (ALB) in front of your ECS Fargate service, complete with three-tier Security Group chaining (Internal ALB -> ECS Tasks -> RDS). Internal ALB (internal = true): Placed inside your private application subnets so it is only reachable inside your VPC or over your enterprise Transit Gateway / VPN—never exposed to the public internet. Three-Tier Security Group Chaining: 1. alb-sg accepts HTTP (80) or HTTPS (443) from your internal corporate/VPC CIDR range. 2. ecs-sg accepts container port traffic (8080) strictly from alb-sg. 3. rds-sg accepts PostgreSQL (5432) strictly from ecs-sg. Health Checks & Port Mapping: Configured the ECS Task Definition, Target Group, and ECS Service to register tasks dynamically on port 8080 with /health checks. Compliance Built-In: `drop_invalid_header_fields = true` and `ELBSecurityPolicy-TLS13-1-2-2021-06` are included because AWS Config / Security Hub rules in enterprise landing zones routinely flag ALBs missing those settings. Custom Internal Domain: If your landing zone provides a private Route 53 Hosted Zone (e.g. `dev.internal.company.com`), add an `aws_route53_record` `A` alias pointing to `aws_lb.internal.dns_name`. # ============================================================================== main.tf — Enterprise DEV Blueprint with Internal ALB # ============================================================================== hcl terraform { required_version = ">= 1.5.0" required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } } provider "aws" { region = var.aws_region default_tags { tags = { Environment = "dev" Application = var.app_name ManagedBy = "terraform" } } } # ============================================================================== # VARIABLES (Inputs the DevOps Engineer Configures) # ============================================================================== variable "aws_region" { type = string default = "ap-south-1" } variable "app_name" { type = string description = "Unique name for the application (e.g., billing-api)" default = "sample-app" } variable "vpc_id" { type = string description = "VPC ID vended by the Enterprise Landing Zone" } variable "private_app_subnet_ids" { type = list(string) description = "Private subnets for Internal ALB and ECS Fargate tasks" } variable "isolated_db_subnet_ids" { type = list(string) description = "Isolated subnets for RDS" } variable "allowed_internal_cidrs" { type = list(string) description = "Internal VPC / corporate CIDRs allowed to reach the Internal ALB" default = ["10.0.0.0/8"] } variable "container_port" { type = number description = "Port exposed by your application container" default = 8080 } variable "acm_certificate_arn" { type = string description = "Optional: ACM certificate ARN to enable HTTPS (443) listener on Internal ALB" default = null } variable "permissions_boundary_arn" { type = string description = "Optional: Enterprise Landing Zone IAM Permissions Boundary ARN" default = null } data "aws_caller_identity" "current" {} # ============================================================================== # 1. ECR REPOSITORY (Container Registry) # ============================================================================== resource "aws_ecr_repository" "app" { name = "${var.app_name}-dev" image_tag_mutability = "IMMUTABLE" force_delete = true image_scanning_configuration { scan_on_push = true } encryption_configuration { encryption_type = "AES256" } } resource "aws_ecr_lifecycle_policy" "app" { repository = aws_ecr_repository.app.name policy = jsonencode({ rules = [{ rulePriority = 1 description = "Keep last 10 images in DEV" selection = { tagStatus = "any" countType = "imageCountMoreThan" countNumber = 10 } action = { type = "expire" } }] }) } # ============================================================================== # 2. S3 BUCKET (Application Storage - Locked Down) # ============================================================================== resource "aws_s3_bucket" "app_data" { bucket = "${var.app_name}-dev-${data.aws_caller_identity.current.account_id}" force_destroy = true } resource "aws_s3_bucket_public_access_block" "app_data" { bucket = aws_s3_bucket.app_data.id block_public_acls = true block_public_policy = true ignore_public_acls = true restrict_public_buckets = true } resource "aws_s3_bucket_server_side_encryption_configuration" "app_data" { bucket = aws_s3_bucket.app_data.id rule { apply_server_side_encryption_by_default { sse_algorithm = "AES256" } } } # ============================================================================== # 3. SECURITY GROUPS (3-Tier Chaining: Internal ALB -> ECS -> RDS) # ============================================================================== resource "aws_security_group" "alb" { name = "${var.app_name}-dev-alb-sg" description = "Internal ALB ingress from corporate/VPC CIDRs" vpc_id = var.vpc_id ingress { description = "HTTP from internal network" from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = var.allowed_internal_cidrs } dynamic "ingress" { for_each = var.acm_certificate_arn != null ? [1] : [] content { description = "HTTPS from internal network" from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = var.allowed_internal_cidrs } } egress { description = "Allow outbound traffic to ECS tasks" from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } } resource "aws_security_group" "ecs_tasks" { name = "${var.app_name}-dev-ecs-sg" description = "Allow container traffic strictly from Internal ALB" vpc_id = var.vpc_id ingress { description = "App traffic from Internal ALB" from_port = var.container_port to_port = var.container_port protocol = "tcp" security_groups = [aws_security_group.alb.id] } egress { description = "Allow outbound HTTPS (ECR/Secrets/S3) and DB traffic" from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } } resource "aws_security_group" "rds" { name = "${var.app_name}-dev-rds-sg" description = "Allow PostgreSQL strictly from ECS tasks SG" vpc_id = var.vpc_id ingress { description = "PostgreSQL from ECS" from_port = 5432 to_port = 5432 protocol = "tcp" security_groups = [aws_security_group.ecs_tasks.id] } } # ============================================================================== # 4. INTERNAL APPLICATION LOAD BALANCER & TARGET GROUP # ============================================================================== resource "aws_lb" "internal" { name = "${var.app_name}-dev-int-alb" internal = true load_balancer_type = "application" security_groups = [aws_security_group.alb.id] subnets = var.private_app_subnet_ids drop_invalid_header_fields = true # Security best practice for enterprise guardrails } resource "aws_lb_target_group" "app" { name = "${var.app_name}-dev-tg" port = var.container_port protocol = "HTTP" vpc_id = var.vpc_id target_type = "ip" # Required for Fargate awsvpc mode health_check { path = "/health" protocol = "HTTP" matcher = "200" interval = 30 timeout = 5 healthy_threshold = 2 unhealthy_threshold = 3 } } resource "aws_lb_listener" "http" { load_balancer_arn = aws_lb.internal.arn port = 80 protocol = "HTTP" default_action { type = "forward" target_group_arn = aws_lb_target_group.app.arn } } resource "aws_lb_listener" "https" { count = var.acm_certificate_arn != null ? 1 : 0 load_balancer_arn = aws_lb.internal.arn port = 443 protocol = "HTTPS" ssl_policy = "ELBSecurityPolicy-TLS13-1-2-2021-06" certificate_arn = var.acm_certificate_arn default_action { type = "forward" target_group_arn = aws_lb_target_group.app.arn } } # ============================================================================== # 5. RDS POSTGRESQL (With AWS-Managed Master Secret) # ============================================================================== resource "aws_db_subnet_group" "rds" { name = "${var.app_name}-dev-db-subnets" subnet_ids = var.isolated_db_subnet_ids } resource "aws_db_instance" "postgres" { identifier = "${var.app_name}-dev-db" engine = "postgres" engine_version = "16" instance_class = "db.t4g.micro" allocated_storage = 20 storage_encrypted = true db_name = "appdb" username = "dbadmin" manage_master_user_password = true db_subnet_group_name = aws_db_subnet_group.rds.name vpc_security_group_ids = [aws_security_group.rds.id] publicly_accessible = false skip_final_snapshot = true } # ============================================================================== # 6. LEAST-PRIVILEGE IAM ROLES (Execution Role vs. Task Role) # ============================================================================== data "aws_iam_policy_document" "ecs_assume_role" { statement { actions = ["sts:AssumeRole"] principals { type = "Service" identifiers = ["://amazonaws.com"] } } } resource "aws_iam_role" "ecs_execution" { name = "${var.app_name}-dev-ecs-exec-role" assume_role_policy = data.aws_iam_policy_document.ecs_assume_role.json permissions_boundary = var.permissions_boundary_arn } resource "aws_iam_role_policy_attachment" "ecs_execution_base" { role = aws_iam_role.ecs_execution.name policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy" } resource "aws_iam_role_policy" "ecs_execution_secrets" { name = "read-rds-secret" role = aws_iam_role.ecs_execution.id policy = jsonencode({ Version = "2012-10-17" Statement = [{ Effect = "Allow" Action = ["secretsmanager:GetSecretValue"] Resource = [aws_db_instance.postgres.master_user_secret.secret_arn] }] }) } resource "aws_iam_role" "ecs_task" { name = "${var.app_name}-dev-ecs-task-role" assume_role_policy = data.aws_iam_policy_document.ecs_assume_role.json permissions_boundary = var.permissions_boundary_arn } resource "aws_iam_role_policy" "ecs_task_s3" { name = "scoped-s3-access" role = aws_iam_role.ecs_task.id policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = ["s3:ListBucket"] Resource = [aws_s3_bucket.app_data.arn] }, { Effect = "Allow" Use code with caution. Action = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"] Resource = ["${aws_s3_bucket.app_data.arn}/*"] } ] }) } ============================================================================== 7. ECS CLUSTER, LOGS & FARGATE SERVICE (Wired to Internal ALB) ============================================================================== resource "aws_cloudwatch_log_group" "ecs" { name = "/ecs/${var.app_name}-dev" retention_in_days = 14 } resource "aws_ecs_cluster" "main" { name = "${var.app_name}-dev-cluster" } resource "aws_ecs_task_definition" "app" { family = "${var.app_name}-dev" network_mode = "awsvpc" requires_compatibilities = ["FARGATE"] cpu = "256" memory = "512" execution_role_arn = aws_iam_role.ecs_execution.arn task_role_arn = aws_iam_role.ecs_task.arn container_definitions = jsonencode([{ name = "app" image = "${aws_ecr_repository.app.repository_url}:latest" essential = true portMappings = [{ containerPort = var.container_port hostPort = var.container_port protocol = "tcp" }] environment = [ { name = "PORT", value = tostring(var.container_port) }, { name = "S3_BUCKET_NAME", value = aws_s3_bucket.app_data.bucket }, { name = "DB_HOST", value = aws_db_instance.postgres.address }, { name = "DB_NAME", value = aws_db_instance.postgres.db_name } ] secrets = [ { name = "DB_USER" valueFrom = "${aws_db_instance.postgres.master_user_secret.secret_arn}:username::" }, { name = "DB_PASSWORD" valueFrom = "${aws_db_instance.postgres.master_user_secret.secret_arn}:password::" } ] logConfiguration = { logDriver = "awslogs" options = { "awslogs-group" = aws_cloudwatch_log_group.ecs.name "awslogs-region" = var.aws_region "awslogs-stream-prefix" = "ecs" } } }]) } resource "aws_ecs_service" "app" { name = "${var.app_name}-dev-service" cluster = aws_ecs_cluster.main.id task_definition = aws_ecs_task_definition.app.arn desired_count = 1 launch_type = "FARGATE" network_configuration { subnets = var.private_app_subnet_ids security_groups = [aws_security_group.ecs_tasks.id] assign_public_ip = false } load_balancer { target_group_arn = aws_lb_target_group.app.arn container_name = "app" container_port = var.container_port } depends_on = [aws_lb_listener.http] } ============================================================================== OUTPUTS ============================================================================== output "internal_alb_dns_name" { description = "Internal DNS endpoint for the ALB" value = aws_lb.internal.dns_name } output "ecr_repository_url" { value = aws_ecr_repository.app.repository_url } output "s3_bucket_name" { value = aws_s3_bucket.app_data.bucket } output "rds_endpoint" { value = aws_db_instance.postgres.endpoint }