Stack #1: ECR Build & Deploy
structure
auto-trading-bot
├── auto_trading_bot_ecr
│ ├── __init__.py
│ └── auto_trading_bot_ecr_stack.py
Create ECR to hold the docker image
ECR creation
./auto_trading_bot_ecr/auto_trading_bot_ecr_stack.py
# Create ECR to hold docker image
ecr = aws_ecr.Repository(
self, "ECR",
repository_name=f"{props['namespace']}",
removal_policy=RemovalPolicy.DESTROY
)
Create a CodeBuild project
CodeBuild Project configuration
./auto_trading_bot_ecr/auto_trading_bot_ecr_stack.py
# CodeBuild Project configuration
docker_build_from_github = aws_codebuild.Project(self, "DockerBuild",
project_name=props["docker_build_project_name"],
build_spec=aws_codebuild.BuildSpec.from_source_filename('docker-build/docker_build_buildspec.yml'),
environment=aws_codebuild.BuildEnvironment(
privileged=True,
build_image=aws_codebuild.LinuxBuildImage.AMAZON_LINUX_2_5,
),
source=aws_codebuild.Source.git_hub(
owner=props["GIT_HUB_OWNER"],
repo=props["GIT_HUB_REPO"],
branch_or_ref=props["GIT_HUB_BRANCH"],
webhook=True
),
environment_variables={
"ACCOUNT_ID": aws_codebuild.BuildEnvironmentVariable(value=Aws.ACCOUNT_ID),
"ECR_URI": aws_codebuild.BuildEnvironmentVariable(value=ecr.repository_uri),
"IMAGE_NAME": aws_codebuild.BuildEnvironmentVariable(value=ecr.repository_name),
"FUNCTION_NAME": aws_codebuild.BuildEnvironmentVariable(value=props["function_name"])
},
description="CodeBuild for Lambda run on container",
timeout=Duration.minutes(15)
)
Grant Lambda permission for updating function
lambda permission
./auto_trading_bot_ecr/auto_trading_bot_ecr_stack.py
# Grant CodeBuild perssion to update Lambda main function
lambda_function_update_policy = {
"Sid": "LambdaFunctionUpdatePolicy",
"Effect": "Allow",
"Action": ["lambda:UpdateFunctionCode"],
"Resource": f"arn:aws:lambda:{Aws.REGION}:{Aws.ACCOUNT_ID}:function:{props["function_name"]}"
}
# Add policy to CodeBuild project
docker_build_from_github.add_to_role_policy(aws_iam.PolicyStatement.from_json(lambda_function_update_policy))