A Smaller Bedrock Gateway, Part 7: Gateway Stack: Tasks, Service, and Alarms
The gateway stack in readable YAML, part 3 of 3: ECS tasks, the service, and CloudWatch alarms, then join and check it.
Series: A Smaller Bedrock Gateway (8 articles)
- …
- 7A Smaller Bedrock Gateway, Part 7: Gateway Stack: Tasks, Service, and Alarms This article
Last updated: 2026-11-13 (Fri) 18:22 GST
In Part 6, I added the load balancer and the IAM roles. In this part, I will complete the gateway template with the ECS cluster, the two task definitions, the service, and the CloudWatch alarms. Then we will join and check the template, ready to deploy in Part 8.
The cluster and the migration task
The cluster has Container Insights turned on. The migration task is a one-shot task that runs the bootstrap program from Part 4: it applies the LiteLLM schema and creates the restricted roles the gateway uses. CloudFormation only registers this task definition. It does not run it, and it does not wait for it before starting the service. That is why the service starts at zero tasks and why Part 8 runs the migration by hand and checks for exit code 0 before going further.
Both task definitions use the same hardening. Each main container runs as UID 65534 with a read-only root file system, drops all Linux capabilities, and runs under an init process. Because the root file system is read-only, a small task-local volume serves as
/tmp . On Fargate platform 1.4.0 that volume starts owned by root, so a short-lived helper container fixes its permissions first and the main container waits for it to succeed.Cluster and migration task definition
This block holds the cluster and the migration task definition. Save this block as
gateway-10.yaml . Cluster: Type: AWS::ECS::Cluster Properties: ClusterSettings: - Name: containerInsights Value: enabled Tags: - Key: Name Value: !Sub '${AWS::StackName}-litellm'
# The tmp volume is task-local ephemeral storage, not EFS; transport encryption # is inapplicable. It is required because the container root filesystem is read-only. # CloudFormation only registers this task definition; it neither starts the task # nor gates ServiceDesiredCount on the result. Orchestration must run it to a # successful exit before setting a nonzero desired count. # On Fargate platform 1.4.0 the task-local tmp bind mount starts empty and # root:root 0755; it is not initialized from the image's /tmp. The non-root main # container cannot write it, so tmp-permissions (root-owned dir, so chmod needs # no capability) runs chmod 1777 first and the main container waits for SUCCESS. MigrationTaskDefinition: Type: AWS::ECS::TaskDefinition Properties: Family: !Sub '${AWS::StackName}-litellm-migration' Cpu: '1024' Memory: '4096' NetworkMode: awsvpc RequiresCompatibilities: - FARGATE RuntimePlatform: CpuArchitecture: X86_64 OperatingSystemFamily: LINUX ExecutionRoleArn: !GetAtt MigrationExecutionRole.Arn Volumes: - Name: tmp ContainerDefinitions: - Name: tmp-permissions Image: !Ref ContainerImage Essential: false User: '0:0' ReadonlyRootFilesystem: true LinuxParameters: InitProcessEnabled: true Capabilities: Drop: - ALL MountPoints: - SourceVolume: tmp ContainerPath: /tmp ReadOnly: false StopTimeout: 30 EntryPoint: - /bin/sh - -c Command: - 'set -eu && if [ "$(stat -c %a /tmp)" != 1777 ]; then chmod 1777 /tmp; fi && stat -c "tmp-permissions %a %u:%g" /tmp' LogConfiguration: LogDriver: awslogs Options: awslogs-group: !Ref LogGroup awslogs-region: !Ref AWS::Region awslogs-stream-prefix: tmp-permissions - Name: migration Image: !Ref ContainerImage Essential: true DependsOn: - ContainerName: tmp-permissions Condition: SUCCESS User: '65534:65534' ReadonlyRootFilesystem: true LinuxParameters: InitProcessEnabled: true Capabilities: Drop: - ALL MountPoints: - SourceVolume: tmp ContainerPath: /tmp ReadOnly: false StopTimeout: 120 EntryPoint: - /bin/sh - -c Command: - >- set -eu && umask 077 && exec python /opt/litellm/bootstrap_db.py Environment: - Name: DATABASE_HOST Value: !GetAtt Database.Endpoint.Address - Name: DATABASE_PORT Value: !GetAtt Database.Endpoint.Port - Name: DATABASE_NAME Value: litellm_v2 - Name: RDS_CA_BUNDLE Value: /etc/ssl/certs/aws-rds-global-bundle.pem - Name: LITELLM_PRISMA_MIGRATE_DEPLOY_TIMEOUT Value: '600' - Name: DISABLE_SCHEMA_UPDATE Value: 'false' - Name: LITELLM_OFFLINE_MODE Value: 'true' - Name: LITELLM_LOCAL_MODEL_COST_MAP Value: 'True' - Name: LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS Value: 'true' - Name: CHECKPOINT_DISABLE Value: '1' - Name: LITELLM_TELEMETRY_DISABLED Value: 'true' - Name: HOME Value: /tmp - Name: XDG_CACHE_HOME Value: /tmp/.cache - Name: PYTHONDONTWRITEBYTECODE Value: '1' - Name: PYTHONPYCACHEPREFIX Value: /tmp/pycache - Name: PYTHONUNBUFFERED Value: '1' - Name: TMPDIR Value: /tmp Secrets: - Name: ADMIN_DATABASE_USER ValueFrom: !Sub '${Database.MasterUserSecret.SecretArn}:username::' - Name: ADMIN_DATABASE_PASSWORD ValueFrom: !Sub '${Database.MasterUserSecret.SecretArn}:password::' - Name: APP_DATABASE_USER_A ValueFrom: !Sub '${AppDbSecretA}:username::' - Name: APP_DATABASE_PASSWORD_A ValueFrom: !Sub '${AppDbSecretA}:password::' - Name: APP_DATABASE_USER_B ValueFrom: !Sub '${AppDbSecretB}:username::' - Name: APP_DATABASE_PASSWORD_B ValueFrom: !Sub '${AppDbSecretB}:password::' LogConfiguration: LogDriver: awslogs Options: awslogs-group: !Ref LogGroup awslogs-region: !Ref AWS::Region awslogs-stream-prefix: migration Tags: - Key: Workload Value: litellm-migrationThe runtime task
The runtime task runs LiteLLM on port 4000 with 1 vCPU and 4 GB of memory. It reads the model, the database endpoint, and the Valkey endpoint from plain environment variables, and receives exactly one database credential slot, one Valkey credential slot, the administrator key, and the salt key from Secrets Manager. LiteLLM telemetry and online lookups are turned off, because the task has no route to the internet anyway. A container health check probes the readiness path.
Runtime task definition
This block holds the runtime task definition. Save this block as
gateway-11.yaml . # The tmp volume is task-local ephemeral storage, not EFS; transport encryption # is inapplicable. It is required because the container root filesystem is read-only. # On Fargate platform 1.4.0 the task-local tmp bind mount starts empty and # root:root 0755; it is not initialized from the image's /tmp. The non-root main # container cannot write it, so tmp-permissions (root-owned dir, so chmod needs # no capability) runs chmod 1777 first and the main container waits for SUCCESS. RuntimeTaskDefinition: Type: AWS::ECS::TaskDefinition Properties: Family: !Sub '${AWS::StackName}-litellm-runtime' Cpu: '1024' Memory: '4096' NetworkMode: awsvpc RequiresCompatibilities: - FARGATE RuntimePlatform: CpuArchitecture: X86_64 OperatingSystemFamily: LINUX ExecutionRoleArn: !GetAtt RuntimeExecutionRole.Arn TaskRoleArn: !GetAtt RuntimeTaskRole.Arn Volumes: - Name: tmp ContainerDefinitions: - Name: tmp-permissions Image: !Ref ContainerImage Essential: false User: '0:0' ReadonlyRootFilesystem: true LinuxParameters: InitProcessEnabled: true Capabilities: Drop: - ALL MountPoints: - SourceVolume: tmp ContainerPath: /tmp ReadOnly: false StopTimeout: 30 EntryPoint: - /bin/sh - -c Command: - 'set -eu && if [ "$(stat -c %a /tmp)" != 1777 ]; then chmod 1777 /tmp; fi && stat -c "tmp-permissions %a %u:%g" /tmp' LogConfiguration: LogDriver: awslogs Options: awslogs-group: !Ref LogGroup awslogs-region: !Ref AWS::Region awslogs-stream-prefix: tmp-permissions - Name: litellm Image: !Ref ContainerImage Essential: true DependsOn: - ContainerName: tmp-permissions Condition: SUCCESS User: '65534:65534' ReadonlyRootFilesystem: true LinuxParameters: InitProcessEnabled: true Capabilities: Drop: - ALL MountPoints: - SourceVolume: tmp ContainerPath: /tmp ReadOnly: false PortMappings: - ContainerPort: 4000 Protocol: tcp StopTimeout: 120 HealthCheck: Command: - CMD-SHELL - >- python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:4000/health/readiness', timeout=5)" || exit 1 Interval: 30 Timeout: 10 Retries: 3 StartPeriod: 300 EntryPoint: - /bin/sh - -c Command: - >- set -eu && umask 077 && LITELLM_MASTER_KEY="sk-${ADMINISTRATOR_KEY_BODY}" && export LITELLM_MASTER_KEY && DATABASE_URL="$(python -c 'import os; from urllib.parse import quote; user=quote(os.environ["APP_DATABASE_USER"], safe=""); password=quote(os.environ["APP_DATABASE_PASSWORD"], safe=""); database=quote(os.environ["DATABASE_NAME"], safe=""); ca=quote(os.environ["RDS_CA_BUNDLE"], safe="/"); print("postgresql://{}:{}@{}:{}/{}?sslmode=verify-full&sslrootcert={}".format(user, password, os.environ["DATABASE_HOST"], os.environ["DATABASE_PORT"], database, ca))')" && export DATABASE_URL && printf '%s\n' 'model_list:' " - model_name: ${MODEL_ALIAS}" ' litellm_params:' " model: bedrock/${MODEL_ID}" ' aws_region_name: os.environ/AWS_REGION' 'general_settings:' ' allow_requests_on_db_unavailable: false' ' coordination_redis:' ' host: os.environ/REDIS_HOST' ' port: os.environ/REDIS_PORT' ' username: os.environ/REDIS_USERNAME' ' password: os.environ/REDIS_PASSWORD' ' ssl: true' ' ssl_cert_reqs: required' ' ssl_check_hostname: true' ' namespace: article07' ' max_connections: 20' ' socket_connect_timeout: 5.0' ' socket_timeout: 2.0' ' fail_closed_rate_limit_enforcement: true' ' fail_closed_budget_enforcement: true' ' user_api_key_cache_ttl: 5' > /tmp/litellm_config.yaml && exec litellm --config /tmp/litellm_config.yaml --host 0.0.0.0 --port 4000 --num_workers 1 Environment: - Name: AWS_REGION Value: !Ref AWS::Region - Name: MODEL_ID Value: !Ref ModelId - Name: MODEL_ALIAS Value: !Ref ModelAlias - Name: DATABASE_HOST Value: !GetAtt Database.Endpoint.Address - Name: DATABASE_PORT Value: !GetAtt Database.Endpoint.Port - Name: DATABASE_NAME Value: litellm_v2 - Name: REDIS_HOST Value: !GetAtt ValkeyReplicationGroup.PrimaryEndPoint.Address - Name: REDIS_PORT Value: !GetAtt ValkeyReplicationGroup.PrimaryEndPoint.Port - Name: REDIS_USERNAME Value: !Sub 'article07-${ValkeyResourceId}' # This non-secret value forces a new task-definition revision after # either Valkey secret changes, so ECS resolves the selected value again. - Name: VALKEY_CREDENTIAL_REVISION Value: !Ref ValkeyCredentialRevision - Name: RDS_CA_BUNDLE Value: /etc/ssl/certs/aws-rds-global-bundle.pem - Name: STORE_MODEL_IN_DB Value: 'True' - Name: DISABLE_SCHEMA_UPDATE Value: 'true' - Name: LITELLM_OFFLINE_MODE Value: 'true' - Name: LITELLM_LOCAL_MODEL_COST_MAP Value: 'True' - Name: LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS Value: 'true' - Name: CHECKPOINT_DISABLE Value: '1' - Name: LITELLM_TELEMETRY_DISABLED Value: 'true' - Name: HOME Value: /tmp - Name: XDG_CACHE_HOME Value: /tmp/.cache - Name: PYTHONDONTWRITEBYTECODE Value: '1' - Name: PYTHONPYCACHEPREFIX Value: /tmp/pycache - Name: PYTHONUNBUFFERED Value: '1' - Name: TMPDIR Value: /tmp # The runtime container receives only the active constrained database # and Valkey credentials. It never receives the RDS-managed administrator # credential or either inactive application credential. Secrets: - Name: ADMINISTRATOR_KEY_BODY ValueFrom: !Sub '${AdministratorKeySecret}:administrator_key::' - Name: LITELLM_SALT_KEY ValueFrom: !Sub '${SaltKeySecret}:salt_key::' - Name: APP_DATABASE_USER ValueFrom: Fn::If: - UseAppCredentialA - !Sub '${AppDbSecretA}:username::' - !Sub '${AppDbSecretB}:username::' - Name: APP_DATABASE_PASSWORD ValueFrom: Fn::If: - UseAppCredentialA - !Sub '${AppDbSecretA}:password::' - !Sub '${AppDbSecretB}:password::' - Name: REDIS_PASSWORD ValueFrom: Fn::If: - UseValkeyCredentialA - !Sub '${ValkeyCredentialSecretA}:password::' - !Sub '${ValkeyCredentialSecretB}:password::' LogConfiguration: LogDriver: awslogs Options: awslogs-group: !Ref LogGroup awslogs-region: !Ref AWS::Region awslogs-stream-prefix: litellm Tags: - Key: Workload Value: litellm-runtimeThe service
The service runs the runtime task on Fargate platform 1.4.0 in the two private subnets, with no public IP addresses and ECS Exec turned off. Deployments keep 100 percent of tasks healthy while new ones start, and the deployment circuit breaker rolls back automatically if a new revision fails to become healthy. The desired count comes from
ServiceDesiredCount , which defaults to 0.Service
This block holds the ECS service. Save this block as
gateway-12.yaml . Service: Type: AWS::ECS::Service DependsOn: - AdminKeyPathAllowRule - ClientGenerationPathAllowRule - ClientHealthPathAllowRule Properties: Cluster: !Ref Cluster TaskDefinition: !Ref RuntimeTaskDefinition LaunchType: FARGATE PlatformVersion: '1.4.0' SchedulingStrategy: REPLICA DesiredCount: !Ref ServiceDesiredCount EnableExecuteCommand: false EnableECSManagedTags: true PropagateTags: SERVICE NetworkConfiguration: AwsvpcConfiguration: Subnets: Fn::Split: - ',' - Fn::ImportValue: Fn::Sub: '${NetworkStackName}-PrivateSubnetIds' SecurityGroups: - Fn::ImportValue: Fn::Sub: '${NetworkStackName}-TaskSecurityGroupId' AssignPublicIp: DISABLED LoadBalancers: - ContainerName: litellm ContainerPort: 4000 TargetGroupArn: !Ref TargetGroup DeploymentConfiguration: MinimumHealthyPercent: 100 MaximumPercent: 200 DeploymentCircuitBreaker: Enable: true Rollback: true HealthCheckGracePeriodSeconds: 300 Tags: - Key: Name Value: !Sub '${AWS::StackName}-litellm' - Key: Workload Value: litellm-runtime
# --------------------------------------------------------------------------- # Operational alarms. AlarmTopicArn changes notification wiring only; every # alarm exists even when no topic is supplied. # ---------------------------------------------------------------------------Alarms
Nine alarms watch the parts most likely to fail: unhealthy targets, 5xx responses from the load balancer and from the targets, ECS CPU and memory above 80 percent, RDS CPU above 80 percent and free storage below 10 GiB, and Valkey engine CPU and memory above 80 percent. The alarms exist even if you do not provide an SNS topic.
AlarmTopicArn only decides whether they notify anyone.Alarms
This block holds the nine CloudWatch alarms. Save this block as
gateway-13.yaml . AlbUnhealthyHostsAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: LiteLLM target group has an unhealthy host. Namespace: AWS/ApplicationELB MetricName: UnHealthyHostCount Dimensions: - Name: LoadBalancer Value: !GetAtt LoadBalancer.LoadBalancerFullName - Name: TargetGroup Value: !GetAtt TargetGroup.TargetGroupFullName Statistic: Maximum Period: 60 EvaluationPeriods: 2 DatapointsToAlarm: 2 Threshold: 0 ComparisonOperator: GreaterThanThreshold TreatMissingData: notBreaching AlarmActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue'] OKActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue']
Alb5xxAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: Internal ALB is returning HTTP 5xx responses. Namespace: AWS/ApplicationELB MetricName: HTTPCode_ELB_5XX_Count Dimensions: - Name: LoadBalancer Value: !GetAtt LoadBalancer.LoadBalancerFullName Statistic: Sum Period: 60 EvaluationPeriods: 5 DatapointsToAlarm: 3 Threshold: 5 ComparisonOperator: GreaterThanOrEqualToThreshold TreatMissingData: notBreaching AlarmActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue'] OKActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue']
Target5xxAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: LiteLLM targets are returning HTTP 5xx responses. Namespace: AWS/ApplicationELB MetricName: HTTPCode_Target_5XX_Count Dimensions: - Name: LoadBalancer Value: !GetAtt LoadBalancer.LoadBalancerFullName - Name: TargetGroup Value: !GetAtt TargetGroup.TargetGroupFullName Statistic: Sum Period: 60 EvaluationPeriods: 5 DatapointsToAlarm: 3 Threshold: 5 ComparisonOperator: GreaterThanOrEqualToThreshold TreatMissingData: notBreaching AlarmActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue'] OKActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue']
EcsCpuAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: LiteLLM ECS service CPU is above 80 percent. Namespace: AWS/ECS MetricName: CPUUtilization Dimensions: - Name: ClusterName Value: !Ref Cluster - Name: ServiceName Value: !GetAtt Service.Name Statistic: Average Period: 300 EvaluationPeriods: 3 DatapointsToAlarm: 3 Threshold: 80 ComparisonOperator: GreaterThanOrEqualToThreshold TreatMissingData: notBreaching AlarmActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue'] OKActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue']
EcsMemoryAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: LiteLLM ECS service memory is above 80 percent. Namespace: AWS/ECS MetricName: MemoryUtilization Dimensions: - Name: ClusterName Value: !Ref Cluster - Name: ServiceName Value: !GetAtt Service.Name Statistic: Average Period: 300 EvaluationPeriods: 3 DatapointsToAlarm: 3 Threshold: 80 ComparisonOperator: GreaterThanOrEqualToThreshold TreatMissingData: notBreaching AlarmActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue'] OKActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue']
RdsFreeStorageAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: LiteLLM PostgreSQL free storage is below 10 GiB. Namespace: AWS/RDS MetricName: FreeStorageSpace Dimensions: - Name: DBInstanceIdentifier Value: !Ref Database Statistic: Minimum Period: 300 EvaluationPeriods: 3 DatapointsToAlarm: 3 Threshold: 10737418240 ComparisonOperator: LessThanThreshold TreatMissingData: breaching AlarmActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue'] OKActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue']
RdsCpuAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: LiteLLM PostgreSQL CPU is above 80 percent. Namespace: AWS/RDS MetricName: CPUUtilization Dimensions: - Name: DBInstanceIdentifier Value: !Ref Database Statistic: Average Period: 300 EvaluationPeriods: 3 DatapointsToAlarm: 3 Threshold: 80 ComparisonOperator: GreaterThanOrEqualToThreshold TreatMissingData: breaching AlarmActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue'] OKActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue']
ValkeyEngineCpuAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: >- LiteLLM Valkey EngineCPUUtilization is above 80 percent on primary nodes only. Namespace: AWS/ElastiCache MetricName: EngineCPUUtilization Dimensions: - Name: ReplicationGroupId Value: !Ref ValkeyReplicationGroup - Name: Role Value: Primary Statistic: Average Period: 300 EvaluationPeriods: 3 DatapointsToAlarm: 3 Threshold: 80 ComparisonOperator: GreaterThanOrEqualToThreshold TreatMissingData: breaching AlarmActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue'] OKActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue']
ValkeyDatabaseMemoryAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: >- LiteLLM Valkey memory counted for eviction is above 80 percent. Namespace: AWS/ElastiCache MetricName: DatabaseMemoryUsageCountedForEvictPercentage Dimensions: - Name: ReplicationGroupId Value: !Ref ValkeyReplicationGroup Statistic: Average Period: 300 EvaluationPeriods: 3 DatapointsToAlarm: 3 Threshold: 80 ComparisonOperator: GreaterThanOrEqualToThreshold TreatMissingData: breaching AlarmActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue'] OKActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref 'AWS::NoValue']Outputs
The outputs give you everything Part 8 needs, including the cluster name, the migration task definition, the subnets, the task security group, and the administrator key secret. Save this block as
gateway-14.yaml .Outputs:
GatewayUrl: Description: >- Private HTTPS gateway URL using the supplied DNS name. External private clients require customer-provided routing and hybrid DNS prerequisites. Value: !Sub 'https://${GatewayDomainName}'
GatewayDomainName: Description: >- Directly supplied private DNS name. Orchestration verifies that it belongs to the imported HostedZoneId and is covered by CertificateArn. Value: !Ref GatewayDomainName
LoadBalancerArn: Description: Internal Application Load Balancer ARN. Value: !Ref LoadBalancer
LoadBalancerDnsName: Description: AWS-generated internal ALB hostname. Clients should use GatewayUrl. Value: !GetAtt LoadBalancer.DNSName
HttpsListenerArn: Description: Deny-by-default HTTPS listener ARN. Value: !Ref HttpsListener
TargetGroupArn: Description: LiteLLM runtime target group ARN. Value: !Ref TargetGroup
ClusterName: Description: ECS cluster name for migration and service operations. Value: !Ref Cluster
ClusterArn: Description: ECS cluster ARN. Value: !GetAtt Cluster.Arn
ServiceName: Description: ECS runtime service name. Initial desired count defaults to zero. Value: !GetAtt Service.Name
ServiceArn: Description: ECS runtime service ARN. Value: !Ref Service
MigrationTaskDefinitionArn: Description: >- CloudFormation registers but does not run this task or enforce its result. Orchestration must run it once with PrivateSubnetIds and TaskSecurityGroupId, require exit code zero, and only then set ServiceDesiredCount above zero. bootstrap_db.py deploys the schema and reconciles both constrained application credential slots. Value: !Ref MigrationTaskDefinition
MigrationInvocation: Description: >- Exact one-shot process for orchestration to run and verify before enabling the service; direct CloudFormation does not invoke it. Value: 'python /opt/litellm/bootstrap_db.py -> DISABLE_SCHEMA_UPDATE=false litellm --skip_server_startup'
RuntimeTaskDefinitionArn: Description: >- Runtime task definition using only the active constrained database and Valkey credential slots. Value: !Ref RuntimeTaskDefinition
PrivateSubnet1Id: Description: First imported private subnet used for one probe launch. Value: Fn::Select: - 0 - Fn::Split: - ',' - Fn::ImportValue: Fn::Sub: '${NetworkStackName}-PrivateSubnetIds'
PrivateSubnet2Id: Description: Second imported private subnet used for one probe launch. Value: Fn::Select: - 1 - Fn::Split: - ',' - Fn::ImportValue: Fn::Sub: '${NetworkStackName}-PrivateSubnetIds'
PrivateSubnetIds: Description: Canonical comma-delimited private subnet import for ECS run-task. Value: Fn::ImportValue: Fn::Sub: '${NetworkStackName}-PrivateSubnetIds'
VpcId: Description: Dedicated VPC imported from stack 1. Value: Fn::ImportValue: Fn::Sub: '${NetworkStackName}-VpcId'
AlbSecurityGroupId: Description: Imported security group attached to the internal ALB. Value: Fn::ImportValue: Fn::Sub: '${NetworkStackName}-AlbSecurityGroupId'
TaskSecurityGroupId: Description: Imported security group for migration and runtime tasks. Value: Fn::ImportValue: Fn::Sub: '${NetworkStackName}-TaskSecurityGroupId'
DatabaseSecurityGroupId: Description: Imported security group attached to PostgreSQL. Value: Fn::ImportValue: Fn::Sub: '${NetworkStackName}-DatabaseSecurityGroupId'
CacheSecurityGroupId: Description: Imported security group attached to Valkey. Value: Fn::ImportValue: Fn::Sub: '${NetworkStackName}-CacheSecurityGroupId'
EndpointSecurityGroupId: Description: Imported interface-endpoint security group. Value: Fn::ImportValue: Fn::Sub: '${NetworkStackName}-EndpointSecurityGroupId'
ProbeSecurityGroupId: Description: Imported validation-probe security group used for both subnet launches. Value: Fn::ImportValue: Fn::Sub: '${NetworkStackName}-ProbeSecurityGroupId'
S3PrefixListId: Description: Imported regional Amazon S3 managed prefix list ID. Value: Fn::ImportValue: Fn::Sub: '${NetworkStackName}-S3PrefixListId'
ClientIngressCidr: Description: Directly supplied private client source CIDR used by listener rules. Value: !Ref ClientIngressCidr
AdminIngressCidr: Description: Directly supplied private administrator source CIDR used by listener rules. Value: !Ref AdminIngressCidr
ModelId: Description: Directly supplied exact Bedrock Europe inference profile used by the runtime. Value: !Ref ModelId
FoundationModelId: Description: Directly supplied exact foundation-model ID used by runtime IAM. Value: !Ref FoundationModelId
ModelAlias: Description: LiteLLM alias configured in the runtime and supplied to the probe. Value: !Ref ModelAlias
AdminDbSecretArn: Description: RDS-managed administrator secret. Only the migration execution role can read it. Value: !GetAtt Database.MasterUserSecret.SecretArn
ActiveAppDbSecretArn: Description: Active constrained runtime database secret. Value: !If [UseAppCredentialA, !Ref AppDbSecretA, !Ref AppDbSecretB]
StandbyAppDbSecretArn: Description: Inactive credential slot to update before the next rotation cutover. Value: !If [UseAppCredentialA, !Ref AppDbSecretB, !Ref AppDbSecretA]
AppDbSecretAArn: Description: Constrained runtime credential slot A. Value: !Ref AppDbSecretA
AppDbSecretBArn: Description: Constrained runtime credential slot B. Value: !Ref AppDbSecretB
ActiveAppCredentialSlot: Description: Slot injected into newly started runtime tasks. Value: !Ref ActiveAppCredentialSlot
AppCredentialRotationProcedure: Description: Operator-run overlapping application password rotation procedure. Value: >- Update only StandbyAppDbSecretArn; run MigrationTaskDefinitionArn to exit 0; switch ActiveAppCredentialSlot; wait for ECS service stability; then update the former active secret and rerun the migration task. Run these overlapping steps without intentionally dropping existing connections. CloudFormation does not run or test this sequence.
AdministratorKeySecretArn: Description: LiteLLM administrator bearer-key body. Do not distribute it to clients. Value: !Ref AdministratorKeySecret
SaltKeySecretArn: Description: Stable LiteLLM encryption salt. Do not rotate after first use. Value: !Ref SaltKeySecret
KmsKeyArn: Description: Customer-managed KMS key ARN. Value: !GetAtt GatewayKmsKey.Arn
GatewayLogGroupName: Description: CloudFormation-generated name of the retained KMS-encrypted ECS log group. Value: !Ref LogGroup
LogGroupArn: Description: ECS operational log-group ARN. Value: !GetAtt LogGroup.Arn
RuntimeTaskRoleArn: Description: >- Primary Bedrock authorization identity, restricted to the exact supplied profile, foundation model, six destination Regions, and imported VPC. The network endpoint policy is defense in depth. Value: !GetAtt RuntimeTaskRole.Arn
DatabaseIdentifier: Description: RDS instance identifier used by deployment verification and alarms. Value: !Ref Database
DatabaseEndpoint: Description: Private RDS endpoint. Clients require CA and hostname verification. Value: !GetAtt Database.Endpoint.Address
DatabasePort: Description: PostgreSQL port. Value: !GetAtt Database.Endpoint.Port
ValkeyResourceId: Description: Deployment-unique short ID used to derive Valkey resource identifiers. Value: !Ref ValkeyResourceId
ValkeyReplicationGroupId: Description: Cluster-mode-disabled two-node Valkey replication group ID. Value: !Ref ValkeyReplicationGroup
ValkeyPrimaryEndpoint: Description: >- Private TLS primary endpoint used by LiteLLM for shared coordination writes. Value: !GetAtt ValkeyReplicationGroup.PrimaryEndPoint.Address
ValkeyPrimaryPort: Description: TLS port for the Valkey primary endpoint. Value: !GetAtt ValkeyReplicationGroup.PrimaryEndPoint.Port
ValkeyUserId: Description: Password-authenticated custom Valkey user ID. Value: !Ref ValkeyUser
ValkeyUserGroupId: Description: >- Valkey user group containing only the custom user, without the built-in permissive default user. Value: !Ref ValkeyUserGroup
ActiveValkeyCredentialSecretArn: Description: Valkey credential slot injected into newly started runtime tasks. Value: !If - UseValkeyCredentialA - !Ref ValkeyCredentialSecretA - !Ref ValkeyCredentialSecretB
StandbyValkeyCredentialSecretArn: Description: Inactive Valkey credential slot to update and validate before cutover. Value: !If - UseValkeyCredentialA - !Ref ValkeyCredentialSecretB - !Ref ValkeyCredentialSecretA
ValkeyCredentialRotationProcedure: Description: Operator-run overlapping Valkey password rotation procedure. Value: >- Replace only the password in StandbyValkeyCredentialSecretArn, preserving the deployment-unique username; increment ValkeyCredentialRevision and update the stack so the Valkey user re-resolves both password slots; validate the standby password from an authorized in-VPC client with required TLS; switch ActiveValkeyCredentialSlot, increment ValkeyCredentialRevision again, update the stack, and wait for ECS stability plus old-task draining; then rotate the former active secret and increment ValkeyCredentialRevision once more. Do not intentionally drop existing connections or remove a password still used by a running task. CloudFormation does not run or test this sequence; the operator must validate each stage.
AlbAccessLogBucketName: Description: Canonical imported always-on ALB access-log bucket. Value: Fn::ImportValue: Fn::Sub: '${NetworkStackName}-AlbAccessLogBucketName'
AlbAccessLogPrefix: Description: Object prefix used in the imported ALB log bucket. Value: !Sub '${AWS::StackName}/alb'
NetworkStackName: Description: >- Paired v2 network stack import prefix. For blue/green replacement, use new paired stack names rather than swapping stable imported identities in place. Value: !Ref NetworkStackNameJoin and check the gateway template
Run this in the folder that holds the fourteen gateway blocks. As in Part 3, the second command prints nothing if the result is exactly the validated template.
awk 'FNR==1 && NR>1 {print ""} 1' gateway-*.yaml > 07-02-litellm-gateway.yamlecho 'c373d6363afa86f4af9b861508c14c2825190e0825818a1fd15cc30ab50841e3 07-02-litellm-gateway.yaml' | shasum -a 256 -c --quiet -A quick recap of activities
In this part, we:
- Added a cluster with Container Insights and a one-shot migration task that CloudFormation registers but never runs.
- Added a non-root, read-only, capability-free runtime task that receives one credential slot of each kind.
- Added a private Fargate service with automatic rollback that starts at zero tasks.
- Added nine alarms across the load balancer, ECS, RDS, and Valkey.
- Joined the fourteen blocks and checked the result against the validated template.
Conclusion
The gateway template is complete. In Part 8, I will deploy it, run the migration gate, start the gateway, send the first request, and confirm in CloudTrail that it never left the private network. I will also cover how the deployment was validated and how to run it day to day.
This is Part 7 of the eight-part A Smaller Bedrock Gateway series. Part 1 covers the design, Parts 2 and 3 the network stack, Part 4 the hardened image, Parts 5 to 7 the gateway stack, and Part 8 the deployment, validation, and day-two operations.
Series: A Smaller Bedrock Gateway (8 articles)
- …
- 7A Smaller Bedrock Gateway, Part 7: Gateway Stack: Tasks, Service, and Alarms This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article