使用在其他堆栈中创建的资源

Use resource created in other stack

我已经在一个堆栈中创建了一个 lambda 函数,现在想在我的 ApiGateway 堆栈中将它用作 lambda 处理程序。

如何将资源从一个堆栈传递到另一个堆栈?我只发现 TypeScript 示例或错误的 python 示例,这些示例要么无法正常工作,要么缺少重要步骤。

主要

#!/usr/bin/env python3

import aws_cdk as cdk

from cdk.api_stack import ApiStack
from cdk.lambda_stack import LambdaStack


app = cdk.App()
LambdaStack(app, "lambda")
ApiStack(app, "api", gitlabUtilsLambda=LambdaStack.outputLambda)


app.synth()

Lambda 堆栈

from constructs import Construct
from aws_cdk import (
    Stack,
    aws_lambda as _lambda,
)

class LambdaStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        gitlabUtilsLambda = _lambda.Function(
            self, "handler",
            runtime=_lambda.Runtime.PYTHON_3_9,
            code=_lambda.Code.from_asset('lambda'),
            handler='createGroup.handler',
        )

        self.outputLambda = gitlabUtilsLambda

我想使用 lambda 函数的 ApiGateway 堆栈:

from constructs import Construct
from aws_cdk import (
    Stack,
    aws_apigateway as apigw,
)


class ApiStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        api = apigw.LambdaRestApi(
            self, 'gitlab',
            handler=kwargs.get("gitlabUtilsLambda"),
            default_method_options=apigw.MethodOptions(api_key_required=True)
        )

        plan = api.add_usage_plan(
            id="UsagePlan")

        plan.add_api_stage(stage=api.deployment_stage)

        apiKey = api.add_api_key(
            id="MyKey", value="xxx")
        plan.add_api_key(apiKey)

我目前正在尝试将其与 handler=kwargs.get("gitlabUtilsLambda"), 一起使用,但这会导致错误。

您不能在 class (LambdaStack.outputLambda) 上调用 属性,您必须在 class (lambda_stack_instance.outputLambda) 的实例上调用它.

此外,与 kwargs 相比,更喜欢类型化参数:

import aws_cdk as cdk

from cdk.api_stack import ApiStack
from cdk.lambda_stack import LambdaStack


app = cdk.App()
lambda_stack = LambdaStack(app, "lambda")
ApiStack(app, "api", handler=lambda_stack.outputLambda)


app.synth()
from constructs import Construct
from aws_cdk import (
    Stack,
    aws_apigateway as apigw,
    aws_lambda as _lambda,
)


class ApiStack(Stack):

    def __init__(self, scope: Construct, construct_id: str, *,
        handler: _lambda.IFunction) -> None:
        
        super().__init__(scope, construct_id)

        api = apigw.LambdaRestApi(
            self, 'gitlab',
            handler=handler,
            default_method_options=apigw.MethodOptions(api_key_required=True)
        )

        plan = api.add_usage_plan(
            id="UsagePlan")

        plan.add_api_stage(stage=api.deployment_stage)

        apiKey = api.add_api_key(
            id="MyKey", value="xxx")
        plan.add_api_key(apiKey)