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.
--AWS account --IAM User for CDK
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
...
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
$ pwd
/path/to/cdk_fargate
$ cd cdk_fargate/
vi cdk_fargate_stack.py
cdk_fargate_stack.py
is here
--Create a VPC by specifying two Availability Zones.
--Create an ECS Cluster by specifying the created VPC.
-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
$ curl cdk-f-farga-xxxxxxxxx.ap-northeast-1.elb.amazonaws.com
cdk destroy
$ cdk destory
All resources have been deleted!
--Image management using ECR --Custom domain support using ACM and Route53
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
Recommended Posts