A complete, production-aligned Terraform starter blueprint that wires together ECR, S3, RDS (PostgreSQL), and ECS Fargate inside an enterprise landing zone, complete with least-privilege IAM roles, Security Group chaining, AWS Secrets Manager integration, and optional IAM Permissions Boundary support. It assumes that landing zone has already provisioned the VPC and subnets, and discovers them automatically via tags. =============================================================================== Key Enterprise Guardrails Built Into This Blueprint =============================================================================== Zero Hardcoded Credentials: manage_master_user_password = true tells RDS to create and manage the DB password inside AWS Secrets Manager, and the ECS Task Definition injects DB_USER and DB_PASSWORD at runtime. Strict IAM Separation: The ecs_execution role can read the DB secret and pull ECR images, while the ecs_task role can only read/write objects inside its own S3 bucket. Neither role can touch anything else in the account. Landing Zone Compatibility: Passing permissions_boundary_arn ensures the module passes strict enterprise SCPs that block IAM role creation without a boundary attached. Note on First Apply: Because aws_ecs_service starts desired_count = 1 pointing to :latest, push an initial Docker image to the created ECR repo (or temporarily set desired_count = 0 on the first run) so the Fargate task starts cleanly. =============================================================================== main.tf — Enterprise DEV Starter Blueprint =============================================================================== 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 ECS Fargate tasks" } variable "isolated_db_subnet_ids" { type = list(string) description = "Isolated subnets for RDS" } 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 # Helpful for DEV cleanup 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 # Helpful for DEV cleanup } 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 (Zero-Trust Chaining: ECS -> RDS) # ============================================================================== resource "aws_security_group" "ecs_tasks" { name = "${var.app_name}-dev-ecs-sg" description = "Outbound-only SG for ECS tasks" vpc_id = var.vpc_id egress { description = "Allow outbound HTTPS/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. 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" # Cost-effective for DEV allocated_storage = 20 storage_encrypted = true db_name = "appdb" username = "dbadmin" manage_master_user_password = true # Automatically creates & rotates secret in Secrets Manager 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 # Helpful for DEV teardown } # ============================================================================== # 5. 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"] } } } # A) ECS Task Execution Role (Used by AWS Fargate agent to pull image & read DB secret) 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[0].secret_arn] }] }) } # B) ECS Task Role (Used by your running application container to access S3) 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" Action = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"] Resource = ["${aws_s3_bucket.app_data.arn}/*"] } ] }) } # ============================================================================== # 6. ECS CLUSTER, LOGS & FARGATE SERVICE # ============================================================================== 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 environment = [ { 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 } ] # Securely injects RDS credentials from Secrets Manager as env vars secrets = [ { name = "DB_USER" valueFrom = "${aws_db_instance.postgres.master_user_secret[0].secret_arn}:username::" }, { name = "DB_PASSWORD" valueFrom = "${aws_db_instance.postgres.master_user_secret[0].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 } } # ============================================================================== # OUTPUTS # ============================================================================== 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 }