[PYTHON] Building an AWS Fargate Service with AWS CDK

Introduction

I would like to build an AWS Fargate Service using AWS CDK (Python).

The code created this time is here

↑ Create the following configuration with this code.

Diagram

CDK_Fargate-全体構成.png

Preparation

--AWS account --IAM User for CDK

flow

  1. Environment variables
  2. cdk install
  3. cdk init
  4. Implementation
  5. cdk deploy
  6. [Operation check](# Operation check)
  7. cdk destroy

cdk install

$ npm install -g aws-cdk

If cdk cannot be executed, check if it is in the PATH.

$ which node
/path/to/bin/node
$ export
...
PATH=/path/to/hoge:/path/to/fuga
...
$ export PATH=$PATH:/path/to/current/bin
$ export
...
PATH=/path/to/hoge:/path/to/fuga:/path/to/current/bin
...

Environment variable settings

export AWS_ACCESS_KEY_ID=hoge
export AWS_SECRET_ACCESS_KEY=fuga
export ROLE_ARN=arn:aws:iam::xxxxxxxxxxxx:role/ecsTaskExecutionRole
export ECR_REGISOTRY=xxxxxxxxxxxx:role.dkr.ecr.ap-northeast-1.amazonaws.com/django-app:latest

cdk init

$ mkdir /path/to/cdk_fargate
$ cd /path/to/cdk_fargate
$ cdk init --language python

Implementation

$ pwd
/path/to/cdk_fargate
$ cd cdk_fargate/
vi cdk_fargate_stack.py  

cdk_fargate_stack.py is here

VPC creation

--Create a VPC by specifying two Availability Zones.

Create ECS Cluster

--Create an ECS Cluster by specifying the created VPC.

Fargate Service creation

-Build a Fargate Service using ecs_pattern.ApplicationLoadBalancedFargateService. --This time, see the image of Nginx.

Output --Output ALB DNS

import os
from dotenv import load_dotenv

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

load_dotenv()

ROLE_ARN = os.environ["ROLE_ARN"]
ECR_REGISOTRY = os.environ["ECR_REGISOTRY"]


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

        vpc = ec2.Vpc(self, "CdkFargateVpc", max_azs=2)

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

        role = iam.Role.from_role_arn(self, "Role", ROLE_ARN)
        image = ecs.ContainerImage.from_registry(ECR_REGISOTRY)
        task_definition = ecs.FargateTaskDefinition(
            scope=self, id="TaskDefinition", execution_role=role, task_role=role
        )
        port_mapping = ecs.PortMapping(container_port=80, host_port=80)
        container = task_definition.add_container(
            id="Container", image=image
        ).add_port_mappings(port_mapping)

        fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(
            self, "FargateService", cluster=cluster, task_definition=task_definition
        )

        core.CfnOutput(
            self,
            "LoadBalancerDNS",
            value=fargate_service.load_balancer.load_balancer_dns_name,
        )


cdk deploy

$ export AWS_ACCESS_KEY_ID=hoge
$ export AWS_SECRET_ACCESS_KEY=fuga
$ cdk deploy

Operation check

$ curl cdk-f-farga-xxxxxxxxx.ap-northeast-1.elb.amazonaws.com

cdk destroy

$ cdk destory

All resources have been deleted!

What I want to do next

--Image management using ECR --Custom domain support using ACM and Route53

Summary

The team develops using Python, but I found it wonderful to be able to manage the configuration using a common language. I would like to continue to promote configuration management using CDK. I couldn't even implement custom domain settings

References

Recommended Posts

Building an AWS Fargate Service with AWS CDK
[AWS] Build an ECR with AWS CDK
AWS CDK with Python
[AWS] Let's build an ECS Cluster with CDK
[Python] Building an environment with Anaconda [Mac]
I tried to make a url shortening service serverless with AWS CDK
Building an Anaconda environment for Python with pyenv
Various commands for building an environment with Apache
Try building an environment for MayaPython with VisualStudioCode
I tried to create an environment to check regularly using Selenium with AWS Fargate
Building an environment for natural language processing with Python
Building an environment to use CaboCha with google colaboratory
CodeCommit + CodePipeline with CDK
Let's get started with Python ~ Building an environment on Windows 10 ~
Building an environment to execute python programs on AWS EC2
Easily build network infrastructure and EC2 with AWS CDK Python