DEV Community

Gert Leenders
Gert Leenders

Posted on • Originally published at element7.io

2 1

Creating an AWS Fargate service with a custom Task Definition using the AWS Python CDK

Because not a lot of Python CDK examples seem to be available on the web I share this CDK code snippet for the common use case of creating a Fargate service. The code below deploys an ECS Fargate service on an ECS cluster. The Service uses a Docker Hub image and contains a port mapping. The code should be self-explanatory.

from aws_cdk import (
    core, aws_ec2 as ec2,
    aws_ecs as ecs,
    aws_ecs_patterns as ecs_patterns
)

class ExampleStack(core.Stack):

    def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        vpc = ec2.Vpc(self, "some-vpc", 
                cidr="10.0.0.0/22",
                max_azs=3)

        cluster = ecs.Cluster(self, "some-cluser", vpc=vpc)

        task_definition = ecs.FargateTaskDefinition( self, "spring-boot-td", 
                cpu=512, memory_limit_mib=2048)

        image = ecs.ContainerImage.from_registry("springio/gs-spring-boot-docker")
        container = task_definition.add_container( "spring-boot-container", image=image)

        port_mapping = ecs.PortMapping(container_port=8080, host_port=8080)
        container.add_port_mappings(port_mapping)

        ecs_patterns.ApplicationLoadBalancedFargateService(self, "some-service",
            cluster=cluster,
            task_definition=task_definition,
            desired_count=2,
            cpu=512,
            memory_limit_mib=2048,
            public_load_balancer=True)
Enter fullscreen mode Exit fullscreen mode

Enjoy!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay