首页 > 解决方案 > 如何在 TypeScript 中使用 aws-cdk 在每次部署时不重建 DockerImageAsset?

问题描述

我的应用程序是一个 Python API,我将其打包为 Docker 映像并与 ECS Fargate(Spot 实例)一起使用。下面的代码有效。

我的问题是每次我部署它时它都会重建整个图像——这非常耗时(下载所有依赖项、制作图像、上传等)。我希望它自己重用上传到 ECR 的完全相同的图像aws-cdk

当我不接触应用程序的代码而只是对堆栈进行更改时,有没有办法(环境变量或其他)让我跳过这个?

#!/usr/bin/env node
import * as cdk from "@aws-cdk/core"
import * as ecs from "@aws-cdk/aws-ecs"
import * as ec2 from "@aws-cdk/aws-ec2"
import * as ecrassets from "@aws-cdk/aws-ecr-assets"

// See https://docs.aws.amazon.com/cdk/api/latest/docs/aws-ecs-readme.html
export class Stack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props)

        /**
         * Repository & Image
         */

        const apiDockerImage = new ecrassets.DockerImageAsset(
            this,
            `my-api-image`,
            {
                directory: `.`,
                exclude: [`cdk.out`, `cdk`, `.git`]
            }
        )

        /**
         * Cluster
         */

        const myCluster = new ecs.Cluster(this, "Cluster", {})

        // Add Spot Capacity to the Cluster
        myCluster.addCapacity(`spot-auto-scaling-group-capacity`, {
            maxCapacity: 2,
            minCapacity: 1,
            instanceType: new ec2.InstanceType(`r5a.large`),
            spotPrice: `0.0400`,
            spotInstanceDraining: true
        })

        // A task Definition describes what a single copy of a task should look like
        const myApiFargateTaskDefinition = new ecs.FargateTaskDefinition(
            this,
            `api-fargate-task-definition`,
            {
                cpu: 2048,
                memoryLimitMiB: 8192,
            }
        )

        // Add image to task def
        myApiFargateTaskDefinition.addContainer(`api-container`, {
            image: ecs.ContainerImage.fromEcrRepository(
                apiDockerImage.repository,
                `latest`
            ),
        })

        // And the service attaching the task def to the cluster
        const myApiService = new ecs.FargateService(
            this,
            `my-api-fargate-service`,
            {
                cluster: myCluster,
                taskDefinition: myApiFargateTaskDefinition,
                desiredCount: 1,
                assignPublicIp: true,
            }
        )
    }
}

标签: amazon-ecsaws-fargateaws-cdkaws-ecr

解决方案


正确的解决方案是在此部署过程之外构建您的映像,并在 ECR 中获取对该映像的引用。


推荐阅读