AWS CDK AWS ECS Constructs (v1)

1.204.0 · deprecated · verified Fri Apr 17

The `aws-cdk-aws-ecs` package provides AWS Cloud Development Kit (CDK) constructs for defining Amazon Elastic Container Service (ECS) resources in Python. It is part of AWS CDK v1. While functional, AWS CDK v2 is the recommended and actively developed version, which consolidates all constructs into `aws-cdk-lib`. This package is largely superseded by `aws-cdk-lib`'s ECS constructs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart defines an AWS CDK v1 stack that creates an ECS Fargate cluster and deploys a simple Fargate service with a sample container image. It demonstrates importing `aws_ecs`, `aws_ec2`, and `core` constructs as expected in v1. Ensure `CDK_DEFAULT_ACCOUNT` and `CDK_DEFAULT_REGION` (or `AWS_ACCOUNT_ID`/`AWS_REGION`) environment variables are set.

import os
from aws_cdk import (
    core,
    aws_ecs as ecs,
    aws_ec2 as ec2,
    aws_ecr as ecr,
    aws_iam as iam,
)

class MyEcsFargateStack(core.Stack):
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Look up an existing VPC or create a new one
        vpc = ec2.Vpc(self, "MyVpc", max_azs=2)

        cluster = ecs.Cluster(self, "MyFargateCluster", vpc=vpc)

        # Create a Task Definition
        task_definition = ecs.FargateTaskDefinition(
            self, "MyTaskDef",
            memory_limit_mib=512,
            cpu=256
        )

        # Add a container to the task definition
        # Using a public image for simplicity, replace with your ECR image if needed
        image_name = os.environ.get('ECR_IMAGE_NAME', 'amazon/amazon-ecs-sample')
        task_definition.add_container(
            "MyContainer",
            image=ecs.ContainerImage.from_registry(image_name),
            port_mappings=[ecs.PortMapping(container_port=80, host_port=80)]
        )

        # Create a Fargate Service
        ecs.FargateService(
            self, "MyFargateService",
            cluster=cluster,
            task_definition=task_definition,
            desired_count=1
        )

app = core.App()
MyEcsFargateStack(app, "MyEcsFargateStack",
    env=core.Environment(
        account=os.environ.get("CDK_DEFAULT_ACCOUNT", os.environ.get("AWS_ACCOUNT_ID")),
        region=os.environ.get("CDK_DEFAULT_REGION", os.environ.get("AWS_REGION"))
    )
)
app.synth()

view raw JSON →