I have created a lambda function in one stack and now want to use it in my ApiGateway stack as lambda handler.
How can I pass a resource from one stack to another? I have only found either TypeScript examples or bad python examples that were either not working or missing the important step.
main
#!/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 Stack
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
The ApiGateway stack where i want to use the lambda function:
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)
Here I´m currently trying it to use with handler=kwargs.get("gitlabUtilsLambda"),
but this results in an error.
CodePudding user response:
You cannot call a property on a class (LambdaStack.outputLambda
), you must call it on an instance of this class (lambda_stack_instance.outputLambda
).
Additionnaly, prefer typed arguments over 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)