[AWS] Let's build an ECS Cluster with CDK

[AWS] Let's build ECR with CDK ECS Cluster version Please refer to Previous article as I will omit the assumptions: pray:

environment

languagepython3.8pipenv

Installation

pipenv install aws_cdk.aws_ec2 aws_cdk.aws_ecs

Implementation

props/ecs_cluster.py

If you want to use an existing VPC when creating an ECS Cluster, you need to look up based on your VPC ID and make the existing VPC available in the Stack. Therefore, parameter management is performed by a class called VpcForEcsCluster.

After that, the parameters that can be set are defined by referring to the API Reference. Container Insights is set to True by default because it is useful for monitoring if it is enabled.

props/ecs_cluster.py


from dataclasses import dataclass
from typing import Optional

from aws_cdk.aws_ecs import CloudMapNamespaceOptions

from src.props.base import Base


@dataclass(frozen=True)
class VpcForEcsCluster(Base):
    id: str
    vpc_id: str


@dataclass(frozen=True)
class EcsCluster(Base):
    id: str
    cluster_name: str
    container_insights: bool = True
    default_cloud_map_namespace: Optional[CloudMapNamespaceOptions] = None

entity/ecs_cluster.py

In the case of ECS Cluster, the parameters are different depending on the environment, specifically, the VPC ID is different, so create an entity for each environment. This time I'm writing only staging, but in production you can define the ProdEcsCluster class in the same file.

entity/ecs_cluster.py


from src.entity.base import Base
from src.props.ecs_cluster import EcsCluster, VpcForEcsCluster


class EcsClusterBase(Base):
    vpc: VpcForEcsCluster
    cluster: EcsCluster


class StgEcsCluster(EcsClusterBase):
    id = 'StgEcsCluster'

    vpc = VpcForEcsCluster(
        id='StgVpc',
        vpc_id='vpc-xxxxxxxx'
    )

    cluster = EcsCluster(
        id='StgEcsCluster',
        cluster_name='sample'
    )

stack/ecs_cluster.py

The stack is designed to be used in any environment.

In Cluster, if you want to use an existing VPC, you need to specify vpc as an argument, so you use a class method called Vpc.from_lookup to get it based on the VPC ID.

stack/ecs_cluster.py


from typing import Any, Type

from aws_cdk.aws_ec2 import Vpc
from aws_cdk.aws_ecs import Cluster
from aws_cdk.core import Construct, Stack

from src.entity.ecs_cluster import EcsClusterBase


class EcsClusterStack(Stack):
    def __init__(
            self,
            scope: Construct,
            entity: Type[EcsClusterBase],
            **kwargs: Any) -> None:
        super().__init__(scope, entity.id, **kwargs)

        vpc = Vpc.from_lookup(self, **entity.vpc.to_dict())
        Cluster(self, **entity.cluster.to_dict(), vpc=vpc)

app.py

Now let's add the stack of resources we want to build to app.py. If you want to build an ECS Cluster using an existing VPC, pass the region / account environment settings to ʻEcsClusterStack`. The CDK will automatically create a Context and keep the bad data (in this case the existing VPC) if it changes during deployment. It also has a cache-like meaning.

app.py


#!/usr/bin/env python3

from aws_cdk import core

from src.entity.ecr import SampleEcr
from src.entity.ecs_cluster import StgEcsCluster
from src.stack.ecr import EcrStack
from src.stack.ecs_cluster import EcsClusterStack

app = core.App()

#Tags to set for all resources
tags = {'CreatedBy': 'iscream'}

#Environmental setting(Required to use existing VPC)
env_stg = {'region': 'ap-northeast-1', 'account': 'xxxxxxxx'}

#ECR created last time
EcrStack(app, entity=SampleEcr, tags=tags)

# ECS Cluster
EcsClusterStack(app, StgEcsCluster, tags=tags, env=env_stg)

app.synth(skip_validation=False)

Deploy

Now deploy !!!

pipenv run cdk deploy StgEcsCluster

Reference

Recommended Posts

[AWS] Let's build an ECS Cluster with CDK
[AWS] Build an ECR with AWS CDK
Building an AWS Fargate Service with AWS CDK
AWS CDK with Python
Easily build HPC on AWS with genuine AWS Cfn Cluster
Let's build git-cat with Python
Easily build network infrastructure and EC2 with AWS CDK Python
Let's develop an investment algorithm with Python 1
Build a WardPress environment on AWS with pulumi
Build a cheap summarization system with AWS components
[Linux] WSL2 Build an environment for laravel7 with Ubuntu 20.04
Build AWS EC2 and RDS with Terraform Terraform 3 minutes cooking