如何使用python让cdk保留以前的lambda版本?

问题描述 投票:0回答:1

我的堆栈有以下代码:

from aws_cdk import CfnOutput, Duration, RemovalPolicy, Size, Stack
from aws_cdk import aws_iam as iam
from aws_cdk import aws_lambda as _lambda
from constructs import Construct


class VsConverterStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, stage: str, **kwargs) -> None:  # type: ignore
        super().__init__(scope, construct_id, **kwargs)

        s3_buckets = {
            "test": {"full": "arn:aws:s3:::mgq-data-test", "name": "mgq-data-test"},
            "beta": {"full": "arn:aws:s3:::mgq-data-beta", "name": "mgq-data-beta"},
            "prod": {"full": "arn:aws:s3:::mgq-data-prod", "name": "mgq-data-prod"},
        }

        if stage not in s3_buckets:
            raise ValueError(f"Invalid stage: {stage}. Must be 'test', 'beta' or 'prod'.")

        # Define Docker image for Lambda using the Dockerfile from the repo root
        docker_image = _lambda.DockerImageCode.from_image_asset(
            directory="../"  # Path to your Dockerfile directory
        )

        # Define the Lambda function with the Docker image
        vs_convert_function = _lambda.DockerImageFunction(
            self,
            "converter",
            function_name=f"vs-converter-{stage}",
            code=docker_image,
            timeout=Duration.seconds(900),
            memory_size=10240,
            ephemeral_storage_size=Size.gibibytes(1),
            environment={"BUCKET": s3_buckets[stage]["name"]},
        )

        # Create a version based on the function's current state
        version = _lambda.Version(
            self,
            "ConverterVersion",
            lambda_=vs_convert_function,
            # removal_policy=RemovalPolicy.RETAIN,
        )

        # Create an alias pointing to the new version
        vs_convert_function_alias = _lambda.Alias(self, "ConverterAlias", alias_name="current", version=version)

        # IAM permissions for the S3 bucket
        bucket_policy = iam.PolicyStatement(
            effect=iam.Effect.ALLOW,
            actions=[
                "s3:ListBucket",
                "s3:GetObject",
                "s3:PutObject",
                "s3:DeleteObject",
            ],
            resources=[f"{s3_buckets[stage]['full']}", f"{s3_buckets[stage]['full']}/*"],
        )
        vs_convert_function.add_to_role_policy(bucket_policy)

        # Add CfnOutput to display the Lambda function name and version
        CfnOutput(self, "LambdaFunctionName", value=vs_convert_function.function_name)
        CfnOutput(self, "LambdaVersion", value=version.version)
        CfnOutput(self, "LambdaAlias", value=vs_convert_function_alias.alias_name)

无论我在 python 代码库或 Dockerfile 中进行什么更改,每当我做

code deploy
时,我都会得到相同的版本号,即使
cdk diff
显示差异。

我来自无服务器框架,我发现在 CDK 中找出无服务器中自然存在的东西具有挑战性。

aws-lambda aws-cdk
1个回答
0
投票

我意识到我在错误的地方使用了

removal_policy=RemovalPolicy.RETAIN,

from aws_cdk import CfnOutput, Duration, RemovalPolicy, Size, Stack
from aws_cdk import aws_iam as iam
from aws_cdk import aws_lambda as _lambda
from constructs import Construct


class VsConverterStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, stage: str, **kwargs) -> None:  # type: ignore
        super().__init__(scope, construct_id, **kwargs)

        s3_buckets = {
            "test": {"full": "arn:aws:s3:::mgq-data-test", "name": "mgq-data-test"},
            "beta": {"full": "arn:aws:s3:::mgq-data-beta", "name": "mgq-data-beta"},
            "prod": {"full": "arn:aws:s3:::mgq-data-prod", "name": "mgq-data-prod"},
        }

        if stage not in s3_buckets:
            raise ValueError(f"Invalid stage: {stage}. Must be 'test', 'beta' or 'prod'.")

        # Define Docker image for Lambda using the Dockerfile from the repo root
        docker_image = _lambda.DockerImageCode.from_image_asset(
            directory="../"  # Path to your Dockerfile directory
        )

        # Define the Lambda function with the Docker image
        vs_convert_function = _lambda.DockerImageFunction(
            self,
            "converter",
            function_name=f"vs-converter-{stage}",
            code=docker_image,
            timeout=Duration.seconds(900),
            memory_size=10240,
            ephemeral_storage_size=Size.gibibytes(1),
            environment={"BUCKET": s3_buckets[stage]["name"]},
            current_version_options={"removal_policy": RemovalPolicy.RETAIN}, # <-- correct way
        )

        # Publish a new version
        version = vs_convert_function.current_version

        # Create an alias pointing to the latest version
        vs_convert_function_alias = _lambda.Alias(self, "ConverterAlias", alias_name="current", version=version)

        # IAM permissions for the S3 bucket
        bucket_policy = iam.PolicyStatement(
            effect=iam.Effect.ALLOW,
            actions=[
                "s3:ListBucket",
                "s3:GetObject",
                "s3:PutObject",
                "s3:DeleteObject",
            ],
            resources=[f"{s3_buckets[stage]['full']}", f"{s3_buckets[stage]['full']}/*"],
        )
        vs_convert_function.add_to_role_policy(bucket_policy)

        # Add CfnOutput to display the Lambda function name and version
        CfnOutput(self, "LambdaFunctionName", value=vs_convert_function.function_name)
        CfnOutput(self, "LambdaVersion", value=version.version)
        CfnOutput(self, "LambdaAlias", value=vs_convert_function_alias.alias_name)
© www.soinside.com 2019 - 2024. All rights reserved.