ECSBuilder¶
Purpose¶
The ECSBuilder is a concrete implementation of the AbstractAWSResourceBuilder designed to create comprehensive AWS ECS (Elastic Container Service) infrastructure for containerized applications. This builder orchestrates the deployment of a complete production-ready stack including ECS Fargate services, Application Load Balancer with SSL termination, CloudWatch logging, IAM roles with least-privilege security, and Route53 DNS integration. Supports secure credential management through both AWS Secrets Manager and Systems Manager Parameter Store for enterprise-grade container deployments.
Dependencies¶
This builder requires the following AWS resources and permissions:
Required AWS Permissions¶
- ECS Management: Create and configure ECS clusters, services, and task definitions
- Fargate Operations: Deploy and manage serverless containers with Fargate capacity providers
- Application Load Balancer: Create ALB with listeners, target groups, and health checks
- VPC Operations: Deploy resources within VPC with private subnet configuration
- ECR Integration: Pull container images from Elastic Container Registry repositories
- IAM Role Management: Create and assign service roles for task execution and runtime permissions
- CloudWatch Logs: Create log groups and manage container logging streams
- Route53 DNS: Create A records and manage DNS routing
- Certificate Manager: Access SSL certificates for HTTPS termination
- Secrets Manager: Retrieve application secrets and credentials
- Systems Manager: Access Parameter Store for configuration values
- S3 Operations: Store and retrieve application artifacts and data
Foundation Dependencies¶
- VPC Infrastructure: Existing VPC with private subnets for secure container execution
- Security Groups: Pre-configured security groups for ALB and ECS service isolation
- ECR Repositories: Container registries with application images
- SSL Certificates: ACM certificates for HTTPS termination at load balancer
- Route53 Hosted Zones: DNS zones for domain routing and service discovery
- Secrets Management: Existing secrets in AWS Secrets Manager or Parameter Store
- S3 Buckets: Buckets containing environment configuration files
- IAM Infrastructure: Service-linked roles and policies for ECS operations
- Environment Configuration: Account and region mappings for multi-environment deployments
Configuration¶
The builder uses the EcsConfig model for the validation of your configuration and becomes the authoritative source of all ECS infrastructure settings.
Please check the also following models to have a detailed view on the configuration possibilities:
- AppParametersConfig model
- ContainerSecretConfig model
- EcsEfsConfig model
- EfsVolumeConfig model
- EfsMountPointConfig model
- EnvironmentFileConfig model
CDK Configuration Structure¶
Basic ECS Service Configuration¶
{
"cluster_name": "app-cluster",
"service_name": "app-service",
"use_iam_authentication": true,
"alb_name": "app-alb",
"alb_domain_prefix": "api",
"ecr_repo_base_name": "app-backend",
"application_port": 8000,
"admin_port": 8001,
"admin_active": true,
"health_check_path": "/health",
"health_check_cmd": "wget -q -O -",
"desired_count": 2,
"cpu": 512,
"memory_limit_mib": 1024,
"ssl_certificate_id": "arn:aws:acm:us-east-1:123456789012:certificate/abc123",
"eu_west_cloudront_prefix_list_id" : "pl-4fa04526",
"environment_files": [
{
"bucket_base_name": "app-config",
"file_path": "production/config.env"
},
{
"bucket_base_name": "shared-config",
"file_path": "common/database.env"
}
],
"efs_config": {
"container_user": "1000:1000",
"volumes": [{
"efs_parameter_key_suffix": "shared",
"volume_name": "shared-data",
"ap_parameter_key_suffix": "app_data"
}],
"mount_points": [{
"volume_name": "shared-data",
"container_path": "/app/data",
"read_only": false
}]
},
"route53": {
"hosted_zone_id": "Z1D633PJN98FT9",
"domain_name": "example.com"
},
"parameters": {
"environment": {
"NODE_ENV": "production",
"API_VERSION": "v1",
"LOG_LEVEL": "info"
},
"secrets": {
"DATABASE_URL": {
"name": "db-connection-string",
"value_from": "SECRET",
"arn": "arn:aws:secretsmanager:eu-west-1:123456789012:secret:db-credentials-abc123",
"suffix": "connection_string"
},
"API_KEY": {
"name": "external-api-key",
"value_from": "PARAM"
}
}
}
}
Configuration Parameters¶
| Parameter | Mandatory | Type | Default | Description |
|---|---|---|---|---|
| cluster_name | Yes | str | Name for the ECS cluster | |
| service_name | Yes | str | Name for the ECS Fargate service | |
| use_iam_authentication | No | bool | False | Wether the connection to the db should be done through IAM policy |
| alb_name | Yes | str | Name for the Application Load Balancer | |
| alb_domain_prefix | Yes | str | Domain prefix for ALB DNS record (e.g., "api" for api.example.com) | |
| ecr_repo_source_env | No | str | devops | Environment name for ECR repository image sourcing |
| ecr_repo_base_name | Yes | str | Base name for ECR repository containing container images | |
| container_repo | No | str | None | External Docker repository URL (mutually exclusive with ecr_repo_base_name) |
| application_port | Yes | int | Port on which the application container listens | |
| admin_port | No | int | None | Optional admin interface port |
| admin_active | No | bool | False | Whether to enable admin port mapping |
| health_check_path | No | str | The path of the application health check endpoint | |
| health_check_cmd | No | str | None | Container-level health check command override |
| desired_count | No | int | 1 | Number of desired running tasks |
| cpu | No | int | 256 | CPU units allocated to the task (256, 512, 1024, etc.) |
| memory_limit_mib | No | int | 512 | Memory limit in MiB (512, 1024, 2048, etc.) |
| ssl_certificate_id | Yes | str | ACM certificate ID for HTTPS termination | |
| eu_west_cloudront_prefix_list_id | Yes | str | CloudFront prefix list ID for EU West region traffic | |
| environment_files | No | List | None | List of S3-based environment files to inject into containers |
| efs_config | No | Dict | None | EFS configuration for persistent storage |
| route53 | Yes | Dict | Route53 configuration with hosted_zone_id and domain_name | |
| parameters | Yes | Dict | Application configuration with environment variables and secrets |
EFS Configuration Structure (Optional)¶
{
"efs_config": {
"container_user": "1000:1000",
"volumes": [
{
"efs_parameter_key_suffix": "SHARED",
"volume_name": "shared-data",
"ap_parameter_key_suffix": "APP_DATA"
},
{
"efs_parameter_key_suffix": "LOGS",
"volume_name": "app-logs"
}
],
"mount_points": [
{
"volume_name": "shared-data",
"container_path": "/app/data",
"read_only": false
},
{
"volume_name": "app-logs",
"container_path": "/var/log/app",
"read_only": false
}
]
}
}
Route53 Configuration Structure¶
{
"hosted_zone_id": "Z1D633PJN98FT9",
"domain_name": "example.com"
}
Parameters Configuration Structure¶
{
"environment": {
"ENV_VAR_NAME": "plain_text_value"
},
"secrets": {
"SECRET_NAME": {
"name": "parameter_or_secret_name",
"value_from": "SECRET|PARAM",
"arn": "arn:aws:secretsmanager:region:account:secret:name",
"suffix": "key_suffix"
}
}
}
Usage¶
Here's an examples of how to use the ECSBuilder to build ECS infrastructure in a CDK stack:
ecs_builder = ECSBuilder()
application_load_balancer = ecs_builder.set_application_helper(app_helper) \
.set_route53_config({
"hosted_zone_id": "Z2ABCDEFGHIJ123",
"domain_name": "company.io"
}) \
.set_app_parameters({
"environment": {
"SERVICE_NAME": "user-service",
"LOG_LEVEL": "debug",
"METRICS_ENABLED": "true"
},
"secrets": {
"JWT_SECRET": {
"name": "jwt-signing-key",
"value_from": "PARAM"
},
"REDIS_URL": {
"name": "cache-connection",
"value_from": "SECRET",
"arn": "arn:aws:secretsmanager:eu-west-1:123456789012:secret:redis-config",
"suffix": "url"
}
}
}) \
.set_builder_config({
"cluster_name": "microservices-cluster",
"service_name": "user-service",
"alb_name": "user-alb",
"alb_domain_prefix": "users",
"ecr_repo_base_name": "user-service",
"application_port": 3000,
"admin_port": 3001,
"admin_active": True,
"health_check_path": "/myapp/ping",
"desired_count": 3,
"cpu": 1024,
"memory_limit_mib": 2048,
"ssl_certificate_id": "xyz789-abc123-def456"
}) \
.build(scope_from_stack)
Behavior and Features¶
Container Image Sources¶
The builder supports two mutually exclusive options for container images:
ECR Repository (Internal)¶
{
"ecr_repo_source_env": "devops",
"ecr_repo_base_name": "my-app"
}
External Docker Repository¶
{
"container_repo": "nginx:latest"
}
Note
You must specify either ecr_repo_base_name OR container_repo, but not both.
Automatic Infrastructure Configuration¶
Network and Security Setup:¶
- VPC Integration: All resources deployed within specified VPC for network isolation
- Private Subnet Deployment: ECS tasks run in private subnets with NAT Gateway egress
- Security Group Management: Automatic lookup and attachment of predefined security groups
- Load Balancer Configuration: Internet-facing ALB with CloudFront and private access patterns
- SSL Termination: HTTPS listeners with ACM certificate integration
Container Runtime Management¶
- Fargate Serverless: No EC2 instances to manage, fully serverless container execution
- Mixed Capacity Strategy: Cost-optimized deployment using both Fargate Spot (weight: 2) and Fargate (weight: 1)
- Health Check Integration: Automatic ALB target group health checks on root path
- Port Mapping: Flexible port configuration for application and optional admin interfaces
- Resource Allocation: Configurable CPU and memory limits with AWS Fargate constraints
Secrets and Configuration Management¶
- Dual Secret Sources: Support for both AWS Secrets Manager and Systems Manager Parameter Store
- Environment Variables: Plain text environment variables for non-sensitive configuration
- Runtime Injection: Secure credential injection at container startup
- Parameter Store Integration: Automatic parameter name resolution with organizational patterns
EFS Persistent Storage (Optional)¶
- Multi-EFS Support: Attach volumes from multiple EFS file systems in a single task
- Access Point Integration: Fine-grained permissions through EFS access points
- Container User Mapping: Align container user/group with EFS access point permissions
- Cross-Account Parameter Access: Retrieve EFS IDs from SSM with cross-account support
- Multiple Mount Points: Mount different volumes at various container paths
- Read/Write Controls: Configure mount points as read-only or read-write
Environment File Management¶
The builder supports loading environment variables from S3-hosted files, providing a centralized and version-controlled approach to configuration management.
Naming Convention¶
ECS resources follow the pattern: {organization-prefix}-{environment}-{resource-name}
The builder automatically:
- Applies organizational naming standards across all resources
- Includes environment context for multi-stage deployments
- Truncates names to respect AWS service limits
- Generates unique CloudFormation logical IDs
Service Configuration¶
ECS Cluster¶
- Fargate Capacity Providers: Enabled for both standard and Spot instances
- Environment-specific Naming: Cluster names include environment context
- VPC Integration: Deployed within organizational VPC infrastructure
ECS Service¶
- Rolling Updates: 100% minimum healthy percent for single-task services, 50% for multi-task
- Maximum Healthy: 200% to allow zero-downtime deployments
- Auto Scaling: Foundation for implementing auto scaling policies
- Service Discovery: Integration ready for AWS Cloud Map service discovery
Application Load Balancer¶
- Internet-facing: Public accessibility through internet gateway
- Multiple Security Groups: Support for CloudFront and private access patterns
- Target Group Health Checks: HTTP health checks on root path with 200/302 success codes
- SSL/TLS Configuration: HTTPS listeners with ACM certificate integration
IAM Security Model¶
Task Execution Role¶
- ECR Access: Pull container images from Elastic Container Registry
- CloudWatch Logs: Create log groups and streams for container output
- Secrets Retrieval: Access Secrets Manager and Parameter Store during startup
- S3 Integration: Get objects and bucket location for application data
Task Runtime Role¶
- RDS Permissions: Full RDS access for database operations
- S3 Operations: Get, list, and put objects for application storage
- CloudWatch Logging: Create and write to log streams during runtime
- Secrets Access: Ongoing access to secrets and parameters
- KMS Integration: Decrypt encrypted secrets and parameters
DNS and Certificate Management¶
Route53 Integration¶
- Alias A Records: Direct routing to Application Load Balancer
- Domain Prefix Support: Flexible subdomain configuration (e.g., api.example.com)
- Hosted Zone Reference: Integration with existing DNS infrastructure
SSL Certificate Handling¶
- ACM Integration: Reference existing certificates by ID
- Cross-Region Support: Handle certificates in different regions (e.g., us-east-1 for CloudFront)
- HTTPS Enforcement: Secure communication between clients and load balancer
Logging and Monitoring¶
CloudWatch Integration¶
- Centralized Logging: Log group naming follows organizational patterns
- Stream Prefixes: Date-based log stream organization
- Retention Policies: One-month retention for cost optimization
- Removal Policy: Destroy log groups when stack is deleted
SSM Parameter Storage¶
- ALB ARN Storage: Store load balancer ARN for CloudFront integration
- Cross-Service Integration: Enable other builders to reference ALB resources
Secrets Management Patterns¶
AWS Secrets Manager¶
- JSON Key Support: Extract specific keys from JSON secrets using suffix parameter
- Complete ARN Reference: Direct secret reference by full ARN
- Runtime Retrieval: Secure credential injection during container startup
Systems Manager Parameter Store¶
- Hierarchical Naming: Automatic parameter name resolution with organizational prefixes
- String Parameters: Support for both regular and secure string parameters
- Cost-Effective Storage: Use Parameter Store for non-sensitive configuration values
Notes
- The
set_usagemethod from the abstract class should not be used in this builder. - ECS services use mixed Fargate capacity strategy for cost optimization (2:1 Spot to standard)
- Security groups must be pre-created following organizational naming patterns
- SSL certificates should be created in us-east-1 for CloudFront compatibility
- Task resource allocation must follow AWS Fargate CPU/memory combinations
- Route53 hosted zones must exist before deployment
- Container image sources are mutually exclusive: use either
ecr_repo_base_nameORcontainer_repo - ECR repositories must contain tagged images matching app version
- Container health checks expect HTTP 200 or 302 responses on root path
- Admin port configuration is optional and only creates port mappings when admin_active is True
- Log groups are created with DESTROY removal policy for development environments
- EFS configuration requires pre-existing EFS file systems with SSM parameters containing file system IDs
- EFS volumes support both root access and access point patterns for security
- Health check paths should return HTTP 200 status for healthy containers
- S3 buckets containing environment files must exist with proper naming in SSM Parameter Store
- Environment files should use standard .env format with KEY=value pairs
- Environment variables from files are merged with inline parameters.environment variables