Search code examples
amazon-web-servicesaws-lambdaaws-lambda-layersaws-cdk

How to pass a variable to Lambda Layer in AWS


I have an AWS CDK app (in Python) that creates a Lambda Layer (LayerVersion). My code looks like this:

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

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

        MY_VAR = 'foobar'
        my_lambda_layer = _lambda.LayerVersion(self, 'MyLambdaLayer',
                                               code=AssetCode(path.join('..', 'my_lib')),
                                               )

I would like to pass a variable (let's call it MY_VAR) from the app to the Lambda Layer, so that my Lambda Layer code (in path ../my_lib) can use it.

If I were to pass such a variable to a Lambda instead of a Lambda Layer, I would do it like this:

lambda_with_env_var = _lambda.Function(self, "Lambda",
                                             code=_lambda.Code.from_asset(path.join('..', 'my_lib')),
                                             environment={
                                                 'MY_VAR': MY_VAR,
                                             },
                                             ...
                                       )

Unfortunately, Lambda Layer does not allow for environment parameter.

How can I achieve passing this function to Lambda Layer (LayerVersion)?


Solution

  • Just pass it to the Lambda itself, not the Layer.