Package: aws-cdk.aws-lambda
AWS Lambda Construct Library---AWS CDK v1 has reached End-of-Support on 2023-06-01.
This package is no longer being updated, and users should migrate to AWS CDK v2.For more information on how to migrate, see theMigrating to AWS CDK v2guide.This construct library allows you to define AWS Lambda Functions.fn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")))Handler CodeThelambda.Codeclass includes static convenience methods for various types of
runtime code.lambda.Code.fromBucket(bucket, key[, objectVersion])- specify an S3 object
that contains the archive of your runtime code.lambda.Code.fromInline(code)- inline the handle code as a string. This is
limited to supported runtimes and the code cannot exceed 4KiB.lambda.Code.fromAsset(path)- specify a directory or a .zip file in the local
filesystem which will be zipped and uploaded to S3 before deployment. See alsobundling asset code.lambda.Code.fromDockerBuild(path, options)- use the result of a Docker
build as code. The runtime code is expected to be located at/assetin the
image and will be zipped and uploaded to S3 as an asset.The following example shows how to define a Python function and deploy the code
from the local directorymy-lambda-handlerto it:lambda_.Function(self,"MyLambda",code=lambda_.Code.from_asset(path.join(__dirname,"my-lambda-handler")),handler="index.main",runtime=lambda_.Runtime.PYTHON_3_9)When deploying a stack that contains this code, the directory will be zip
archived and then uploaded to an S3 bucket, then the exact location of the S3
objects will be passed when the stack is deployed.During synthesis, the CDK expects to find a directory on disk at the asset
directory specified. Note that we are referencing the asset directory relatively
to our CDK project directory. This is especially important when we want to share
this construct through a library. Different programming languages will have
different techniques for bundling resources into libraries.Docker ImagesLambda functions allow specifying their handlers within docker images. The docker
image can be an image from ECR or a local asset that the CDK will package and load
into ECR.The followingDockerImageFunctionconstruct uses a local folder with a
Dockerfile as the asset that will be used as the function handler.lambda_.DockerImageFunction(self,"AssetFunction",code=lambda_.DockerImageCode.from_image_asset(path.join(__dirname,"docker-handler")))You can also specify an image that already exists in ECR as the function handler.importaws_cdk.aws_ecrasecrrepo=ecr.Repository(self,"Repository")lambda_.DockerImageFunction(self,"ECRFunction",code=lambda_.DockerImageCode.from_ecr(repo))The props for these docker image resources allow overriding the image'sCMD,ENTRYPOINT, andWORKDIRconfigurations as well as choosing a specific tag or digest. See their docs for more information.Execution RoleLambda functions assume an IAM role during execution. In CDK by default, Lambda
functions will use an autogenerated Role if one is not provided.The autogenerated Role is automatically given permissions to execute the Lambda
function. To reference the autogenerated Role:fn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")))role=fn.roleYou can also provide your own IAM role. Provided IAM roles will not automatically
be given permissions to execute the Lambda function. To provide a role and grant
it appropriate permissions:my_role=iam.Role(self,"My Role",assumed_by=iam.ServicePrincipal("lambda.amazonaws.com"))fn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),role=my_role)my_role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AWSLambdaBasicExecutionRole"))my_role.add_managed_policy(iam.ManagedPolicy.from_aws_managed_policy_name("service-role/AWSLambdaVPCAccessExecutionRole"))Function TimeoutAWS Lambda functions have a default timeout of 3 seconds, but this can be increased
up to 15 minutes. The timeout is available as a property ofFunctionso that
you can reference it elsewhere in your stack. For instance, you could use it to create
a CloudWatch alarm to report when your function timed out:importaws_cdk.coreascdkimportaws_cdk.aws_cloudwatchascloudwatchfn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),timeout=cdk.Duration.minutes(5))iffn.timeout:cloudwatch.Alarm(self,"MyAlarm",metric=fn.metric_duration().with(statistic="Maximum"),evaluation_periods=1,datapoints_to_alarm=1,threshold=fn.timeout.to_milliseconds(),treat_missing_data=cloudwatch.TreatMissingData.IGNORE,alarm_name="My Lambda Timeout")Resource-based PoliciesAWS Lambda supports resource-based policies for controlling access to Lambda
functions and layers on a per-resource basis. In particular, this allows you to
give permission to AWS services and other AWS accounts to modify and invoke your
functions. You can also restrict permissions given to AWS services by providing
a source account or ARN (representing the account and identifier of the resource
that accesses the function or layer).# fn: lambda.Functionprincipal=iam.ServicePrincipal("my-service")fn.grant_invoke(principal)# Equivalent to:fn.add_permission("my-service Invocation",principal=principal)For more information, seeResource-based
policiesin the AWS Lambda Developer Guide.Providing an unowned principal (such as account principals, generic ARN
principals, service principals, and principals in other accounts) to a call tofn.grantInvokewill result in a resource-based policy being created. If the
principal in question has conditions limiting the source account or ARN of the
operation (see above), these conditions will be automatically added to the
resource policy.# fn: lambda.Functionservice_principal=iam.ServicePrincipal("my-service")source_arn="arn:aws:s3:::my-bucket"source_account="111122223333"service_principal_with_conditions=service_principal.with_conditions({"ArnLike":{"aws:SourceArn":source_arn},"StringEquals":{"aws:SourceAccount":source_account}})fn.grant_invoke(service_principal_with_conditions)# Equivalent to:fn.add_permission("my-service Invocation",principal=service_principal,source_arn=source_arn,source_account=source_account)VersionsYou can useversionsto manage the deployment of your AWS Lambda functions. For example, you can
publish a new version of a function for beta testing without affecting users of
the stable production version.The function version includes the following information:The function code and all associated dependencies.The Lambda runtime that executes the function.All of the function settings, including the environment variables.A unique Amazon Resource Name (ARN) to identify this version of the function.You could create a version to your lambda function using theVersionconstruct.# fn: lambda.Functionversion=lambda_.Version(self,"MyVersion",lambda_=fn)The major caveat to know here is that a function version must always point to a
specific 'version' of the function. When the function is modified, the version
will continue to point to the 'then version' of the function.One way to ensure that thelambda.Versionalways points to the latest version
of yourlambda.Functionis to set an environment variable which changes at
least as often as your code does. This makes sure the function always has the
latest code. For instance -code_version="stringOrMethodToGetCodeVersion"fn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),environment={"CodeVersionString":code_version})Thefn.latestVersionproperty returns alambda.IVersionwhich represents
the$LATESTpseudo-version.However, most AWS services require a specific AWS Lambda version,
and won't allow you to use$LATEST. Therefore, you would normally want
to uselambda.currentVersion.Thefn.currentVersionproperty can be used to obtain alambda.Versionresource that represents the AWS Lambda function defined in your application.
Any change to your function's code or configuration will result in the creation
of a new version resource. You can specify options for this version through thecurrentVersionOptionsproperty.NOTE: ThecurrentVersionproperty is only supported when your AWS Lambda function
uses eitherlambda.Code.fromAssetorlambda.Code.fromInline. Other types
of code providers (such aslambda.Code.fromBucket) require that you define alambda.Versionresource directly since the CDK is unable to determine if
their contents had changed.currentVersion: Updated hashing logicTo produce a new lambda version each time the lambda function is modified, thecurrentVersionproperty under the hood, computes a new logical id based on the
properties of the function. This informs CloudFormation that a newAWS::Lambda::Versionresource should be created pointing to the updated Lambda
function.However, a bug was introduced in this calculation that caused the logical id to
change when it was not required (ex: when the Function'sTagsproperty, or
when theDependsOnclause was modified). This caused the deployment to fail
since the Lambda service does not allow creating duplicate versions.This has been fixed in the AWS CDK butexistingusers need to opt-in via afeature flag. Users who have runcdk initsince this fix will be opted in,
by default.Otherwise, you will need to enable thefeature flag@aws-cdk/aws-lambda:recognizeVersionProps. Since CloudFormation does not
allow duplicate versions, you will also need to make some modification to
your function so that a new version can be created. To efficiently and trivially
modify all your lambda functions at once, you can attach theFunctionVersionUpgradeaspect to the stack, which slightly alters the
function description. This aspect is intended for one-time use to upgrade the
version of all your functions at the same time, and can safely be removed after
deploying once.stack=Stack()Aspects.of(stack).add(lambda_.FunctionVersionUpgrade(LAMBDA_RECOGNIZE_VERSION_PROPS))When the new logic is in effect, you may rarely come across the following error:The following properties are not recognized as version properties. This will
occur, typically whenproperty overridesare used, when a new property
introduced inAWS::Lambda::Functionis used that CDK is still unaware of.To overcome this error, use the APIFunction.classifyVersionProperty()to
record whether a new version should be generated when this property is changed.
This can be typically determined by checking whether the property can be
modified using theUpdateFunctionConfigurationAPI or not.currentVersion: Updated hashing logic for layer versionsAn additional update to the hashing logic fixes two issues surrounding layers.
Prior to this change, updating the lambda layer version would have no effect on
the function version. Also, the order of lambda layers provided to the function
was unnecessarily baked into the hash.This has been fixed in the AWS CDK starting with version 2.27. If you rancdk initwith an earlier version, you will need to opt-in via afeature flag.
If you runcdk initwith v2.27 or later, this fix will be opted in, by default.Existing users will need to enable thefeature flag@aws-cdk/aws-lambda:recognizeLayerVersion. Since CloudFormation does not
allow duplicate versions, they will also need to make some modification to
their function so that a new version can be created. To efficiently and trivially
modify all your lambda functions at once, users can attach theFunctionVersionUpgradeaspect to the stack, which slightly alters the
function description. This aspect is intended for one-time use to upgrade the
version of all your functions at the same time, and can safely be removed after
deploying once.stack=Stack()Aspects.of(stack).add(lambda_.FunctionVersionUpgrade(LAMBDA_RECOGNIZE_LAYER_VERSION))AliasesYou can define one or morealiasesfor your AWS Lambda function. A Lambda alias is like a pointer to a specific
Lambda function version. Users can access the function version using the alias
ARN.Theversion.addAlias()method can be used to define an AWS Lambda alias that
points to a specific version.The following example defines an alias namedlivewhich will always point to a
version that represents the function as defined in your CDK app. When you change
your lambda code or configuration, a new resource will be created. You can
specify options for the current version through thecurrentVersionOptionsproperty.fn=lambda_.Function(self,"MyFunction",current_version_options=lambda.VersionOptions(removal_policy=RemovalPolicy.RETAIN,# retain old versionsretry_attempts=1),runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")))fn.add_alias("live")Function URLA function URL is a dedicated HTTP(S) endpoint for your Lambda function. When you create a function URL, Lambda automatically generates a unique URL endpoint for you. Function URLs can be created for the latest version Lambda Functions, or Function Aliases (but not for Versions).Function URLs are dual stack-enabled, supporting IPv4 and IPv6, and cross-origin resource sharing (CORS) configuration. After you configure a function URL for your function, you can invoke your function through its HTTP(S) endpoint via a web browser, curl, Postman, or any HTTP client. To invoke a function using IAM authentication your HTTP client must support SigV4 signing.See theInvoking Function URLssection of the AWS Lambda Developer Guide
for more information on the input and output payloads of Functions invoked in this way.IAM-authenticated Function URLsTo create a Function URL which can be called by an IAM identity, calladdFunctionUrl(), followed bygrantInvokeFunctionUrl():# Can be a Function or an Alias# fn: lambda.Function# my_role: iam.Rolefn_url=fn.add_function_url()fn_url.grant_invoke_url(my_role)CfnOutput(self,"TheUrl",# The .url attributes will return the unique Function URLvalue=fn_url.url)Calls to this URL need to be signed with SigV4.Anonymous Function URLsTo create a Function URL which can be called anonymously, passauthType: FunctionUrlAuthType.NONEtoaddFunctionUrl():# Can be a Function or an Alias# fn: lambda.Functionfn_url=fn.add_function_url(auth_type=lambda_.FunctionUrlAuthType.NONE)CfnOutput(self,"TheUrl",value=fn_url.url)CORS configuration for Function URLsIf you want your Function URLs to be invokable from a web page in browser, you
will need to configure cross-origin resource sharing to allow the call (if you do
not do this, your browser will refuse to make the call):# fn: lambda.Functionfn.add_function_url(auth_type=lambda_.FunctionUrlAuthType.NONE,cors=lambda.FunctionUrlCorsOptions(# Allow this to be called from websites on https://example.com.# Can also be ['*'] to allow all domain.allowed_origins=["https://example.com"]))LayersThelambda.LayerVersionclass can be used to define Lambda layers and manage
granting permissions to other AWS accounts or organizations.layer=lambda_.LayerVersion(stack,"MyLayer",code=lambda_.Code.from_asset(path.join(__dirname,"layer-code")),compatible_runtimes=[lambda_.Runtime.NODEJS_14_X],license="Apache-2.0",description="A layer to test the L2 construct")# To grant usage by other AWS accountslayer.add_permission("remote-account-grant",account_id=aws_account_id)# To grant usage to all accounts in some AWS Ogranization# layer.grantUsage({ accountId: '*', organizationId });lambda_.Function(stack,"MyLayeredLambda",code=lambda_.InlineCode("foo"),handler="index.handler",runtime=lambda_.Runtime.NODEJS_14_X,layers=[layer])By default, updating a layer creates a new layer version, and CloudFormation will delete the old version as part of the stack update.Alternatively, a removal policy can be used to retain the old version:lambda_.LayerVersion(self,"MyLayer",removal_policy=RemovalPolicy.RETAIN,code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")))ArchitectureLambda functions, by default, run on compute systems that have the 64 bit x86 architecture.The AWS Lambda service also runs compute on the ARM architecture, which can reduce cost
for some workloads.A lambda function can be configured to be run on one of these platforms:lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),architecture=lambda_.Architecture.ARM_64)Similarly, lambda layer versions can also be tagged with architectures it is compatible with.lambda_.LayerVersion(self,"MyLayer",removal_policy=RemovalPolicy.RETAIN,code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),compatible_architectures=[lambda_.Architecture.X86_64,lambda_.Architecture.ARM_64])Lambda InsightsLambda functions can be configured to use CloudWatchLambda Insightswhich provides low-level runtime metrics for a Lambda functions.lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),insights_version=lambda_.LambdaInsightsVersion.VERSION_1_0_98_0)If the version of insights is not yet available in the CDK, you can also provide the ARN directly as so -layer_arn="arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14"lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),insights_version=lambda_.LambdaInsightsVersion.from_insight_version_arn(layer_arn))If you are deploying an ARM_64 Lambda Function, you must specify a
Lambda Insights Version >=1_0_119_0.lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",architecture=lambda_.Architecture.ARM_64,code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),insights_version=lambda_.LambdaInsightsVersion.VERSION_1_0_119_0)Event Rule TargetYou can use an AWS Lambda function as a target for an Amazon CloudWatch event
rule:importaws_cdk.aws_eventsaseventsimportaws_cdk.aws_events_targetsastargets# fn: lambda.Functionrule=events.Rule(self,"Schedule Rule",schedule=events.Schedule.cron(minute="0",hour="4"))rule.add_target(targets.LambdaFunction(fn))Event SourcesAWS Lambda supports avariety of event sources.In most cases, it is possible to trigger a function as a result of an event by
using one of theadd<Event>Notificationmethods on the source construct. For
example, thes3.Bucketconstruct has anonEventmethod which can be used to
trigger a Lambda when an event, such as PutObject occurs on an S3 bucket.An alternative way to add event sources to a function is to usefunction.addEventSource(source).
This method accepts anIEventSourceobject. The module@aws-cdk/aws-lambda-event-sourcesincludes classes for the various event sources supported by AWS Lambda.For example, the following code adds an SQS queue as an event source for a function:importaws_cdk.aws_lambda_event_sourcesaseventsourcesimportaws_cdk.aws_sqsassqs# fn: lambda.Functionqueue=sqs.Queue(self,"Queue")fn.add_event_source(eventsources.SqsEventSource(queue))The following code adds an S3 bucket notification as an event source:importaws_cdk.aws_lambda_event_sourcesaseventsourcesimportaws_cdk.aws_s3ass3# fn: lambda.Functionbucket=s3.Bucket(self,"Bucket")fn.add_event_source(eventsources.S3EventSource(bucket,events=[s3.EventType.OBJECT_CREATED,s3.EventType.OBJECT_REMOVED],filters=[s3.NotificationKeyFilter(prefix="subdir/")]))See the documentation for the@aws-cdk/aws-lambda-event-sourcesmodule for more details.Imported LambdasWhen referencing an imported lambda in the CDK, usefromFunctionArn()for most use cases:fn=lambda_.Function.from_function_arn(self,"Function","arn:aws:lambda:us-east-1:123456789012:function:MyFn")ThefromFunctionAttributes()API is available for more specific use cases:fn=lambda_.Function.from_function_attributes(self,"Function",function_arn="arn:aws:lambda:us-east-1:123456789012:function:MyFn",# The following are optional properties for specific use cases and should be used with caution:# Use Case: imported function is in the same account as the stack. This tells the CDK that it# can modify the function's permissions.same_environment=True,# Use Case: imported function is in a different account and user commits to ensuring that the# imported function has the correct permissions outside the CDK.skip_permissions=True)IffromFunctionArn()causes an error related to having to provide an account and/or region in a different construct,
and the lambda is in the same account and region as the stack you're importing it into,
you can useFunction.fromFunctionName()instead:fn=lambda_.Function.from_function_name(self,"Function","MyFn")Lambda with DLQA dead-letter queue can be automatically created for a Lambda function by
setting thedeadLetterQueueEnabled: trueconfiguration. In such case CDK creates
asqs.QueueasdeadLetterQueue.fn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null,\"hi\"); }"),dead_letter_queue_enabled=True)It is also possible to provide a dead-letter queue instead of getting a new queue created:importaws_cdk.aws_sqsassqsdlq=sqs.Queue(self,"DLQ")fn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null,\"hi\"); }"),dead_letter_queue=dlq)You can also use asns.Topicinstead of ansqs.Queueas dead-letter queue:importaws_cdk.aws_snsassnsdlt=sns.Topic(self,"DLQ")fn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_inline("// your code here"),dead_letter_topic=dlt)Seethe AWS documentationto learn more about AWS Lambdas and DLQs.Lambda with X-Ray Tracingfn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null,\"hi\"); }"),tracing=lambda_.Tracing.ACTIVE)Seethe AWS documentationto learn more about AWS Lambda's X-Ray support.Lambda with ProfilingThe following code configures the lambda function with CodeGuru profiling. By default, this creates a new CodeGuru
profiling group -fn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.PYTHON_3_9,handler="index.handler",code=lambda_.Code.from_asset("lambda-handler"),profiling=True)TheprofilingGroupproperty can be used to configure an existing CodeGuru profiler group.CodeGuru profiling is supported for all Java runtimes and Python3.6+ runtimes.Seethe AWS documentationto learn more about AWS Lambda's Profiling support.Lambda with Reserved Concurrent Executionsfn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null,\"hi\"); }"),reserved_concurrent_executions=100)Seethe AWS documentationmanaging concurrency.AutoScalingYou can use Application AutoScaling to automatically configure the provisioned concurrency for your functions. AutoScaling can be set to track utilization or be based on a schedule. To configure AutoScaling on a function alias:importaws_cdk.aws_autoscalingasautoscaling# fn: lambda.Functionalias=fn.add_alias("prod")# Create AutoScaling targetas=alias.add_auto_scaling(max_capacity=50)# Configure Target Trackingas.scale_on_utilization(utilization_target=0.5)# Configure Scheduled Scalingas.scale_on_schedule("ScaleUpInTheMorning",schedule=autoscaling.Schedule.cron(hour="8",minute="0"),min_capacity=20)importaws_cdk.aws_applicationautoscalingasappscalingimportaws_cdk.coreascdkfromaws_cdk.cx_apiimportLAMBDA_RECOGNIZE_LAYER_VERSIONimportaws_cdk.aws_lambdaaslambda_## Stack verification steps:# aws application-autoscaling describe-scalable-targets --service-namespace lambda --resource-ids function:<function name>:prod# has a minCapacity of 3 and maxCapacity of 50#classTestStack(cdk.Stack):def__init__(self,scope,id):super().__init__(scope,id)fn=lambda_.Function(self,"MyLambda",code=lambda_.InlineCode("exports.handler = async () => { console.log('hello world'); };"),handler="index.handler",runtime=lambda_.Runtime.NODEJS_14_X)version=fn.current_versionalias=lambda_.Alias(self,"Alias",alias_name="prod",version=version)scaling_target=alias.add_auto_scaling(min_capacity=3,max_capacity=50)scaling_target.scale_on_utilization(utilization_target=0.5)scaling_target.scale_on_schedule("ScaleUpInTheMorning",schedule=appscaling.Schedule.cron(hour="8",minute="0"),min_capacity=20)scaling_target.scale_on_schedule("ScaleDownAtNight",schedule=appscaling.Schedule.cron(hour="20",minute="0"),max_capacity=20)cdk.CfnOutput(self,"FunctionName",value=fn.function_name)app=cdk.App()stack=TestStack(app,"aws-lambda-autoscaling")# Changes the function description when the feature flag is present# to validate the changed function hash.cdk.Aspects.of(stack).add(lambda_.FunctionVersionUpgrade(LAMBDA_RECOGNIZE_LAYER_VERSION))app.synth()Seethe AWS documentationon autoscaling lambda functions.Log GroupLambda functions automatically create a log group with the name/aws/lambda/<function-name>upon first execution with
log data set to never expire.ThelogRetentionproperty can be used to set a different expiration period.It is possible to obtain the function's log group as alogs.ILogGroupby calling thelogGroupproperty of theFunctionconstruct.By default, CDK uses the AWS SDK retry options when creating a log group. ThelogRetentionRetryOptionsproperty
allows you to customize the maximum number of retries and base backoff duration.Notethat, if eitherlogRetentionis set orlogGroupproperty is called, aCloudFormation custom
resourceis added
to the stack that pre-creates the log group as part of the stack deployment, if it already doesn't exist, and sets the
correct log retention period (never expire, by default).Further notethat, if the log group already exists and thelogRetentionis not set, the custom resource will reset
the log retention to never expire even if it was configured with a different value.FileSystem AccessYou can configure a function to mount an Amazon Elastic File System (Amazon EFS) to a
directory in your runtime environment with thefilesystemproperty. To access Amazon EFS
from lambda function, the Amazon EFS access point will be required.The following sample allows the lambda function to mount the Amazon EFS access point to/mnt/msgin the runtime environment and access the filesystem with the POSIX identity defined inposixUser.importaws_cdk.aws_ec2asec2importaws_cdk.aws_efsasefs# create a new VPCvpc=ec2.Vpc(self,"VPC")# create a new Amazon EFS filesystemfile_system=efs.FileSystem(self,"Efs",vpc=vpc)# create a new access point from the filesystemaccess_point=file_system.add_access_point("AccessPoint",# set /export/lambda as the root of the access pointpath="/export/lambda",# as /export/lambda does not exist in a new efs filesystem, the efs will create the directory with the following createAclcreate_acl=efs.Acl(owner_uid="1001",owner_gid="1001",permissions="750"),# enforce the POSIX identity so lambda function will access with this identityposix_user=efs.PosixUser(uid="1001",gid="1001"))fn=lambda_.Function(self,"MyLambda",# mount the access point to /mnt/msg in the lambda runtime environmentfilesystem=lambda_.FileSystem.from_efs_access_point(access_point,"/mnt/msg"),runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),vpc=vpc)Ephemeral StorageYou can configure ephemeral storage on a function to control the amount of storage it gets for reading
or writing data, allowing you to use AWS Lambda for ETL jobs, ML inference, or other data-intensive workloads.
The ephemeral storage will be accessible in the functions'/tmpdirectory.fromaws_cdk.coreimportSizefn=lambda_.Function(self,"MyFunction",runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")),ephemeral_storage_size=Size.mebibytes(1024))Read more about using this feature inthis AWS blog post.Singleton FunctionTheSingletonFunctionconstruct is a way to guarantee that a lambda function will be guaranteed to be part of the stack,
once and only once, irrespective of how many times the construct is declared to be part of the stack. This is guaranteed
as long as theuuidproperty and the optionallambdaPurposeproperty stay the same whenever they're declared into the
stack.A typical use case of this function is when a higher level construct needs to declare a Lambda function as part of it but
needs to guarantee that the function is declared once. However, a user of this higher level construct can declare it any
number of times and with different properties. UsingSingletonFunctionhere with a fixeduuidwill guarantee this.For example, theLogRetentionconstruct requires only one single lambda function for all different log groups whose
retention it seeks to manage.Bundling Asset CodeWhen usinglambda.Code.fromAsset(path)it is possible to bundle the code by running a
command in a Docker container. The asset path will be mounted at/asset-input. The
Docker container is responsible for putting content at/asset-output. The content at/asset-outputwill be zipped and used as Lambda code.Example with Python:lambda_.Function(self,"Function",code=lambda_.Code.from_asset(path.join(__dirname,"my-python-handler"),bundling=BundlingOptions(image=lambda_.Runtime.PYTHON_3_9.bundling_image,command=["bash","-c","pip install -r requirements.txt -t /asset-output && cp -au . /asset-output"])),runtime=lambda_.Runtime.PYTHON_3_9,handler="index.handler")Runtimes expose abundlingImageproperty that points to theAWS SAMbuild image.Usecdk.DockerImage.fromRegistry(image)to use an existing image orcdk.DockerImage.fromBuild(path)to build a specific image:lambda_.Function(self,"Function",code=lambda_.Code.from_asset("/path/to/handler",bundling=BundlingOptions(image=DockerImage.from_build("/path/to/dir/with/DockerFile",build_args={"ARG1":"value1"}),command=["my","cool","command"])),runtime=lambda_.Runtime.PYTHON_3_9,handler="index.handler")Language-specific APIsLanguage-specific higher level constructs are provided in separate modules:@aws-cdk/aws-lambda-nodejs:Github&CDK Docs@aws-cdk/aws-lambda-python:Github&CDK DocsCode SigningCode signing for AWS Lambda helps to ensure that only trusted code runs in your Lambda functions.
When enabled, AWS Lambda checks every code deployment and verifies that the code package is signed by a trusted source.
For more information, seeConfiguring code signing for AWS Lambda.
The following code configures a function with code signing.importaws_cdk.aws_signerassignersigning_profile=signer.SigningProfile(self,"SigningProfile",platform=signer.Platform.AWS_LAMBDA_SHA384_ECDSA)code_signing_config=lambda_.CodeSigningConfig(self,"CodeSigningConfig",signing_profiles=[signing_profile])lambda_.Function(self,"Function",code_signing_config=code_signing_config,runtime=lambda_.Runtime.NODEJS_16_X,handler="index.handler",code=lambda_.Code.from_asset(path.join(__dirname,"lambda-handler")))