Skip to content
v2.273.0

AWS Lambda Construct Library ​

This construct library allows you to define AWS Lambda Functions.

ts
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});
python
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)
java
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .build();
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
})

When deployed, this construct creates or updates an existing AWS::Lambda::Function resource. When updating, AWS CloudFormation calls the UpdateFunctionConfiguration and UpdateFunctionCode Lambda APIs under the hood. Because these calls happen sequentially, and invocations can happen between these calls, your function may encounter errors in the time between the calls. For example, if you update an existing Lambda function by removing an environment variable and the code that references that environment variable in the same CDK deployment, you may see invocation errors related to a missing environment variable. To work around this, you can invoke your function against a version or alias by default, rather than the $LATEST version.

To further mitigate these issues, you can ensure consistency between your function code and infrastructure configuration by defining environment variables as a single source of truth in your CDK stack. You can define them in a separate env.ts file and reference them in both your handler and CDK configuration. This approach allows you to catch errors at compile time, benefit from improved IDE support, minimize the risk of mismatched configurations, and enhance maintainability.

Handler Code ​

The lambda.Code class 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.fromBucketV2(bucket, key, {objectVersion: version, sourceKMSKey: key}) - specify an S3 object that contains the archive of your runtime code.
ts

import { Key } from 'aws-cdk-lib/aws-kms';
import * as s3 from 'aws-cdk-lib/aws-s3';

const bucket = new s3.Bucket(this, 'Bucket');
declare const key: Key;

const options = {
    sourceKMSKey: key,
};
const fnBucket = new lambda.Function(this, 'myFunction2', {
    runtime: lambda.Runtime.NODEJS_LATEST,
    handler: 'index.handler',
    code: lambda.Code.fromBucketV2(bucket, 'python-lambda-handler.zip', options),
});

  • lambda.Code.fromInline(code) - inline the handle code as a string. This is limited to supported runtimes.
  • 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 also bundling 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 /asset in the image and will be zipped and uploaded to S3 as an asset.
  • lambda.Code.fromCustomCommand(output, command, customCommandOptions) - supply a command that is invoked during cdk synth. That command is meant to direct the generated code to output (a zip file or a directory), which is then used as the code for the created AWS Lambda.

Self-managed S3 code storage ​

Use S3ObjectStorageMode.REFERENCE with Code.fromBucketV2() to have Lambda reference the deployment package directly from your S3 bucket instead of copying it into Lambda-managed storage. Lambda requires a versioned S3 object for this mode.

ts
import * as s3 from 'aws-cdk-lib/aws-s3';

declare const bucket: s3.IBucket;
declare const objectVersion: string;

new lambda.Function(this, 'MyFunction', {
  functionName: 'my-function',
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromBucketV2(bucket, 'my-function.zip', {
    objectVersion,
    s3ObjectStorageMode: lambda.S3ObjectStorageMode.REFERENCE,
  }),
});

new lambda.LayerVersion(this, 'MyLayer', {
  layerVersionName: 'my-layer',
  code: lambda.Code.fromBucketV2(bucket, 'my-layer.zip', {
    objectVersion,
    s3ObjectStorageMode: lambda.S3ObjectStorageMode.REFERENCE,
  }),
});
python
import aws_cdk.aws_s3 as s3

# bucket: s3.IBucket
# object_version: str


lambda_.Function(self, "MyFunction",
    function_name="my-function",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_bucket_v2(bucket, "my-function.zip",
        object_version=object_version,
        s3_object_storage_mode=lambda_.S3ObjectStorageMode.REFERENCE
    )
)

lambda_.LayerVersion(self, "MyLayer",
    layer_version_name="my-layer",
    code=lambda_.Code.from_bucket_v2(bucket, "my-layer.zip",
        object_version=object_version,
        s3_object_storage_mode=lambda_.S3ObjectStorageMode.REFERENCE
    )
)
java
import software.amazon.awscdk.services.s3.*;

IBucket bucket;
String objectVersion;


Function.Builder.create(this, "MyFunction")
        .functionName("my-function")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromBucketV2(bucket, "my-function.zip", BucketOptions.builder()
                .objectVersion(objectVersion)
                .s3ObjectStorageMode(S3ObjectStorageMode.REFERENCE)
                .build()))
        .build();

LayerVersion.Builder.create(this, "MyLayer")
        .layerVersionName("my-layer")
        .code(Code.fromBucketV2(bucket, "my-layer.zip", BucketOptions.builder()
                .objectVersion(objectVersion)
                .s3ObjectStorageMode(S3ObjectStorageMode.REFERENCE)
                .build()))
        .build();
csharp
using Amazon.CDK.AWS.S3;

IBucket bucket;
string objectVersion;


new Function(this, "MyFunction", new FunctionProps {
    FunctionName = "my-function",
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromBucketV2(bucket, "my-function.zip", new BucketOptions {
        ObjectVersion = objectVersion,
        S3ObjectStorageMode = S3ObjectStorageMode.REFERENCE
    })
});

new LayerVersion(this, "MyLayer", new LayerVersionProps {
    LayerVersionName = "my-layer",
    Code = Code.FromBucketV2(bucket, "my-layer.zip", new BucketOptions {
        ObjectVersion = objectVersion,
        S3ObjectStorageMode = S3ObjectStorageMode.REFERENCE
    })
});
go
import s3 "github.com/aws/aws-cdk-go/awscdk"

var bucket IBucket
var objectVersion string


lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	FunctionName: jsii.String("my-function"),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromBucketV2(bucket, jsii.String("my-function.zip"), &BucketOptions{
		ObjectVersion: jsii.String(*ObjectVersion),
		S3ObjectStorageMode: lambda.S3ObjectStorageMode_REFERENCE,
	}),
})

lambda.NewLayerVersion(this, jsii.String("MyLayer"), &LayerVersionProps{
	LayerVersionName: jsii.String("my-layer"),
	Code: lambda.Code_*FromBucketV2(bucket, jsii.String("my-layer.zip"), &BucketOptions{
		ObjectVersion: jsii.String(*ObjectVersion),
		S3ObjectStorageMode: lambda.S3ObjectStorageMode_REFERENCE,
	}),
})

When using REFERENCE, CDK grants the Lambda service principal permission to call s3:GetObject and s3:GetObjectVersion for the referenced object. The grant is scoped to the function or layer name when a concrete name is specified. If the name is unresolved or generated by CloudFormation, the grant is scoped to functions or layers in the same account and CDK emits a warning. Specify functionName or layerVersionName to scope the policy to a particular resource.

For deployment packages encrypted with a customer-managed KMS key, configure the bucket with its encryptionKey. CDK grants the Lambda service principal kms:Decrypt permission on that key. When importing an encrypted bucket, use Bucket.fromBucketAttributes() and provide its encryptionKey; CDK cannot infer the key from the bucket name or ARN. If the source bucket or bucket encryption key is imported and its policy cannot be modified by CDK, configure the required permissions before deployment. The sourceKMSKey option configures encryption of Lambda-managed code storage and is not the key used to decrypt the original object in REFERENCE mode. See Self-managed S3 code storage for the required bucket and key policies.

The following example shows how to define a Python function and deploy the code from the local directory my-lambda-handler to it:

ts
new lambda.Function(this, 'MyLambda', {
  code: lambda.Code.fromAsset(path.join(__dirname, 'my-lambda-handler')),
  handler: 'index.main',
  runtime: lambda.Runtime.PYTHON_3_9,
});
python
lambda_.Function(self, "MyLambda",
    code=lambda_.Code.from_asset(path.join(__dirname, "my-lambda-handler")),
    handler="index.main",
    runtime=lambda_.Runtime.PYTHON_3_9
)
java
Function.Builder.create(this, "MyLambda")
        .code(Code.fromAsset(join(__dirname, "my-lambda-handler")))
        .handler("index.main")
        .runtime(Runtime.PYTHON_3_9)
        .build();
csharp
new Function(this, "MyLambda", new FunctionProps {
    Code = Code.FromAsset(Join(__dirname, "my-lambda-handler")),
    Handler = "index.main",
    Runtime = Runtime.PYTHON_3_9
});
go
lambda.NewFunction(this, jsii.String("MyLambda"), &FunctionProps{
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("my-lambda-handler"))),
	Handler: jsii.String("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 Images ​

Lambda 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 following DockerImageFunction construct uses a local folder with a Dockerfile as the asset that will be used as the function handler.

ts
new lambda.DockerImageFunction(this, 'AssetFunction', {
  code: lambda.DockerImageCode.fromImageAsset(path.join(__dirname, 'docker-handler')),
});
python
lambda_.DockerImageFunction(self, "AssetFunction",
    code=lambda_.DockerImageCode.from_image_asset(path.join(__dirname, "docker-handler"))
)
java
DockerImageFunction.Builder.create(this, "AssetFunction")
        .code(DockerImageCode.fromImageAsset(join(__dirname, "docker-handler")))
        .build();
csharp
new DockerImageFunction(this, "AssetFunction", new DockerImageFunctionProps {
    Code = DockerImageCode.FromImageAsset(Join(__dirname, "docker-handler"))
});
go
lambda.NewDockerImageFunction(this, jsii.String("AssetFunction"), &DockerImageFunctionProps{
	Code: lambda.DockerImageCode_FromImageAsset(path.join(__dirname, jsii.String("docker-handler"))),
})

You can also specify an image that already exists in ECR as the function handler.

ts
import * as ecr from 'aws-cdk-lib/aws-ecr';
const repo = new ecr.Repository(this, 'Repository');

new lambda.DockerImageFunction(this, 'ECRFunction', {
  code: lambda.DockerImageCode.fromEcr(repo),
});
python
import aws_cdk.aws_ecr as ecr

repo = ecr.Repository(self, "Repository")

lambda_.DockerImageFunction(self, "ECRFunction",
    code=lambda_.DockerImageCode.from_ecr(repo)
)
java
import software.amazon.awscdk.services.ecr.*;

Repository repo = new Repository(this, "Repository");

DockerImageFunction.Builder.create(this, "ECRFunction")
        .code(DockerImageCode.fromEcr(repo))
        .build();
csharp
using Amazon.CDK.AWS.ECR;

var repo = new Repository(this, "Repository");

new DockerImageFunction(this, "ECRFunction", new DockerImageFunctionProps {
    Code = DockerImageCode.FromEcr(repo)
});
go
import ecr "github.com/aws/aws-cdk-go/awscdk"

repo := ecr.NewRepository(this, jsii.String("Repository"))

lambda.NewDockerImageFunction(this, jsii.String("ECRFunction"), &DockerImageFunctionProps{
	Code: lambda.DockerImageCode_FromEcr(repo),
})

The props for these docker image resources allow overriding the image's CMD, ENTRYPOINT, and WORKDIR configurations as well as choosing a specific tag or digest. See their docs for more information.

To deploy a DockerImageFunction on Lambda arm64 architecture, specify Architecture.ARM_64 in architecture. This will bundle docker image assets for arm64 architecture with --platform linux/arm64 even if build within an x86_64 host.

With that being said, if you are bundling DockerImageFunction for Lambda amd64 architecture from a arm64 machine like a Macbook with arm64 CPU, you would need to specify architecture: lambda.Architecture.X86_64 as well. This ensures the --platform argument is passed to the image assets bundling process so you can bundle up X86_64 images from the arm64 machine.

ts
new lambda.DockerImageFunction(this, 'AssetFunction', {
  code: lambda.DockerImageCode.fromImageAsset(path.join(__dirname, 'docker-arm64-handler')),
  architecture: lambda.Architecture.ARM_64,
});
python
lambda_.DockerImageFunction(self, "AssetFunction",
    code=lambda_.DockerImageCode.from_image_asset(path.join(__dirname, "docker-arm64-handler")),
    architecture=lambda_.Architecture.ARM_64
)
java
DockerImageFunction.Builder.create(this, "AssetFunction")
        .code(DockerImageCode.fromImageAsset(join(__dirname, "docker-arm64-handler")))
        .architecture(Architecture.ARM_64)
        .build();
csharp
new DockerImageFunction(this, "AssetFunction", new DockerImageFunctionProps {
    Code = DockerImageCode.FromImageAsset(Join(__dirname, "docker-arm64-handler")),
    Architecture = Architecture.ARM_64
});
go
lambda.NewDockerImageFunction(this, jsii.String("AssetFunction"), &DockerImageFunctionProps{
	Code: lambda.DockerImageCode_FromImageAsset(path.join(__dirname, jsii.String("docker-arm64-handler"))),
	Architecture: lambda.Architecture_ARM_64(),
})

Execution Role ​

Lambda 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:

ts
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});

const role = fn.role; // the Role
python
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)

role = fn.role
java
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .build();

IRole role = fn.getRole();
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});

var role = fn.Role;
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
})

role := fn.Role

You 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:

ts
const myRole = new iam.Role(this, 'My Role', {
  assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});

const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  role: myRole, // user-provided role
});

myRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"));
myRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole")); // only required if your function lives in a VPC
python
my_role = iam.Role(self, "My Role",
    assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)

fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    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"))
java
Role myRole = Role.Builder.create(this, "My Role")
        .assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
        .build();

Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .role(myRole)
        .build();

myRole.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"));
myRole.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole"));
csharp
var myRole = new Role(this, "My Role", new RoleProps {
    AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});

var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    Role = myRole
});

myRole.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"));
myRole.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole"));
go
myRole := iam.NewRole(this, jsii.String("My Role"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})

fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	Role: myRole,
})

myRole.AddManagedPolicy(iam.ManagedPolicy_FromAwsManagedPolicyName(jsii.String("service-role/AWSLambdaBasicExecutionRole")))
myRole.AddManagedPolicy(iam.ManagedPolicy_FromAwsManagedPolicyName(jsii.String("service-role/AWSLambdaVPCAccessExecutionRole")))

Function Timeout ​

AWS 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 of Function so 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:

ts
import * as cdk from 'aws-cdk-lib';
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';

const fn = new lambda.Function(this, 'MyFunction', {
   runtime: lambda.Runtime.NODEJS_LATEST,
   handler: 'index.handler',
   code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
   timeout: Duration.minutes(5),
});

if (fn.timeout) {
   new cloudwatch.Alarm(this, `MyAlarm`, {
      metric: fn.metricDuration().with({
         statistic: 'Maximum',
      }),
      evaluationPeriods: 1,
      datapointsToAlarm: 1,
      threshold: fn.timeout.toMilliseconds(),
      treatMissingData: cloudwatch.TreatMissingData.IGNORE,
      alarmName: 'My Lambda Timeout',
   });
}
python
import aws_cdk as cdk
import aws_cdk.aws_cloudwatch as cloudwatch


fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    timeout=Duration.minutes(5)
)

if fn.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"
    )
java
import software.amazon.awscdk.*;
import software.amazon.awscdk.services.cloudwatch.*;


Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .timeout(Duration.minutes(5))
        .build();

if (fn.getTimeout()) {
    Alarm.Builder.create(this, "MyAlarm")
            .metric(fn.metricDuration().with(MetricOptions.builder()
                    .statistic("Maximum")
                    .build()))
            .evaluationPeriods(1)
            .datapointsToAlarm(1)
            .threshold(fn.timeout.toMilliseconds())
            .treatMissingData(TreatMissingData.IGNORE)
            .alarmName("My Lambda Timeout")
            .build();
}
csharp
using Amazon.CDK;
using Amazon.CDK.AWS.CloudWatch;


var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    Timeout = Duration.Minutes(5)
});

if (fn.Timeout)
{
    new Alarm(this, "MyAlarm", new AlarmProps {
        Metric = fn.MetricDuration().With(new MetricOptions {
            Statistic = "Maximum"
        }),
        EvaluationPeriods = 1,
        DatapointsToAlarm = 1,
        Threshold = fn.Timeout.ToMilliseconds(),
        TreatMissingData = TreatMissingData.IGNORE,
        AlarmName = "My Lambda Timeout"
    });
}
go
import cdk "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"


fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	Timeout: awscdk.Duration_Minutes(jsii.Number(5)),
})

if fn.Timeout {
	cloudwatch.NewAlarm(this, jsii.String("MyAlarm"), &AlarmProps{
		Metric: fn.metricDuration().With(&MetricOptions{
			Statistic: jsii.String("Maximum"),
		}),
		EvaluationPeriods: jsii.Number(1),
		DatapointsToAlarm: jsii.Number(1),
		Threshold: fn.*Timeout.ToMilliseconds(),
		TreatMissingData: cloudwatch.TreatMissingData_IGNORE,
		AlarmName: jsii.String("My Lambda Timeout"),
	})
}

Advanced Logging ​

You can have more control over your function logs, by specifying the log format (Json or plain text), the system log level, the application log level, as well as choosing the log group:

ts
import { ILogGroup } from 'aws-cdk-lib/aws-logs';

declare const logGroup: ILogGroup;

new lambda.Function(this, 'Lambda', {
  code: new lambda.InlineCode('foo'),
  handler: 'index.handler',
  runtime: lambda.Runtime.NODEJS_LATEST,
  loggingFormat: lambda.LoggingFormat.JSON,
  systemLogLevelV2: lambda.SystemLogLevel.INFO,
  applicationLogLevelV2: lambda.ApplicationLogLevel.INFO,
  logGroup: logGroup,
});
python
from aws_cdk.aws_logs import ILogGroup

# log_group: ILogGroup


lambda_.Function(self, "Lambda",
    code=lambda_.InlineCode("foo"),
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    logging_format=lambda_.LoggingFormat.JSON,
    system_log_level_v2=lambda_.SystemLogLevel.INFO,
    application_log_level_v2=lambda_.ApplicationLogLevel.INFO,
    log_group=log_group
)
java
import software.amazon.awscdk.services.logs.ILogGroup;

ILogGroup logGroup;


Function.Builder.create(this, "Lambda")
        .code(new InlineCode("foo"))
        .handler("index.handler")
        .runtime(Runtime.NODEJS_LATEST)
        .loggingFormat(LoggingFormat.JSON)
        .systemLogLevelV2(SystemLogLevel.INFO)
        .applicationLogLevelV2(ApplicationLogLevel.INFO)
        .logGroup(logGroup)
        .build();
csharp
using Amazon.CDK.AWS.Logs;

ILogGroup logGroup;


new Function(this, "Lambda", new FunctionProps {
    Code = new InlineCode("foo"),
    Handler = "index.handler",
    Runtime = Runtime.NODEJS_LATEST,
    LoggingFormat = LoggingFormat.JSON,
    SystemLogLevelV2 = SystemLogLevel.INFO,
    ApplicationLogLevelV2 = ApplicationLogLevel.INFO,
    LogGroup = logGroup
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var logGroup ILogGroup


lambda.NewFunction(this, jsii.String("Lambda"), &FunctionProps{
	Code: lambda.NewInlineCode(jsii.String("foo")),
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	LoggingFormat: lambda.LoggingFormat_JSON,
	SystemLogLevelV2: lambda.SystemLogLevel_INFO,
	ApplicationLogLevelV2: lambda.ApplicationLogLevel_INFO,
	LogGroup: logGroup,
})

To use applicationLogLevelV2 and/or systemLogLevelV2 you must set loggingFormat to LoggingFormat.JSON.

Customizing Log Group Creation ​

Log Group Creation Methods ​

MethodDescriptionTag PropagationProp InjectionAspectsNotes
logRetention propLegacy approach using Custom ResourceFalseFalseFalseDoes not support TPA
logGroup propExplicitly supplied by user in CDK appTrueTrueTrueFull support for TPA
Lazy creationLambda service creates logGroup on first invocationFalseFalseFalseOccurs when both logRetention and logGroup are undefined and USE_CDK_MANAGED_LAMBDA_LOGGROUP is false
USE_CDK_MANAGED_LAMBDA_LOGGROUPCDK Lambda function construct creates log group with default propsTrueTrueTrueFeature flag must be enabled

TPA: Tag propagation, Prop Injection, Aspects

Order of precedence ​

text
                       Highest Precedence
                             |
             +---------------+---------------+
             |                               |
  +-------------------------+      +------------------------+
  |   logRetention is set   |      |     logGroup is set    |
  +-----------+-------------+      +----------+-------------+
              |                               |
              v                               v
      Create LogGroup via            Use the provided LogGroup
  Custom Resource (retention       instance (CDK-managed,
  managed, logGroup disallowed)    logRetention disallowed)
              |                               |
              +---------------+---------------+
                              |
                              v
          +-----------------------------------------------+
          |         Feature flag enabled:                 |
          | aws-cdk:aws-lambda:useCdkManagedLogGroup      |
          +------------------ +---------------------------+
                              |
                              v
              Create LogGroup at synth time
          (CDK-managed, default settings for logGroup)
                              |
                              v
                  +---------------------------+
                  | Default (no config set)   |
                  +------------+--------------+
                              |
                              v
     Lambda service creates log group on first invocation runtime
            (CDK does not manage the log group resource)

Tag Propagation ​

Refer section Log Group Creation Methods to find out which modes support tag propagation. As an example, adding the following line in your cdk app will also propagate to the logGroup.

const fn = new lambda.Function(this, 'MyFunctionWithFFTrue', {
  runtime: lambda.Runtime.NODEJS_20_X,
  handler: 'handler.main',
  code: lambda.Code.fromAsset('lambda'),
});
cdk.Tags.of(fn).add('env', 'dev'); // the tag is also added to the log group

Log removal policy ​

When using the deprecated logRetention property for creating a LogGroup, you can configure log removal policy:

ts
import * as logs from 'aws-cdk-lib/aws-logs';

const fn = new lambda.Function(this, 'MyFunctionWithFFTrue', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'handler.main',
  code: lambda.Code.fromAsset('lambda'),
  logRetention: logs.RetentionDays.INFINITE,
  logRemovalPolicy: RemovalPolicy.RETAIN,
});
python
import aws_cdk.aws_logs as logs


fn = lambda_.Function(self, "MyFunctionWithFFTrue",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="handler.main",
    code=lambda_.Code.from_asset("lambda"),
    log_retention=logs.RetentionDays.INFINITE,
    log_removal_policy=RemovalPolicy.RETAIN
)
java
import software.amazon.awscdk.services.logs.*;


Function fn = Function.Builder.create(this, "MyFunctionWithFFTrue")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("handler.main")
        .code(Code.fromAsset("lambda"))
        .logRetention(RetentionDays.INFINITE)
        .logRemovalPolicy(RemovalPolicy.RETAIN)
        .build();
csharp
using Amazon.CDK.AWS.Logs;


var fn = new Function(this, "MyFunctionWithFFTrue", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "handler.main",
    Code = Code.FromAsset("lambda"),
    LogRetention = RetentionDays.INFINITE,
    LogRemovalPolicy = RemovalPolicy.RETAIN
});
go
import logs "github.com/aws/aws-cdk-go/awscdk"


fn := lambda.NewFunction(this, jsii.String("MyFunctionWithFFTrue"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("handler.main"),
	Code: lambda.Code_FromAsset(jsii.String("lambda")),
	LogRetention: logs.RetentionDays_INFINITE,
	LogRemovalPolicy: awscdk.RemovalPolicy_RETAIN,
})

Resource-based Policies ​

AWS 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, AWS Organizations, or other AWS accounts to modify and invoke your functions.

Grant function access to AWS services ​

ts
// Grant permissions to a service
declare const fn: lambda.Function;
const principal = new iam.ServicePrincipal('my-service');

fn.grantInvoke(principal);

// Equivalent to:
fn.addPermission('my-service Invocation', {
  principal: principal,
});
python
# Grant permissions to a service
# fn: lambda.Function

principal = iam.ServicePrincipal("my-service")

fn.grant_invoke(principal)

# Equivalent to:
fn.add_permission("my-service Invocation",
    principal=principal
)
java
// Grant permissions to a service
Function fn;

ServicePrincipal principal = new ServicePrincipal("my-service");

fn.grantInvoke(principal);

// Equivalent to:
fn.addPermission("my-service Invocation", Permission.builder()
        .principal(principal)
        .build());
csharp
// Grant permissions to a service
Function fn;

var principal = new ServicePrincipal("my-service");

fn.GrantInvoke(principal);

// Equivalent to:
fn.AddPermission("my-service Invocation", new Permission {
    Principal = principal
});
go
// Grant permissions to a service
var fn Function

principal := iam.NewServicePrincipal(jsii.String("my-service"))

fn.GrantInvoke(principal)

// Equivalent to:
fn.AddPermission(jsii.String("my-service Invocation"), &Permission{
	Principal: principal,
})

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).

Important:

By default fn.grantInvoke() grants permission to the principal to invoke any version of the function, including all past ones. If you only want the principal to be granted permission to invoke the latest version or the unqualified Lambda ARN, use grantInvokeLatestVersion(grantee).

ts
declare const fn: lambda.Function;
const principal = new iam.ServicePrincipal('my-service');
// Grant invoke only to latest version and unqualified lambda arn
fn.grantInvokeLatestVersion(principal);
python
# fn: lambda.Function

principal = iam.ServicePrincipal("my-service")
# Grant invoke only to latest version and unqualified lambda arn
fn.grant_invoke_latest_version(principal)
java
Function fn;

ServicePrincipal principal = new ServicePrincipal("my-service");
// Grant invoke only to latest version and unqualified lambda arn
fn.grantInvokeLatestVersion(principal);
csharp
Function fn;

var principal = new ServicePrincipal("my-service");
// Grant invoke only to latest version and unqualified lambda arn
fn.GrantInvokeLatestVersion(principal);
go
var fn Function

principal := iam.NewServicePrincipal(jsii.String("my-service"))
// Grant invoke only to latest version and unqualified lambda arn
fn.GrantInvokeLatestVersion(principal)

If you want to grant access for invoking a specific version of Lambda function, you can use fn.grantInvokeVersion(grantee, version)

ts
declare const fn: lambda.Function;
const principal = new iam.ServicePrincipal('my-service');
declare const version: lambda.IVersion;
// Grant invoke only to the specific version
fn.grantInvokeVersion(principal, version);
python
# fn: lambda.Function
# version: lambda.IVersion

principal = iam.ServicePrincipal("my-service")
# Grant invoke only to the specific version
fn.grant_invoke_version(principal, version)
java
Function fn;
IVersion version;

ServicePrincipal principal = new ServicePrincipal("my-service");
// Grant invoke only to the specific version
fn.grantInvokeVersion(principal, version);
csharp
Function fn;
IVersion version;

var principal = new ServicePrincipal("my-service");
// Grant invoke only to the specific version
fn.GrantInvokeVersion(principal, version);
go
var fn Function
var version IVersion

principal := iam.NewServicePrincipal(jsii.String("my-service"))
// Grant invoke only to the specific version
fn.GrantInvokeVersion(principal, version)

For more information, see Granting function access to AWS services in the AWS Lambda Developer Guide.

Grant function access to an AWS Organization ​

ts
// Grant permissions to an entire AWS organization
declare const fn: lambda.Function;
const org = new iam.OrganizationPrincipal('o-xxxxxxxxxx');

fn.grantInvoke(org);
python
# Grant permissions to an entire AWS organization
# fn: lambda.Function

org = iam.OrganizationPrincipal("o-xxxxxxxxxx")

fn.grant_invoke(org)
java
// Grant permissions to an entire AWS organization
Function fn;

OrganizationPrincipal org = new OrganizationPrincipal("o-xxxxxxxxxx");

fn.grantInvoke(org);
csharp
// Grant permissions to an entire AWS organization
Function fn;

var org = new OrganizationPrincipal("o-xxxxxxxxxx");

fn.GrantInvoke(org);
go
// Grant permissions to an entire AWS organization
var fn Function

org := iam.NewOrganizationPrincipal(jsii.String("o-xxxxxxxxxx"))

fn.GrantInvoke(org)

In the above example, the principal will be * and all users in the organization o-xxxxxxxxxx will get function invocation permissions.

You can restrict permissions given to the organization by specifying an AWS account or role as the principal:

ts
// Grant permission to an account ONLY IF they are part of the organization
declare const fn: lambda.Function;
const account = new iam.AccountPrincipal('123456789012');

fn.grantInvoke(account.inOrganization('o-xxxxxxxxxx'));
python
# Grant permission to an account ONLY IF they are part of the organization
# fn: lambda.Function

account = iam.AccountPrincipal("123456789012")

fn.grant_invoke(account.in_organization("o-xxxxxxxxxx"))
java
// Grant permission to an account ONLY IF they are part of the organization
Function fn;

AccountPrincipal account = new AccountPrincipal("123456789012");

fn.grantInvoke(account.inOrganization("o-xxxxxxxxxx"));
csharp
// Grant permission to an account ONLY IF they are part of the organization
Function fn;

var account = new AccountPrincipal("123456789012");

fn.GrantInvoke(account.InOrganization("o-xxxxxxxxxx"));
go
// Grant permission to an account ONLY IF they are part of the organization
var fn Function

account := iam.NewAccountPrincipal(jsii.String("123456789012"))

fn.GrantInvoke(account.InOrganization(jsii.String("o-xxxxxxxxxx")))

For more information, see Granting function access to an organization in the AWS Lambda Developer Guide.

Grant function access to other AWS accounts ​

ts
// Grant permission to other AWS account
declare const fn: lambda.Function;
const account = new iam.AccountPrincipal('123456789012');

fn.grantInvoke(account);
python
# Grant permission to other AWS account
# fn: lambda.Function

account = iam.AccountPrincipal("123456789012")

fn.grant_invoke(account)
java
// Grant permission to other AWS account
Function fn;

AccountPrincipal account = new AccountPrincipal("123456789012");

fn.grantInvoke(account);
csharp
// Grant permission to other AWS account
Function fn;

var account = new AccountPrincipal("123456789012");

fn.GrantInvoke(account);
go
// Grant permission to other AWS account
var fn Function

account := iam.NewAccountPrincipal(jsii.String("123456789012"))

fn.GrantInvoke(account)

For more information, see Granting function access to other accounts in the AWS Lambda Developer Guide.

Grant function access to unowned principals ​

Providing an unowned principal (such as account principals, generic ARN principals, service principals, and principals in other accounts) to a call to fn.grantInvoke will 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.

ts
declare const fn: lambda.Function;
const servicePrincipal = new iam.ServicePrincipal('my-service');
const sourceArn = 'arn:aws:s3:::amzn-s3-demo-bucket';
const sourceAccount = '111122223333';
const servicePrincipalWithConditions = servicePrincipal.withConditions({
  ArnLike: {
    'aws:SourceArn': sourceArn,
  },
  StringEquals: {
    'aws:SourceAccount': sourceAccount,
  },
});

fn.grantInvoke(servicePrincipalWithConditions);
python
# fn: lambda.Function

service_principal = iam.ServicePrincipal("my-service")
source_arn = "arn:aws:s3:::amzn-s3-demo-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)
java
Function fn;

ServicePrincipal servicePrincipal = new ServicePrincipal("my-service");
String sourceArn = "arn:aws:s3:::amzn-s3-demo-bucket";
String sourceAccount = "111122223333";
PrincipalBase servicePrincipalWithConditions = servicePrincipal.withConditions(Map.of(
        "ArnLike", Map.of(
                "aws:SourceArn", sourceArn),
        "StringEquals", Map.of(
                "aws:SourceAccount", sourceAccount)));

fn.grantInvoke(servicePrincipalWithConditions);
csharp
Function fn;

var servicePrincipal = new ServicePrincipal("my-service");
var sourceArn = "arn:aws:s3:::amzn-s3-demo-bucket";
var sourceAccount = "111122223333";
var servicePrincipalWithConditions = servicePrincipal.WithConditions(new Dictionary<string, object> {
    { "ArnLike", new Dictionary<string, string> {
        { "aws:SourceArn", sourceArn }
    } },
    { "StringEquals", new Dictionary<string, string> {
        { "aws:SourceAccount", sourceAccount }
    } }
});

fn.GrantInvoke(servicePrincipalWithConditions);
go
var fn Function

servicePrincipal := iam.NewServicePrincipal(jsii.String("my-service"))
sourceArn := "arn:aws:s3:::amzn-s3-demo-bucket"
sourceAccount := "111122223333"
servicePrincipalWithConditions := servicePrincipal.WithConditions(map[string]interface{}{
	"ArnLike": map[string]*string{
		"aws:SourceArn": sourceArn,
	},
	"StringEquals": map[string]*string{
		"aws:SourceAccount": sourceAccount,
	},
})

fn.GrantInvoke(servicePrincipalWithConditions)

Grant function access to a CompositePrincipal ​

To grant invoke permissions to a CompositePrincipal use the grantInvokeCompositePrincipal method:

ts
declare const fn: lambda.Function;
const compositePrincipal = new iam.CompositePrincipal(
  new iam.OrganizationPrincipal('o-zzzzzzzzzz'),
  new iam.ServicePrincipal('apigateway.amazonaws.com'),
);

fn.grantInvokeCompositePrincipal(compositePrincipal);
python
# fn: lambda.Function

composite_principal = iam.CompositePrincipal(
    iam.OrganizationPrincipal("o-zzzzzzzzzz"),
    iam.ServicePrincipal("apigateway.amazonaws.com"))

fn.grant_invoke_composite_principal(composite_principal)
java
Function fn;

CompositePrincipal compositePrincipal = new CompositePrincipal(
new OrganizationPrincipal("o-zzzzzzzzzz"),
new ServicePrincipal("apigateway.amazonaws.com"));

fn.grantInvokeCompositePrincipal(compositePrincipal);
csharp
Function fn;

var compositePrincipal = new CompositePrincipal(
new OrganizationPrincipal("o-zzzzzzzzzz"),
new ServicePrincipal("apigateway.amazonaws.com"));

fn.GrantInvokeCompositePrincipal(compositePrincipal);
go
var fn Function

compositePrincipal := iam.NewCompositePrincipal(
iam.NewOrganizationPrincipal(jsii.String("o-zzzzzzzzzz")),
iam.NewServicePrincipal(jsii.String("apigateway.amazonaws.com")))

fn.GrantInvokeCompositePrincipal(compositePrincipal)

Versions ​

You can use versions to 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 the Version construct.

ts
declare const fn: lambda.Function;
const version = new lambda.Version(this, 'MyVersion', {
  lambda: fn,
});
python
# fn: lambda.Function

version = lambda_.Version(self, "MyVersion",
    lambda_=fn
)
java
Function fn;

Version version = Version.Builder.create(this, "MyVersion")
        .lambda(fn)
        .build();
csharp
Function fn;

var version = new Version(this, "MyVersion", new VersionProps {
    Lambda = fn
});
go
var fn Function

version := lambda.NewVersion(this, jsii.String("MyVersion"), &VersionProps{
	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 the lambda.Version always points to the latest version of your lambda.Function is 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 -

ts
const codeVersion = "stringOrMethodToGetCodeVersion";
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  environment: {
    'CodeVersionString': codeVersion,
  },
});
python
code_version = "stringOrMethodToGetCodeVersion"
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    environment={
        "CodeVersionString": code_version
    }
)
java
String codeVersion = "stringOrMethodToGetCodeVersion";
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .environment(Map.of(
                "CodeVersionString", codeVersion))
        .build();
csharp
var codeVersion = "stringOrMethodToGetCodeVersion";
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    Environment = new Dictionary<string, string> {
        { "CodeVersionString", codeVersion }
    }
});
go
codeVersion := "stringOrMethodToGetCodeVersion"
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	Environment: map[string]*string{
		"CodeVersionString": codeVersion,
	},
})

The fn.latestVersion property returns a lambda.IVersion which represents the $LATEST pseudo-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 use lambda.currentVersion.

The fn.currentVersion property can be used to obtain a lambda.Version resource 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 the currentVersionOptions property.

NOTE: The currentVersion property is only supported when your AWS Lambda function uses either lambda.Code.fromAsset or lambda.Code.fromInline. Other types of code providers (such as lambda.Code.fromBucket) require that you define a lambda.Version resource directly since the CDK is unable to determine if their contents had changed.

currentVersion: Updated hashing logic ​

To produce a new lambda version each time the lambda function is modified, the currentVersion property under the hood, computes a new logical id based on the properties of the function. This informs CloudFormation that a new AWS::Lambda::Version resource 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's Tags property, or when the DependsOn clause 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 but existing users need to opt-in via a feature flag. Users who have run cdk init since this fix will be opted in, by default.

Otherwise, you will need to enable the feature 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 the FunctionVersionUpgrade aspect 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.

ts
const stack = new Stack();
Aspects.of(stack).add(new lambda.FunctionVersionUpgrade(LAMBDA_RECOGNIZE_VERSION_PROPS));
python
stack = Stack()
Aspects.of(stack).add(lambda_.FunctionVersionUpgrade(LAMBDA_RECOGNIZE_VERSION_PROPS))
java
Stack stack = new Stack();
Aspects.of(stack).add(new FunctionVersionUpgrade(LAMBDA_RECOGNIZE_VERSION_PROPS));
csharp
var stack = new Stack();
Aspects.Of(stack).Add(new FunctionVersionUpgrade(LAMBDA_RECOGNIZE_VERSION_PROPS));
go
stack := awscdk.Newstack()
awscdk.Aspects_Of(stack).Add(lambda.NewFunctionVersionUpgrade(awscdklibcxapi.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 when property overrides are used, when a new property introduced in AWS::Lambda::Function is used that CDK is still unaware of.

To overcome this error, use the API Function.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 the UpdateFunctionConfiguration API or not.

currentVersion: Updated hashing logic for layer versions ​

An 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 ran cdk init with an earlier version, you will need to opt-in via a feature flag. If you run cdk init with v2.27 or later, this fix will be opted in, by default.

Existing users will need to enable the feature 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 the FunctionVersionUpgrade aspect 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.

ts
const stack = new Stack();
Aspects.of(stack).add(new lambda.FunctionVersionUpgrade(LAMBDA_RECOGNIZE_LAYER_VERSION));
python
stack = Stack()
Aspects.of(stack).add(lambda_.FunctionVersionUpgrade(LAMBDA_RECOGNIZE_LAYER_VERSION))
java
Stack stack = new Stack();
Aspects.of(stack).add(new FunctionVersionUpgrade(LAMBDA_RECOGNIZE_LAYER_VERSION));
csharp
var stack = new Stack();
Aspects.Of(stack).Add(new FunctionVersionUpgrade(LAMBDA_RECOGNIZE_LAYER_VERSION));
go
stack := awscdk.Newstack()
awscdk.Aspects_Of(stack).Add(lambda.NewFunctionVersionUpgrade(awscdklibcxapi.LAMBDA_RECOGNIZE_LAYER_VERSION))

Aliases ​

You can define one or more aliases for 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.

The version.addAlias() method can be used to define an AWS Lambda alias that points to a specific version.

The following example defines an alias named live which 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 the currentVersionOptions property.

ts
const fn = new lambda.Function(this, 'MyFunction', {
  currentVersionOptions: {
    removalPolicy: RemovalPolicy.RETAIN, // retain old versions
    retryAttempts: 1,                   // async retry attempts
  },
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});

fn.addAlias('live');
python
fn = lambda_.Function(self, "MyFunction",
    current_version_options=lambda.VersionOptions(
        removal_policy=RemovalPolicy.RETAIN,  # retain old versions
        retry_attempts=1
    ),
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)

fn.add_alias("live")
java
Function fn = Function.Builder.create(this, "MyFunction")
        .currentVersionOptions(VersionOptions.builder()
                .removalPolicy(RemovalPolicy.RETAIN) // retain old versions
                .retryAttempts(1)
                .build())
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .build();

fn.addAlias("live");
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    CurrentVersionOptions = new VersionOptions {
        RemovalPolicy = RemovalPolicy.RETAIN,  // retain old versions
        RetryAttempts = 1
    },
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});

fn.AddAlias("live");
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	CurrentVersionOptions: &VersionOptions{
		RemovalPolicy: awscdk.RemovalPolicy_RETAIN,
		 // retain old versions
		RetryAttempts: jsii.Number(1),
	},
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
})

fn.AddAlias(jsii.String("live"))

Function URL ​

A 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 the Invoking Function URLs section of the AWS Lambda Developer Guide for more information on the input and output payloads of Functions invoked in this way.

IAM-authenticated Function URLs ​

To create a Function URL which can be called by an IAM identity, call addFunctionUrl(), followed by grantInvokeFunctionUrl():

ts
// Can be a Function or an Alias
declare const fn: lambda.Function;
declare const myRole: iam.Role;

const fnUrl = fn.addFunctionUrl();
fnUrl.grantInvokeUrl(myRole);

new CfnOutput(this, 'TheUrl', {
  // The .url attributes will return the unique Function URL
  value: fnUrl.url,
});
python
# Can be a Function or an Alias
# fn: lambda.Function
# my_role: iam.Role


fn_url = fn.add_function_url()
fn_url.grant_invoke_url(my_role)

CfnOutput(self, "TheUrl",
    # The .url attributes will return the unique Function URL
    value=fn_url.url
)
java
// Can be a Function or an Alias
Function fn;
Role myRole;


FunctionUrl fnUrl = fn.addFunctionUrl();
fnUrl.grantInvokeUrl(myRole);

CfnOutput.Builder.create(this, "TheUrl")
        // The .url attributes will return the unique Function URL
        .value(fnUrl.getUrl())
        .build();
csharp
// Can be a Function or an Alias
Function fn;
Role myRole;


var fnUrl = fn.AddFunctionUrl();
fnUrl.GrantInvokeUrl(myRole);

new CfnOutput(this, "TheUrl", new CfnOutputProps {
    // The .url attributes will return the unique Function URL
    Value = fnUrl.Url
});
go
// Can be a Function or an Alias
var fn Function
var myRole Role


fnUrl := fn.AddFunctionUrl()
fnUrl.GrantInvokeUrl(myRole)

awscdk.NewCfnOutput(this, jsii.String("TheUrl"), &CfnOutputProps{
	// The .url attributes will return the unique Function URL
	Value: fnUrl.Url,
})

Calls to this URL need to be signed with SigV4.

Anonymous Function URLs ​

To create a Function URL which can be called anonymously, pass authType: FunctionUrlAuthType.NONE to addFunctionUrl():

ts
// Can be a Function or an Alias
declare const fn: lambda.Function;

const fnUrl = fn.addFunctionUrl({
  authType: lambda.FunctionUrlAuthType.NONE,
});

new CfnOutput(this, 'TheUrl', {
  value: fnUrl.url,
});
python
# Can be a Function or an Alias
# fn: lambda.Function


fn_url = fn.add_function_url(
    auth_type=lambda_.FunctionUrlAuthType.NONE
)

CfnOutput(self, "TheUrl",
    value=fn_url.url
)
java
// Can be a Function or an Alias
Function fn;


FunctionUrl fnUrl = fn.addFunctionUrl(FunctionUrlOptions.builder()
        .authType(FunctionUrlAuthType.NONE)
        .build());

CfnOutput.Builder.create(this, "TheUrl")
        .value(fnUrl.getUrl())
        .build();
csharp
// Can be a Function or an Alias
Function fn;


var fnUrl = fn.AddFunctionUrl(new FunctionUrlOptions {
    AuthType = FunctionUrlAuthType.NONE
});

new CfnOutput(this, "TheUrl", new CfnOutputProps {
    Value = fnUrl.Url
});
go
// Can be a Function or an Alias
var fn Function


fnUrl := fn.AddFunctionUrl(&FunctionUrlOptions{
	AuthType: lambda.FunctionUrlAuthType_NONE,
})

awscdk.NewCfnOutput(this, jsii.String("TheUrl"), &CfnOutputProps{
	Value: fnUrl.Url,
})

Important Function URL Permission Update - Oct 2025 ​

Starting Oct 2025, Function URL invocation will require two permissions

  • lambda:InvokeFunctionUrl
  • lambda:InvokeFunction (New)

CDK has updated grantInvokeUrl and addFunctionUrl to add both permission above.

If your existing CDK stack uses grantInvokeUrl or addFunctionUrl, your next deployment will automatically add the lambda:InvokeFunction permission without requiring any code changes. This ensures your Function URLs continue working seamlessly. No additional actions are needed.

CORS configuration for Function URLs ​

If 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):

ts
declare const fn: lambda.Function;

fn.addFunctionUrl({
  authType: lambda.FunctionUrlAuthType.NONE,
  cors: {
    // Allow this to be called from websites on https://example.com.
    // Can also be ['*'] to allow all domain.
    allowedOrigins: ['https://example.com'],

    // More options are possible here, see the documentation for FunctionUrlCorsOptions
  },
});
python
# fn: lambda.Function


fn.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"]
    )
)
java
Function fn;


fn.addFunctionUrl(FunctionUrlOptions.builder()
        .authType(FunctionUrlAuthType.NONE)
        .cors(FunctionUrlCorsOptions.builder()
                // Allow this to be called from websites on https://example.com.
                // Can also be ['*'] to allow all domain.
                .allowedOrigins(List.of("https://example.com"))
                .build())
        .build());
csharp
Function fn;


fn.AddFunctionUrl(new FunctionUrlOptions {
    AuthType = FunctionUrlAuthType.NONE,
    Cors = new FunctionUrlCorsOptions {
        // Allow this to be called from websites on https://example.com.
        // Can also be ['*'] to allow all domain.
        AllowedOrigins = new [] { "https://example.com" }
    }
});
go
var fn Function


fn.AddFunctionUrl(&FunctionUrlOptions{
	AuthType: lambda.FunctionUrlAuthType_NONE,
	Cors: &FunctionUrlCorsOptions{
		// Allow this to be called from websites on https://example.com.
		// Can also be ['*'] to allow all domain.
		AllowedOrigins: []*string{
			jsii.String("https://example.com"),
		},
	},
})

Invoke Mode for Function URLs ​

Invoke mode determines how AWS Lambda invokes your function. You can configure the invoke mode when creating a Function URL using the invokeMode property

ts
declare const fn: lambda.Function;

fn.addFunctionUrl({
  authType: lambda.FunctionUrlAuthType.NONE,
  invokeMode: lambda.InvokeMode.RESPONSE_STREAM,
});
python
# fn: lambda.Function


fn.add_function_url(
    auth_type=lambda_.FunctionUrlAuthType.NONE,
    invoke_mode=lambda_.InvokeMode.RESPONSE_STREAM
)
java
Function fn;


fn.addFunctionUrl(FunctionUrlOptions.builder()
        .authType(FunctionUrlAuthType.NONE)
        .invokeMode(InvokeMode.RESPONSE_STREAM)
        .build());
csharp
Function fn;


fn.AddFunctionUrl(new FunctionUrlOptions {
    AuthType = FunctionUrlAuthType.NONE,
    InvokeMode = InvokeMode.RESPONSE_STREAM
});
go
var fn Function


fn.AddFunctionUrl(&FunctionUrlOptions{
	AuthType: lambda.FunctionUrlAuthType_NONE,
	InvokeMode: lambda.InvokeMode_RESPONSE_STREAM,
})

If the invokeMode property is not specified, the default BUFFERED mode will be used.

Layers ​

The lambda.LayerVersion class can be used to define Lambda layers and manage granting permissions to other AWS accounts or organizations.

ts
const layer = new lambda.LayerVersion(stack, 'MyLayer', {
  code: lambda.Code.fromAsset(path.join(__dirname, 'layer-code')),
  compatibleRuntimes: [lambda.Runtime.NODEJS_LATEST],
  license: 'Apache-2.0',
  description: 'A layer to test the L2 construct',
});

// To grant usage by other AWS accounts
layer.addPermission('remote-account-grant', { accountId: awsAccountId });

// To grant usage to all accounts in some AWS Ogranization
// layer.grantUsage({ accountId: '*', organizationId });

new lambda.Function(stack, 'MyLayeredLambda', {
  code: new lambda.InlineCode('foo'),
  handler: 'index.handler',
  runtime: lambda.Runtime.NODEJS_LATEST,
  layers: [layer],
});
python
layer = lambda_.LayerVersion(stack, "MyLayer",
    code=lambda_.Code.from_asset(path.join(__dirname, "layer-code")),
    compatible_runtimes=[lambda_.Runtime.NODEJS_LATEST],
    license="Apache-2.0",
    description="A layer to test the L2 construct"
)

# To grant usage by other AWS accounts
layer.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_LATEST,
    layers=[layer]
)
java
LayerVersion layer = LayerVersion.Builder.create(stack, "MyLayer")
        .code(Code.fromAsset(join(__dirname, "layer-code")))
        .compatibleRuntimes(List.of(Runtime.NODEJS_LATEST))
        .license("Apache-2.0")
        .description("A layer to test the L2 construct")
        .build();

// To grant usage by other AWS accounts
layer.addPermission("remote-account-grant", LayerVersionPermission.builder().accountId(awsAccountId).build());

// To grant usage to all accounts in some AWS Ogranization
// layer.grantUsage({ accountId: '*', organizationId });

// To grant usage to all accounts in some AWS Ogranization
// layer.grantUsage({ accountId: '*', organizationId });
Function.Builder.create(stack, "MyLayeredLambda")
        .code(new InlineCode("foo"))
        .handler("index.handler")
        .runtime(Runtime.NODEJS_LATEST)
        .layers(List.of(layer))
        .build();
csharp
var layer = new LayerVersion(stack, "MyLayer", new LayerVersionProps {
    Code = Code.FromAsset(Join(__dirname, "layer-code")),
    CompatibleRuntimes = new [] { Runtime.NODEJS_LATEST },
    License = "Apache-2.0",
    Description = "A layer to test the L2 construct"
});

// To grant usage by other AWS accounts
layer.AddPermission("remote-account-grant", new LayerVersionPermission { AccountId = awsAccountId });

// To grant usage to all accounts in some AWS Ogranization
// layer.grantUsage({ accountId: '*', organizationId });

// To grant usage to all accounts in some AWS Ogranization
// layer.grantUsage({ accountId: '*', organizationId });
new Function(stack, "MyLayeredLambda", new FunctionProps {
    Code = new InlineCode("foo"),
    Handler = "index.handler",
    Runtime = Runtime.NODEJS_LATEST,
    Layers = new [] { layer }
});
go
layer := lambda.NewLayerVersion(stack, jsii.String("MyLayer"), &LayerVersionProps{
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("layer-code"))),
	CompatibleRuntimes: []Runtime{
		lambda.Runtime_NODEJS_LATEST(),
	},
	License: jsii.String("Apache-2.0"),
	Description: jsii.String("A layer to test the L2 construct"),
})

// To grant usage by other AWS accounts
layer.addPermission(jsii.String("remote-account-grant"), &LayerVersionPermission{
	AccountId: awsAccountId,
})

// To grant usage to all accounts in some AWS Ogranization
// layer.grantUsage({ accountId: '*', organizationId });

// To grant usage to all accounts in some AWS Ogranization
// layer.grantUsage({ accountId: '*', organizationId });
lambda.NewFunction(stack, jsii.String("MyLayeredLambda"), &FunctionProps{
	Code: lambda.NewInlineCode(jsii.String("foo")),
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Layers: []ILayerVersion{
		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:

ts
new lambda.LayerVersion(this, 'MyLayer', {
  removalPolicy: RemovalPolicy.RETAIN,
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});
python
lambda_.LayerVersion(self, "MyLayer",
    removal_policy=RemovalPolicy.RETAIN,
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)
java
LayerVersion.Builder.create(this, "MyLayer")
        .removalPolicy(RemovalPolicy.RETAIN)
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .build();
csharp
new LayerVersion(this, "MyLayer", new LayerVersionProps {
    RemovalPolicy = RemovalPolicy.RETAIN,
    Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
go
lambda.NewLayerVersion(this, jsii.String("MyLayer"), &LayerVersionProps{
	RemovalPolicy: awscdk.RemovalPolicy_RETAIN,
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
})

Architecture ​

Lambda 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:

ts
new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  architecture: lambda.Architecture.ARM_64,
});
python
lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    architecture=lambda_.Architecture.ARM_64
)
java
Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .architecture(Architecture.ARM_64)
        .build();
csharp
new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    Architecture = Architecture.ARM_64
});
go
lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	Architecture: lambda.Architecture_ARM_64(),
})

Similarly, lambda layer versions can also be tagged with architectures it is compatible with.

ts
new lambda.LayerVersion(this, 'MyLayer', {
  removalPolicy: RemovalPolicy.RETAIN,
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  compatibleArchitectures: [lambda.Architecture.X86_64, lambda.Architecture.ARM_64],
});
python
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]
)
java
LayerVersion.Builder.create(this, "MyLayer")
        .removalPolicy(RemovalPolicy.RETAIN)
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .compatibleArchitectures(List.of(Architecture.X86_64, Architecture.ARM_64))
        .build();
csharp
new LayerVersion(this, "MyLayer", new LayerVersionProps {
    RemovalPolicy = RemovalPolicy.RETAIN,
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    CompatibleArchitectures = new [] { Architecture.X86_64, Architecture.ARM_64 }
});
go
lambda.NewLayerVersion(this, jsii.String("MyLayer"), &LayerVersionProps{
	RemovalPolicy: awscdk.RemovalPolicy_RETAIN,
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	CompatibleArchitectures: []Architecture{
		lambda.Architecture_X86_64(),
		lambda.Architecture_ARM_64(),
	},
})

Capacity Providers ​

Lambda capacity providers allow you to run Lambda functions on dedicated compute resources instead of the default serverless execution environment. Capacity providers can have multiple functions and function versions associated with them, but a function can be attached to at most one capacity provider.

Creating a Capacity Provider ​

To create a capacity provider, you need to specify the VPC configuration and optionally configure permissions, scaling, and instance requirements:

ts
import * as ec2 from 'aws-cdk-lib/aws-ec2';

// Create a VPC for the capacity provider
const vpc = new ec2.Vpc(this, 'MyVpc');
const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', { vpc });

// Create a basic capacity provider
const capacityProvider = new lambda.CapacityProvider(this, 'MyCapacityProvider', {
  capacityProviderName: 'my-capacity-provider',
  subnets: vpc.privateSubnets,
  securityGroups: [securityGroup],
});
python
import aws_cdk.aws_ec2 as ec2


# Create a VPC for the capacity provider
vpc = ec2.Vpc(self, "MyVpc")
security_group = ec2.SecurityGroup(self, "SecurityGroup", vpc=vpc)

# Create a basic capacity provider
capacity_provider = lambda_.CapacityProvider(self, "MyCapacityProvider",
    capacity_provider_name="my-capacity-provider",
    subnets=vpc.private_subnets,
    security_groups=[security_group]
)
java
import software.amazon.awscdk.services.ec2.*;


// Create a VPC for the capacity provider
Vpc vpc = new Vpc(this, "MyVpc");
SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup").vpc(vpc).build();

// Create a basic capacity provider
CapacityProvider capacityProvider = CapacityProvider.Builder.create(this, "MyCapacityProvider")
        .capacityProviderName("my-capacity-provider")
        .subnets(vpc.getPrivateSubnets())
        .securityGroups(List.of(securityGroup))
        .build();
csharp
using Amazon.CDK.AWS.EC2;


// Create a VPC for the capacity provider
var vpc = new Vpc(this, "MyVpc");
var securityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps { Vpc = vpc });

// Create a basic capacity provider
var capacityProvider = new CapacityProvider(this, "MyCapacityProvider", new CapacityProviderProps {
    CapacityProviderName = "my-capacity-provider",
    Subnets = vpc.PrivateSubnets,
    SecurityGroups = new [] { securityGroup }
});
go
import "github.com/aws/aws-cdk-go/awscdk"


// Create a VPC for the capacity provider
vpc := ec2.NewVpc(this, jsii.String("MyVpc"))
securityGroup := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup"), &SecurityGroupProps{
	Vpc: Vpc,
})

// Create a basic capacity provider
capacityProvider := lambda.NewCapacityProvider(this, jsii.String("MyCapacityProvider"), &CapacityProviderProps{
	CapacityProviderName: jsii.String("my-capacity-provider"),
	Subnets: vpc.PrivateSubnets,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
})

By default, permissions are granted to the capacity provider to manage instances using the AWS managed policy AWSLambdaManagedEC2ResourceOperator. You can also supply a custom role via the operatorRole parameter.

Configuring Scaling Policies ​

You can configure target tracking scaling policies to automatically scale your capacity provider based on CPU utilization:

ts
import * as ec2 from 'aws-cdk-lib/aws-ec2';

const vpc = new ec2.Vpc(this, 'MyVpc');
const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', { vpc });

const capacityProvider = new lambda.CapacityProvider(this, 'MyCapacityProvider', {
  subnets: vpc.privateSubnets,
  securityGroups: [securityGroup],
  scalingOptions: lambda.ScalingOptions.manual([
    lambda.TargetTrackingScalingPolicy.cpuUtilization(70),
  ]),
});
python
import aws_cdk.aws_ec2 as ec2


vpc = ec2.Vpc(self, "MyVpc")
security_group = ec2.SecurityGroup(self, "SecurityGroup", vpc=vpc)

capacity_provider = lambda_.CapacityProvider(self, "MyCapacityProvider",
    subnets=vpc.private_subnets,
    security_groups=[security_group],
    scaling_options=lambda_.ScalingOptions.manual([
        lambda_.TargetTrackingScalingPolicy.cpu_utilization(70)
    ])
)
java
import software.amazon.awscdk.services.ec2.*;


Vpc vpc = new Vpc(this, "MyVpc");
SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup").vpc(vpc).build();

CapacityProvider capacityProvider = CapacityProvider.Builder.create(this, "MyCapacityProvider")
        .subnets(vpc.getPrivateSubnets())
        .securityGroups(List.of(securityGroup))
        .scalingOptions(ScalingOptions.manual(List.of(TargetTrackingScalingPolicy.cpuUtilization(70))))
        .build();
csharp
using Amazon.CDK.AWS.EC2;


var vpc = new Vpc(this, "MyVpc");
var securityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps { Vpc = vpc });

var capacityProvider = new CapacityProvider(this, "MyCapacityProvider", new CapacityProviderProps {
    Subnets = vpc.PrivateSubnets,
    SecurityGroups = new [] { securityGroup },
    ScalingOptions = ScalingOptions.Manual(new [] { TargetTrackingScalingPolicy.CpuUtilization(70) })
});
go
import "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("MyVpc"))
securityGroup := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup"), &SecurityGroupProps{
	Vpc: Vpc,
})

capacityProvider := lambda.NewCapacityProvider(this, jsii.String("MyCapacityProvider"), &CapacityProviderProps{
	Subnets: vpc.PrivateSubnets,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
	ScalingOptions: lambda.ScalingOptions_Manual([]TargetTrackingScalingPolicy{
		lambda.TargetTrackingScalingPolicy_CpuUtilization(jsii.Number(70)),
	}),
})

Instance Type Configuration ​

You can control which EC2 instance types the capacity provider can use:

ts
import * as ec2 from 'aws-cdk-lib/aws-ec2';

const vpc = new ec2.Vpc(this, 'MyVpc');
const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', { vpc });

// Allow only specific instance families
const allowCapacityProvider = new lambda.CapacityProvider(this, 'MyCapacityProviderAllowed', {
  subnets: vpc.privateSubnets,
  securityGroups: [securityGroup],
  instanceTypeFilter: lambda.InstanceTypeFilter.allow([
    ec2.InstanceType.of(ec2.InstanceClass.M5, ec2.InstanceSize.LARGE),
    ec2.InstanceType.of(ec2.InstanceClass.M5, ec2.InstanceSize.XLARGE),
  ]),
});

// Or exclude specific instance types
const excludeCapacityProvider = new lambda.CapacityProvider(this, 'MyCapacityProviderExcluded', {
  subnets: vpc.privateSubnets,
  securityGroups: [securityGroup],
  instanceTypeFilter: lambda.InstanceTypeFilter.exclude([
    ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),
  ]),
});
python
import aws_cdk.aws_ec2 as ec2


vpc = ec2.Vpc(self, "MyVpc")
security_group = ec2.SecurityGroup(self, "SecurityGroup", vpc=vpc)

# Allow only specific instance families
allow_capacity_provider = lambda_.CapacityProvider(self, "MyCapacityProviderAllowed",
    subnets=vpc.private_subnets,
    security_groups=[security_group],
    instance_type_filter=lambda_.InstanceTypeFilter.allow([
        ec2.InstanceType.of(ec2.InstanceClass.M5, ec2.InstanceSize.LARGE),
        ec2.InstanceType.of(ec2.InstanceClass.M5, ec2.InstanceSize.XLARGE)
    ])
)

# Or exclude specific instance types
exclude_capacity_provider = lambda_.CapacityProvider(self, "MyCapacityProviderExcluded",
    subnets=vpc.private_subnets,
    security_groups=[security_group],
    instance_type_filter=lambda_.InstanceTypeFilter.exclude([
        ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO)
    ])
)
java
import software.amazon.awscdk.services.ec2.*;


Vpc vpc = new Vpc(this, "MyVpc");
SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup").vpc(vpc).build();

// Allow only specific instance families
CapacityProvider allowCapacityProvider = CapacityProvider.Builder.create(this, "MyCapacityProviderAllowed")
        .subnets(vpc.getPrivateSubnets())
        .securityGroups(List.of(securityGroup))
        .instanceTypeFilter(InstanceTypeFilter.allow(List.of(InstanceType.of(InstanceClass.M5, InstanceSize.LARGE), InstanceType.of(InstanceClass.M5, InstanceSize.XLARGE))))
        .build();

// Or exclude specific instance types
CapacityProvider excludeCapacityProvider = CapacityProvider.Builder.create(this, "MyCapacityProviderExcluded")
        .subnets(vpc.getPrivateSubnets())
        .securityGroups(List.of(securityGroup))
        .instanceTypeFilter(InstanceTypeFilter.exclude(List.of(InstanceType.of(InstanceClass.T2, InstanceSize.MICRO))))
        .build();
csharp
using Amazon.CDK.AWS.EC2;


var vpc = new Vpc(this, "MyVpc");
var securityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps { Vpc = vpc });

// Allow only specific instance families
var allowCapacityProvider = new CapacityProvider(this, "MyCapacityProviderAllowed", new CapacityProviderProps {
    Subnets = vpc.PrivateSubnets,
    SecurityGroups = new [] { securityGroup },
    InstanceTypeFilter = InstanceTypeFilter.Allow(new [] { InstanceType.Of(InstanceClass.M5, InstanceSize.LARGE), InstanceType.Of(InstanceClass.M5, InstanceSize.XLARGE) })
});

// Or exclude specific instance types
var excludeCapacityProvider = new CapacityProvider(this, "MyCapacityProviderExcluded", new CapacityProviderProps {
    Subnets = vpc.PrivateSubnets,
    SecurityGroups = new [] { securityGroup },
    InstanceTypeFilter = InstanceTypeFilter.Exclude(new [] { InstanceType.Of(InstanceClass.T2, InstanceSize.MICRO) })
});
go
import "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("MyVpc"))
securityGroup := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup"), &SecurityGroupProps{
	Vpc: Vpc,
})

// Allow only specific instance families
allowCapacityProvider := lambda.NewCapacityProvider(this, jsii.String("MyCapacityProviderAllowed"), &CapacityProviderProps{
	Subnets: vpc.PrivateSubnets,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
	InstanceTypeFilter: lambda.InstanceTypeFilter_Allow([]InstanceType{
		ec2.InstanceType_Of(ec2.InstanceClass_M5, ec2.InstanceSize_LARGE),
		ec2.InstanceType_*Of(ec2.InstanceClass_M5, ec2.InstanceSize_XLARGE),
	}),
})

// Or exclude specific instance types
excludeCapacityProvider := lambda.NewCapacityProvider(this, jsii.String("MyCapacityProviderExcluded"), &CapacityProviderProps{
	Subnets: vpc.*PrivateSubnets,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
	InstanceTypeFilter: lambda.InstanceTypeFilter_Exclude([]InstanceType{
		ec2.InstanceType_*Of(ec2.InstanceClass_T2, ec2.InstanceSize_MICRO),
	}),
})

System Logging ​

You can configure system logging to monitor capacity provider scaling activity:

ts
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as logs from 'aws-cdk-lib/aws-logs';

const vpc = new ec2.Vpc(this, 'MyVpc');
const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', { vpc });

const capacityProvider = new lambda.CapacityProvider(this, 'MyCapacityProvider', {
  subnets: vpc.privateSubnets,
  securityGroups: [securityGroup],
  logGroup: new logs.LogGroup(this, 'CpLogs', {
    logGroupName: '/aws/lambda/capacity-provider/my-cp',
  }),
  systemLogLevel: lambda.SystemLogLevel.DEBUG,
});
python
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_logs as logs


vpc = ec2.Vpc(self, "MyVpc")
security_group = ec2.SecurityGroup(self, "SecurityGroup", vpc=vpc)

capacity_provider = lambda_.CapacityProvider(self, "MyCapacityProvider",
    subnets=vpc.private_subnets,
    security_groups=[security_group],
    log_group=logs.LogGroup(self, "CpLogs",
        log_group_name="/aws/lambda/capacity-provider/my-cp"
    ),
    system_log_level=lambda_.SystemLogLevel.DEBUG
)
java
import software.amazon.awscdk.services.ec2.*;
import software.amazon.awscdk.services.logs.*;


Vpc vpc = new Vpc(this, "MyVpc");
SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup").vpc(vpc).build();

CapacityProvider capacityProvider = CapacityProvider.Builder.create(this, "MyCapacityProvider")
        .subnets(vpc.getPrivateSubnets())
        .securityGroups(List.of(securityGroup))
        .logGroup(LogGroup.Builder.create(this, "CpLogs")
                .logGroupName("/aws/lambda/capacity-provider/my-cp")
                .build())
        .systemLogLevel(SystemLogLevel.DEBUG)
        .build();
csharp
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.Logs;


var vpc = new Vpc(this, "MyVpc");
var securityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps { Vpc = vpc });

var capacityProvider = new CapacityProvider(this, "MyCapacityProvider", new CapacityProviderProps {
    Subnets = vpc.PrivateSubnets,
    SecurityGroups = new [] { securityGroup },
    LogGroup = new LogGroup(this, "CpLogs", new LogGroupProps {
        LogGroupName = "/aws/lambda/capacity-provider/my-cp"
    }),
    SystemLogLevel = SystemLogLevel.DEBUG
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import logs "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("MyVpc"))
securityGroup := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup"), &SecurityGroupProps{
	Vpc: Vpc,
})

capacityProvider := lambda.NewCapacityProvider(this, jsii.String("MyCapacityProvider"), &CapacityProviderProps{
	Subnets: vpc.PrivateSubnets,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
	LogGroup: logs.NewLogGroup(this, jsii.String("CpLogs"), &LogGroupProps{
		LogGroupName: jsii.String("/aws/lambda/capacity-provider/my-cp"),
	}),
	SystemLogLevel: lambda.SystemLogLevel_DEBUG,
})

Tag Propagation ​

You can propagate explicit tags to managed resources (EC2 instances, ENIs, EBS volumes) launched by the capacity provider:

ts
import * as ec2 from 'aws-cdk-lib/aws-ec2';

const vpc = new ec2.Vpc(this, 'MyVpc');
const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', { vpc });

const capacityProvider = new lambda.CapacityProvider(this, 'MyCapacityProvider', {
  subnets: vpc.privateSubnets,
  securityGroups: [securityGroup],
  propagateTags: lambda.PropagateTags.explicit({
    CostCenter: 'Engineering',
    Project: 'MyProject',
  }),
});
python
import aws_cdk.aws_ec2 as ec2


vpc = ec2.Vpc(self, "MyVpc")
security_group = ec2.SecurityGroup(self, "SecurityGroup", vpc=vpc)

capacity_provider = lambda_.CapacityProvider(self, "MyCapacityProvider",
    subnets=vpc.private_subnets,
    security_groups=[security_group],
    propagate_tags=lambda_.PropagateTags.explicit({
        "CostCenter": "Engineering",
        "Project": "MyProject"
    })
)
java
import software.amazon.awscdk.services.ec2.*;


Vpc vpc = new Vpc(this, "MyVpc");
SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup").vpc(vpc).build();

CapacityProvider capacityProvider = CapacityProvider.Builder.create(this, "MyCapacityProvider")
        .subnets(vpc.getPrivateSubnets())
        .securityGroups(List.of(securityGroup))
        .propagateTags(PropagateTags.explicit(Map.of(
                "CostCenter", "Engineering",
                "Project", "MyProject")))
        .build();
csharp
using Amazon.CDK.AWS.EC2;


var vpc = new Vpc(this, "MyVpc");
var securityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps { Vpc = vpc });

var capacityProvider = new CapacityProvider(this, "MyCapacityProvider", new CapacityProviderProps {
    Subnets = vpc.PrivateSubnets,
    SecurityGroups = new [] { securityGroup },
    PropagateTags = PropagateTags.Explicit(new Dictionary<string, string> {
        { "CostCenter", "Engineering" },
        { "Project", "MyProject" }
    })
});
go
import "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("MyVpc"))
securityGroup := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup"), &SecurityGroupProps{
	Vpc: Vpc,
})

capacityProvider := lambda.NewCapacityProvider(this, jsii.String("MyCapacityProvider"), &CapacityProviderProps{
	Subnets: vpc.PrivateSubnets,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
	PropagateTags: lambda.PropagateTags_Explicit(map[string]*string{
		"CostCenter": jsii.String("Engineering"),
		"Project": jsii.String("MyProject"),
	}),
})

Use PropagateTags.none() to explicitly disable propagation, or omit the prop entirely (defaults to no propagation). Up to 40 tags can be specified with PropagateTags.explicit().

Using a Capacity Provider with Lambda Functions ​

Once you have a capacity provider, you can configure Lambda functions to use it:

ts
declare const capacityProvider: lambda.CapacityProvider;

const fn = new lambda.Function(this, 'MyFunction', {
  // Runtime must be equal to or newer than NODEJS_LATEST
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});

// Associate the function with the capacity provider
capacityProvider.addFunction(fn, {
  perExecutionEnvironmentMaxConcurrency: 10,
  executionEnvironmentMemoryGiBPerVCpu: 4,
});
python
# capacity_provider: lambda.CapacityProvider


fn = lambda_.Function(self, "MyFunction",
    # Runtime must be equal to or newer than NODEJS_LATEST
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)

# Associate the function with the capacity provider
capacity_provider.add_function(fn,
    per_execution_environment_max_concurrency=10,
    execution_environment_memory_gi_b_per_v_cpu=4
)
java
CapacityProvider capacityProvider;


Function fn = Function.Builder.create(this, "MyFunction")
        // Runtime must be equal to or newer than NODEJS_LATEST
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .build();

// Associate the function with the capacity provider
capacityProvider.addFunction(fn, CapacityProviderFunctionOptions.builder()
        .perExecutionEnvironmentMaxConcurrency(10)
        .executionEnvironmentMemoryGiBPerVCpu(4)
        .build());
csharp
CapacityProvider capacityProvider;


var fn = new Function(this, "MyFunction", new FunctionProps {
    // Runtime must be equal to or newer than NODEJS_LATEST
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});

// Associate the function with the capacity provider
capacityProvider.AddFunction(fn, new CapacityProviderFunctionOptions {
    PerExecutionEnvironmentMaxConcurrency = 10,
    ExecutionEnvironmentMemoryGiBPerVCpu = 4
});
go
var capacityProvider CapacityProvider


fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	// Runtime must be equal to or newer than NODEJS_LATEST
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
})

// Associate the function with the capacity provider
capacityProvider.AddFunction(fn, &CapacityProviderFunctionOptions{
	PerExecutionEnvironmentMaxConcurrency: jsii.Number(10),
	ExecutionEnvironmentMemoryGiBPerVCpu: jsii.Number(4),
})

Note that once you use a capacity provider in a function, it cannot be removed, only changed.

CapacityProviderFunctionOptions (addFunction method) ​

NameTypeRequiredDescription
perExecutionEnvironmentMaxConcurrencynumberNoMaximum concurrent invokes per execution environment.
executionEnvironmentMemoryGiBPerVCpunumberNoMemory per VCPU in GiB.
publishToLatestPublishedbooleanNoWhether to automatically publish to $LATEST.PUBLISHED version.
latestPublishedScalingConfigLatestPublishedScalingConfigNoScaling configuration for $LATEST.PUBLISHED version.

LatestPublishedScalingConfig ​

NameTypeRequiredDescription
minExecutionEnvironmentsnumberNoMinimum execution environments for $LATEST.PUBLISHED version.
maxExecutionEnvironmentsnumberNoMaximum execution environments for $LATEST.PUBLISHED version.

Capacity Provider Versions ​

When publishing Lambda versions that use capacity providers, you can configure scaling settings specific to each version.

To publish a permanent version with specific scaling properties, you can use the currentVersion property of the function:

ts
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  currentVersionOptions: {
    minExecutionEnvironments: 3,
  }
});

const version = fn.latestVersion
python
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    current_version_options=lambda.VersionOptions(
        min_execution_environments=3
    )
)

version = fn.latest_version
java
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .currentVersionOptions(VersionOptions.builder()
                .minExecutionEnvironments(3)
                .build())
        .build();

IVersion version = fn.getLatestVersion();
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    CurrentVersionOptions = new VersionOptions {
        MinExecutionEnvironments = 3
    }
});

var version = fn.LatestVersion;
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	CurrentVersionOptions: &VersionOptions{
		MinExecutionEnvironments: jsii.Number(3),
	},
})

version := fn.latestVersion

You can also specify scaling properties for the special $LATEST.PUBLISHED version when attaching the function to the capacity provider.

$LATEST.PUBLISHED is a version that is automatically published when you deploy changes to your function.

ts
declare const capacityProvider: lambda.CapacityProvider;
declare const fn: lambda.Function;

capacityProvider.addFunction(fn, {
  latestPublishedScalingConfig: {
    minExecutionEnvironments: 5,
    maxExecutionEnvironments: 25,
  },
});
python
# capacity_provider: lambda.CapacityProvider
# fn: lambda.Function


capacity_provider.add_function(fn,
    latest_published_scaling_config=lambda.LatestPublishedScalingConfig(
        min_execution_environments=5,
        max_execution_environments=25
    )
)
java
CapacityProvider capacityProvider;
Function fn;


capacityProvider.addFunction(fn, CapacityProviderFunctionOptions.builder()
        .latestPublishedScalingConfig(LatestPublishedScalingConfig.builder()
                .minExecutionEnvironments(5)
                .maxExecutionEnvironments(25)
                .build())
        .build());
csharp
CapacityProvider capacityProvider;
Function fn;


capacityProvider.AddFunction(fn, new CapacityProviderFunctionOptions {
    LatestPublishedScalingConfig = new LatestPublishedScalingConfig {
        MinExecutionEnvironments = 5,
        MaxExecutionEnvironments = 25
    }
});
go
var capacityProvider CapacityProvider
var fn Function


capacityProvider.AddFunction(fn, &CapacityProviderFunctionOptions{
	LatestPublishedScalingConfig: &LatestPublishedScalingConfig{
		MinExecutionEnvironments: jsii.Number(5),
		MaxExecutionEnvironments: jsii.Number(25),
	},
})
NameTypeRequiredDescription
minExecutionEnvironmentsnumberNoMinimum execution environments to maintain for this version.
maxExecutionEnvironmentsnumberNoMaximum execution environments allowed for this version.

Security and Encryption ​

Capacity providers support encryption using AWS KMS keys:

ts
import * as kms from 'aws-cdk-lib/aws-kms';
import * as ec2 from 'aws-cdk-lib/aws-ec2';

const vpc = new ec2.Vpc(this, 'MyVpc');
const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', { vpc });
const kmsKey = new kms.Key(this, 'MyKey');

const capacityProvider = new lambda.CapacityProvider(this, 'MyCapacityProvider', {
  subnets: vpc.privateSubnets,
  securityGroups: [securityGroup],
  kmsKey: kmsKey,
});
python
import aws_cdk.aws_kms as kms
import aws_cdk.aws_ec2 as ec2


vpc = ec2.Vpc(self, "MyVpc")
security_group = ec2.SecurityGroup(self, "SecurityGroup", vpc=vpc)
kms_key = kms.Key(self, "MyKey")

capacity_provider = lambda_.CapacityProvider(self, "MyCapacityProvider",
    subnets=vpc.private_subnets,
    security_groups=[security_group],
    kms_key=kms_key
)
java
import software.amazon.awscdk.services.kms.*;
import software.amazon.awscdk.services.ec2.*;


Vpc vpc = new Vpc(this, "MyVpc");
SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup").vpc(vpc).build();
Key kmsKey = new Key(this, "MyKey");

CapacityProvider capacityProvider = CapacityProvider.Builder.create(this, "MyCapacityProvider")
        .subnets(vpc.getPrivateSubnets())
        .securityGroups(List.of(securityGroup))
        .kmsKey(kmsKey)
        .build();
csharp
using Amazon.CDK.AWS.KMS;
using Amazon.CDK.AWS.EC2;


var vpc = new Vpc(this, "MyVpc");
var securityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps { Vpc = vpc });
var kmsKey = new Key(this, "MyKey");

var capacityProvider = new CapacityProvider(this, "MyCapacityProvider", new CapacityProviderProps {
    Subnets = vpc.PrivateSubnets,
    SecurityGroups = new [] { securityGroup },
    KmsKey = kmsKey
});
go
import kms "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("MyVpc"))
securityGroup := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup"), &SecurityGroupProps{
	Vpc: Vpc,
})
kmsKey := kms.NewKey(this, jsii.String("MyKey"))

capacityProvider := lambda.NewCapacityProvider(this, jsii.String("MyCapacityProvider"), &CapacityProviderProps{
	Subnets: vpc.PrivateSubnets,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
	KmsKey: kmsKey,
})

Capacity Provider Configuration Reference ​

CapacityProviderProps ​

NameTypeRequiredDescription
capacityProviderNamestringNoName of the capacity provider. Must be unique within the AWS account and region.
securityGroupsISecurityGroup[]YesSecurity groups to associate with EC2 instances. Up to 5 allowed.
subnetsISubnet[]YesSubnets where the capacity provider can launch EC2 instances. 1-16 subnets supported.
operatorRoleIRoleNoIAM role for Lambda to manage the capacity provider. Uses AWS Managed Policy AWSLambdaManagedEC2ResourceOperator by default.
architecturesArchitecture[]NoInstruction set architecture for compute instances.
instanceTypeFilterInstanceTypeFilterNoFilter for allowed or excluded instance types.
maxVCpuCountnumberNoMaximum number of EC2 instances for scaling.
scalingOptionsScalingOptionsNoScaling configuration including policies.
kmsKeyIKeyNoKMS key for encrypting capacity provider data.
logGroupILogGroupNoCloudWatch log group for capacity provider system logs.
systemLogLevelSystemLogLevelNoLevel of detail for capacity provider system logs (DEBUG, INFO, WARN).

Lambda Insights ​

Lambda functions can be configured to use CloudWatch Lambda Insights which provides low-level runtime metrics for a Lambda functions.

ts
new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  insightsVersion: lambda.LambdaInsightsVersion.VERSION_1_0_98_0,
});
python
lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    insights_version=lambda_.LambdaInsightsVersion.VERSION_1_0_98_0
)
java
Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .insightsVersion(LambdaInsightsVersion.VERSION_1_0_98_0)
        .build();
csharp
new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    InsightsVersion = LambdaInsightsVersion.VERSION_1_0_98_0
});
go
lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	InsightsVersion: 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 -

ts
const layerArn = 'arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14';
new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  insightsVersion: lambda.LambdaInsightsVersion.fromInsightVersionArn(layerArn),
});
python
layer_arn = "arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14"
lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    insights_version=lambda_.LambdaInsightsVersion.from_insight_version_arn(layer_arn)
)
java
String layerArn = "arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14";
Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .insightsVersion(LambdaInsightsVersion.fromInsightVersionArn(layerArn))
        .build();
csharp
var layerArn = "arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14";
new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    InsightsVersion = LambdaInsightsVersion.FromInsightVersionArn(layerArn)
});
go
layerArn := "arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14"
lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	InsightsVersion: lambda.LambdaInsightsVersion_FromInsightVersionArn(layerArn),
})

If you are deploying an ARM_64 Lambda Function, you must specify a Lambda Insights Version >= 1_0_119_0.

ts
new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  architecture: lambda.Architecture.ARM_64,
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  insightsVersion: lambda.LambdaInsightsVersion.VERSION_1_0_119_0,
});
python
lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    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
)
java
Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .architecture(Architecture.ARM_64)
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .insightsVersion(LambdaInsightsVersion.VERSION_1_0_119_0)
        .build();
csharp
new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Architecture = Architecture.ARM_64,
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    InsightsVersion = LambdaInsightsVersion.VERSION_1_0_119_0
});
go
lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Architecture: lambda.Architecture_ARM_64(),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	InsightsVersion: lambda.LambdaInsightsVersion_VERSION_1_0_119_0(),
})

Parameters and Secrets Extension ​

Lambda functions can be configured to use the Parameters and Secrets Extension. The Parameters and Secrets Extension can be used to retrieve and cache secrets from Secrets Manager or parameters from Parameter Store in Lambda functions without using an SDK.

ts
import * as sm from 'aws-cdk-lib/aws-secretsmanager';
import * as ssm from 'aws-cdk-lib/aws-ssm';

const secret = new sm.Secret(this, 'Secret');
const parameter = new ssm.StringParameter(this, 'Parameter', {
  parameterName: 'mySsmParameterName',
  stringValue: 'mySsmParameterValue',
});

const paramsAndSecrets = lambda.ParamsAndSecretsLayerVersion.fromVersion(lambda.ParamsAndSecretsVersions.V1_0_103, {
  cacheSize: 500,
  logLevel: lambda.ParamsAndSecretsLogLevel.DEBUG,
});

const lambdaFunction = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  architecture: lambda.Architecture.ARM_64,
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  paramsAndSecrets,
});

secret.grantRead(lambdaFunction);
parameter.grantRead(lambdaFunction);
python
import aws_cdk.aws_secretsmanager as sm
import aws_cdk.aws_ssm as ssm


secret = sm.Secret(self, "Secret")
parameter = ssm.StringParameter(self, "Parameter",
    parameter_name="mySsmParameterName",
    string_value="mySsmParameterValue"
)

params_and_secrets = lambda_.ParamsAndSecretsLayerVersion.from_version(lambda_.ParamsAndSecretsVersions.V1_0_103,
    cache_size=500,
    log_level=lambda_.ParamsAndSecretsLogLevel.DEBUG
)

lambda_function = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    architecture=lambda_.Architecture.ARM_64,
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    params_and_secrets=params_and_secrets
)

secret.grant_read(lambda_function)
parameter.grant_read(lambda_function)
java
import software.amazon.awscdk.services.secretsmanager.*;
import software.amazon.awscdk.services.ssm.*;


Secret secret = new Secret(this, "Secret");
StringParameter parameter = StringParameter.Builder.create(this, "Parameter")
        .parameterName("mySsmParameterName")
        .stringValue("mySsmParameterValue")
        .build();

ParamsAndSecretsLayerVersion paramsAndSecrets = ParamsAndSecretsLayerVersion.fromVersion(ParamsAndSecretsVersions.V1_0_103, ParamsAndSecretsOptions.builder()
        .cacheSize(500)
        .logLevel(ParamsAndSecretsLogLevel.DEBUG)
        .build());

Function lambdaFunction = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .architecture(Architecture.ARM_64)
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .paramsAndSecrets(paramsAndSecrets)
        .build();

secret.grantRead(lambdaFunction);
parameter.grantRead(lambdaFunction);
csharp
using Amazon.CDK.AWS.SecretsManager;
using Amazon.CDK.AWS.SSM;


var secret = new Secret(this, "Secret");
var parameter = new StringParameter(this, "Parameter", new StringParameterProps {
    ParameterName = "mySsmParameterName",
    StringValue = "mySsmParameterValue"
});

var paramsAndSecrets = ParamsAndSecretsLayerVersion.FromVersion(ParamsAndSecretsVersions.V1_0_103, new ParamsAndSecretsOptions {
    CacheSize = 500,
    LogLevel = ParamsAndSecretsLogLevel.DEBUG
});

var lambdaFunction = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Architecture = Architecture.ARM_64,
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    ParamsAndSecrets = paramsAndSecrets
});

secret.GrantRead(lambdaFunction);
parameter.GrantRead(lambdaFunction);
go
import sm "github.com/aws/aws-cdk-go/awscdk"
import ssm "github.com/aws/aws-cdk-go/awscdk"


secret := sm.NewSecret(this, jsii.String("Secret"))
parameter := ssm.NewStringParameter(this, jsii.String("Parameter"), &StringParameterProps{
	ParameterName: jsii.String("mySsmParameterName"),
	StringValue: jsii.String("mySsmParameterValue"),
})

paramsAndSecrets := lambda.ParamsAndSecretsLayerVersion_FromVersion(lambda.ParamsAndSecretsVersions_V1_0_103, &ParamsAndSecretsOptions{
	CacheSize: jsii.Number(500),
	LogLevel: lambda.ParamsAndSecretsLogLevel_DEBUG,
})

lambdaFunction := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Architecture: lambda.Architecture_ARM_64(),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	ParamsAndSecrets: ParamsAndSecrets,
})

secret.grantRead(lambdaFunction)
parameter.grantRead(lambdaFunction)

If the version of Parameters and Secrets Extension is not yet available in the CDK, you can also provide the ARN directly as so:

ts
import * as sm from 'aws-cdk-lib/aws-secretsmanager';
import * as ssm from 'aws-cdk-lib/aws-ssm';

const secret = new sm.Secret(this, 'Secret');
const parameter = new ssm.StringParameter(this, 'Parameter', {
  parameterName: 'mySsmParameterName',
  stringValue: 'mySsmParameterValue',
});

const layerArn = 'arn:aws:lambda:us-east-1:177933569100:layer:AWS-Parameters-and-Secrets-Lambda-Extension:4';
const paramsAndSecrets = lambda.ParamsAndSecretsLayerVersion.fromVersionArn(layerArn, {
  cacheSize: 500,
});

const lambdaFunction = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  architecture: lambda.Architecture.ARM_64,
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  paramsAndSecrets,
});

secret.grantRead(lambdaFunction);
parameter.grantRead(lambdaFunction);
python
import aws_cdk.aws_secretsmanager as sm
import aws_cdk.aws_ssm as ssm


secret = sm.Secret(self, "Secret")
parameter = ssm.StringParameter(self, "Parameter",
    parameter_name="mySsmParameterName",
    string_value="mySsmParameterValue"
)

layer_arn = "arn:aws:lambda:us-east-1:177933569100:layer:AWS-Parameters-and-Secrets-Lambda-Extension:4"
params_and_secrets = lambda_.ParamsAndSecretsLayerVersion.from_version_arn(layer_arn,
    cache_size=500
)

lambda_function = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    architecture=lambda_.Architecture.ARM_64,
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    params_and_secrets=params_and_secrets
)

secret.grant_read(lambda_function)
parameter.grant_read(lambda_function)
java
import software.amazon.awscdk.services.secretsmanager.*;
import software.amazon.awscdk.services.ssm.*;


Secret secret = new Secret(this, "Secret");
StringParameter parameter = StringParameter.Builder.create(this, "Parameter")
        .parameterName("mySsmParameterName")
        .stringValue("mySsmParameterValue")
        .build();

String layerArn = "arn:aws:lambda:us-east-1:177933569100:layer:AWS-Parameters-and-Secrets-Lambda-Extension:4";
ParamsAndSecretsLayerVersion paramsAndSecrets = ParamsAndSecretsLayerVersion.fromVersionArn(layerArn, ParamsAndSecretsOptions.builder()
        .cacheSize(500)
        .build());

Function lambdaFunction = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .architecture(Architecture.ARM_64)
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .paramsAndSecrets(paramsAndSecrets)
        .build();

secret.grantRead(lambdaFunction);
parameter.grantRead(lambdaFunction);
csharp
using Amazon.CDK.AWS.SecretsManager;
using Amazon.CDK.AWS.SSM;


var secret = new Secret(this, "Secret");
var parameter = new StringParameter(this, "Parameter", new StringParameterProps {
    ParameterName = "mySsmParameterName",
    StringValue = "mySsmParameterValue"
});

var layerArn = "arn:aws:lambda:us-east-1:177933569100:layer:AWS-Parameters-and-Secrets-Lambda-Extension:4";
var paramsAndSecrets = ParamsAndSecretsLayerVersion.FromVersionArn(layerArn, new ParamsAndSecretsOptions {
    CacheSize = 500
});

var lambdaFunction = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Architecture = Architecture.ARM_64,
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    ParamsAndSecrets = paramsAndSecrets
});

secret.GrantRead(lambdaFunction);
parameter.GrantRead(lambdaFunction);
go
import sm "github.com/aws/aws-cdk-go/awscdk"
import ssm "github.com/aws/aws-cdk-go/awscdk"


secret := sm.NewSecret(this, jsii.String("Secret"))
parameter := ssm.NewStringParameter(this, jsii.String("Parameter"), &StringParameterProps{
	ParameterName: jsii.String("mySsmParameterName"),
	StringValue: jsii.String("mySsmParameterValue"),
})

layerArn := "arn:aws:lambda:us-east-1:177933569100:layer:AWS-Parameters-and-Secrets-Lambda-Extension:4"
paramsAndSecrets := lambda.ParamsAndSecretsLayerVersion_FromVersionArn(layerArn, &ParamsAndSecretsOptions{
	CacheSize: jsii.Number(500),
})

lambdaFunction := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Architecture: lambda.Architecture_ARM_64(),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	ParamsAndSecrets: ParamsAndSecrets,
})

secret.grantRead(lambdaFunction)
parameter.grantRead(lambdaFunction)

Event Rule Target ​

You can use an AWS Lambda function as a target for an Amazon CloudWatch event rule:

ts
import * as events from 'aws-cdk-lib/aws-events';
import * as targets from 'aws-cdk-lib/aws-events-targets';

declare const fn: lambda.Function;
const rule = new events.Rule(this, 'Schedule Rule', {
 schedule: events.Schedule.cron({ minute: '0', hour: '4' }),
});
rule.addTarget(new targets.LambdaFunction(fn));
python
import aws_cdk.aws_events as events
import aws_cdk.aws_events_targets as targets

# fn: lambda.Function

rule = events.Rule(self, "Schedule Rule",
    schedule=events.Schedule.cron(minute="0", hour="4")
)
rule.add_target(targets.LambdaFunction(fn))
java
import software.amazon.awscdk.services.events.*;
import software.amazon.awscdk.services.events.targets.*;

Function fn;

Rule rule = Rule.Builder.create(this, "Schedule Rule")
        .schedule(Schedule.cron(CronOptions.builder().minute("0").hour("4").build()))
        .build();
rule.addTarget(new LambdaFunction(fn));
csharp
using Amazon.CDK.AWS.Events;
using Amazon.CDK.AWS.Events.Targets;

Function fn;

var rule = new Rule(this, "Schedule Rule", new RuleProps {
    Schedule = Schedule.Cron(new CronOptions { Minute = "0", Hour = "4" })
});
rule.AddTarget(new LambdaFunction(fn));
go
import "github.com/aws/aws-cdk-go/awscdk"
import targets "github.com/aws/aws-cdk-go/awscdk"

var fn Function

rule := events.NewRule(this, jsii.String("Schedule Rule"), &RuleProps{
	Schedule: events.Schedule_Cron(&CronOptions{
		Minute: jsii.String("0"),
		Hour: jsii.String("4"),
	}),
})
rule.AddTarget(targets.NewLambdaFunction(fn))

Event Sources ​

AWS Lambda supports a variety of event sources.

In most cases, it is possible to trigger a function as a result of an event by using one of the add<Event>Notification methods on the source construct. For example, the s3.Bucket construct has an onEvent method 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 use function.addEventSource(source). This method accepts an IEventSource object. The module @aws-cdk/aws-lambda-event-sources includes 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:

ts
import * as eventsources from 'aws-cdk-lib/aws-lambda-event-sources';
import * as sqs from 'aws-cdk-lib/aws-sqs';

declare const fn: lambda.Function;
const queue = new sqs.Queue(this, 'Queue');
fn.addEventSource(new eventsources.SqsEventSource(queue));
python
import aws_cdk.aws_lambda_event_sources as eventsources
import aws_cdk.aws_sqs as sqs

# fn: lambda.Function

queue = sqs.Queue(self, "Queue")
fn.add_event_source(eventsources.SqsEventSource(queue))
java
import software.amazon.awscdk.services.lambda.eventsources.*;
import software.amazon.awscdk.services.sqs.*;

Function fn;

Queue queue = new Queue(this, "Queue");
fn.addEventSource(new SqsEventSource(queue));
csharp
using Amazon.CDK.AWS.Lambda.EventSources;
using Amazon.CDK.AWS.SQS;

Function fn;

var queue = new Queue(this, "Queue");
fn.AddEventSource(new SqsEventSource(queue));
go
import eventsources "github.com/aws/aws-cdk-go/awscdk"
import sqs "github.com/aws/aws-cdk-go/awscdk"

var fn Function

queue := sqs.NewQueue(this, jsii.String("Queue"))
fn.AddEventSource(eventsources.NewSqsEventSource(queue))

The following code adds an S3 bucket notification as an event source:

ts
import * as eventsources from 'aws-cdk-lib/aws-lambda-event-sources';
import * as s3 from 'aws-cdk-lib/aws-s3';

declare const fn: lambda.Function;
const bucket = new s3.Bucket(this, 'Bucket');
fn.addEventSource(new eventsources.S3EventSource(bucket, {
  events: [ s3.EventType.OBJECT_CREATED, s3.EventType.OBJECT_REMOVED ],
  filters: [ { prefix: 'subdir/' } ] // optional
}));
python
import aws_cdk.aws_lambda_event_sources as eventsources
import aws_cdk.aws_s3 as s3

# fn: lambda.Function

bucket = 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/")]
))
java
import software.amazon.awscdk.services.lambda.eventsources.*;
import software.amazon.awscdk.services.s3.*;

Function fn;

Bucket bucket = new Bucket(this, "Bucket");
fn.addEventSource(S3EventSource.Builder.create(bucket)
        .events(List.of(EventType.OBJECT_CREATED, EventType.OBJECT_REMOVED))
        .filters(List.of(NotificationKeyFilter.builder().prefix("subdir/").build()))
        .build());
csharp
using Amazon.CDK.AWS.Lambda.EventSources;
using Amazon.CDK.AWS.S3;

Function fn;

var bucket = new Bucket(this, "Bucket");
fn.AddEventSource(new S3EventSource(bucket, new S3EventSourceProps {
    Events = new [] { EventType.OBJECT_CREATED, EventType.OBJECT_REMOVED },
    Filters = new [] { new NotificationKeyFilter { Prefix = "subdir/" } }
}));
go
import eventsources "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var fn Function

bucket := s3.NewBucket(this, jsii.String("Bucket"))
fn.AddEventSource(eventsources.NewS3EventSource(bucket, &S3EventSourceProps{
	Events: []EventType{
		s3.EventType_OBJECT_CREATED,
		s3.EventType_OBJECT_REMOVED,
	},
	Filters: []NotificationKeyFilter{
		&NotificationKeyFilter{
			Prefix: jsii.String("subdir/"),
		},
	},
}))

The following code adds an DynamoDB notification as an event source filtering insert events:

ts
import * as eventsources from 'aws-cdk-lib/aws-lambda-event-sources';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';

declare const fn: lambda.Function;
const table = new dynamodb.Table(this, 'Table', {
  partitionKey: {
    name: 'id',
    type: dynamodb.AttributeType.STRING,
  },
  stream: dynamodb.StreamViewType.NEW_IMAGE,
});
fn.addEventSource(new eventsources.DynamoEventSource(table, {
  startingPosition: lambda.StartingPosition.LATEST,
  filters: [lambda.FilterCriteria.filter({ eventName: lambda.FilterRule.isEqual('INSERT') })],
}));
python
import aws_cdk.aws_lambda_event_sources as eventsources
import aws_cdk.aws_dynamodb as dynamodb

# fn: lambda.Function

table = dynamodb.Table(self, "Table",
    partition_key=dynamodb.Attribute(
        name="id",
        type=dynamodb.AttributeType.STRING
    ),
    stream=dynamodb.StreamViewType.NEW_IMAGE
)
fn.add_event_source(eventsources.DynamoEventSource(table,
    starting_position=lambda_.StartingPosition.LATEST,
    filters=[lambda_.FilterCriteria.filter({"event_name": lambda_.FilterRule.is_equal("INSERT")})]
))
java
import software.amazon.awscdk.services.lambda.eventsources.*;
import software.amazon.awscdk.services.dynamodb.*;

Function fn;

Table table = Table.Builder.create(this, "Table")
        .partitionKey(Attribute.builder()
                .name("id")
                .type(AttributeType.STRING)
                .build())
        .stream(StreamViewType.NEW_IMAGE)
        .build();
fn.addEventSource(DynamoEventSource.Builder.create(table)
        .startingPosition(StartingPosition.LATEST)
        .filters(List.of(FilterCriteria.filter(Map.of("eventName", FilterRule.isEqual("INSERT")))))
        .build());
csharp
using Amazon.CDK.AWS.Lambda.EventSources;
using Amazon.CDK.AWS.DynamoDB;

Function fn;

var table = new Table(this, "Table", new TableProps {
    PartitionKey = new Attribute {
        Name = "id",
        Type = AttributeType.STRING
    },
    Stream = StreamViewType.NEW_IMAGE
});
fn.AddEventSource(new DynamoEventSource(table, new DynamoEventSourceProps {
    StartingPosition = StartingPosition.LATEST,
    Filters = new [] { FilterCriteria.Filter(new Dictionary<string, object> { { "eventName", FilterRule.IsEqual("INSERT") } }) }
}));
go
import eventsources "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var fn Function

table := dynamodb.NewTable(this, jsii.String("Table"), &TableProps{
	PartitionKey: &Attribute{
		Name: jsii.String("id"),
		Type: dynamodb.AttributeType_STRING,
	},
	Stream: dynamodb.StreamViewType_NEW_IMAGE,
})
fn.AddEventSource(eventsources.NewDynamoEventSource(table, &DynamoEventSourceProps{
	StartingPosition: lambda.StartingPosition_LATEST,
	Filters: []map[string]interface{}{
		lambda.FilterCriteria_Filter(map[string]interface{}{
			"eventName": lambda.FilterRule_isEqual(jsii.String("INSERT")),
		}),
	},
}))

By default, Lambda will encrypt Filter Criteria using AWS managed keys. But if you want to use a self managed KMS key to encrypt the filters, You can specify the self managed key using the filterEncryption property.

ts
import * as eventsources from 'aws-cdk-lib/aws-lambda-event-sources';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
import { Key } from 'aws-cdk-lib/aws-kms';

declare const fn: lambda.Function;
const table = new dynamodb.Table(this, 'Table', {
  partitionKey: {
    name: 'id',
    type: dynamodb.AttributeType.STRING,
  },
  stream: dynamodb.StreamViewType.NEW_IMAGE,
});
// Your self managed KMS key
const myKey = Key.fromKeyArn(
  this,
  'SourceBucketEncryptionKey',
  'arn:aws:kms:us-east-1:123456789012:key/<key-id>',
);

fn.addEventSource(new eventsources.DynamoEventSource(table, {
  startingPosition: lambda.StartingPosition.LATEST,
  filters: [lambda.FilterCriteria.filter({ eventName: lambda.FilterRule.isEqual('INSERT') })],
  filterEncryption: myKey,
}));
python
import aws_cdk.aws_lambda_event_sources as eventsources
import aws_cdk.aws_dynamodb as dynamodb
from aws_cdk.aws_kms import Key

# fn: lambda.Function

table = dynamodb.Table(self, "Table",
    partition_key=dynamodb.Attribute(
        name="id",
        type=dynamodb.AttributeType.STRING
    ),
    stream=dynamodb.StreamViewType.NEW_IMAGE
)
# Your self managed KMS key
my_key = Key.from_key_arn(self, "SourceBucketEncryptionKey", "arn:aws:kms:us-east-1:123456789012:key/<key-id>")

fn.add_event_source(eventsources.DynamoEventSource(table,
    starting_position=lambda_.StartingPosition.LATEST,
    filters=[lambda_.FilterCriteria.filter({"event_name": lambda_.FilterRule.is_equal("INSERT")})],
    filter_encryption=my_key
))
java
import software.amazon.awscdk.services.lambda.eventsources.*;
import software.amazon.awscdk.services.dynamodb.*;
import software.amazon.awscdk.services.kms.Key;

Function fn;

Table table = Table.Builder.create(this, "Table")
        .partitionKey(Attribute.builder()
                .name("id")
                .type(AttributeType.STRING)
                .build())
        .stream(StreamViewType.NEW_IMAGE)
        .build();
// Your self managed KMS key
IKey myKey = Key.fromKeyArn(this, "SourceBucketEncryptionKey", "arn:aws:kms:us-east-1:123456789012:key/<key-id>");

fn.addEventSource(DynamoEventSource.Builder.create(table)
        .startingPosition(StartingPosition.LATEST)
        .filters(List.of(FilterCriteria.filter(Map.of("eventName", FilterRule.isEqual("INSERT")))))
        .filterEncryption(myKey)
        .build());
csharp
using Amazon.CDK.AWS.Lambda.EventSources;
using Amazon.CDK.AWS.DynamoDB;
using Amazon.CDK.AWS.KMS;

Function fn;

var table = new Table(this, "Table", new TableProps {
    PartitionKey = new Attribute {
        Name = "id",
        Type = AttributeType.STRING
    },
    Stream = StreamViewType.NEW_IMAGE
});
// Your self managed KMS key
var myKey = Key.FromKeyArn(this, "SourceBucketEncryptionKey", "arn:aws:kms:us-east-1:123456789012:key/<key-id>");

fn.AddEventSource(new DynamoEventSource(table, new DynamoEventSourceProps {
    StartingPosition = StartingPosition.LATEST,
    Filters = new [] { FilterCriteria.Filter(new Dictionary<string, object> { { "eventName", FilterRule.IsEqual("INSERT") } }) },
    FilterEncryption = myKey
}));
go
import eventsources "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var fn Function

table := dynamodb.NewTable(this, jsii.String("Table"), &TableProps{
	PartitionKey: &Attribute{
		Name: jsii.String("id"),
		Type: dynamodb.AttributeType_STRING,
	},
	Stream: dynamodb.StreamViewType_NEW_IMAGE,
})
// Your self managed KMS key
myKey := awscdk.Key_FromKeyArn(this, jsii.String("SourceBucketEncryptionKey"), jsii.String("arn:aws:kms:us-east-1:123456789012:key/<key-id>"))

fn.AddEventSource(eventsources.NewDynamoEventSource(table, &DynamoEventSourceProps{
	StartingPosition: lambda.StartingPosition_LATEST,
	Filters: []map[string]interface{}{
		lambda.FilterCriteria_Filter(map[string]interface{}{
			"eventName": lambda.FilterRule_isEqual(jsii.String("INSERT")),
		}),
	},
	FilterEncryption: myKey,
}))

Lambda requires allow kms:Decrypt on Lambda principal lambda.amazonaws.com to use the key for Filter Criteria Encryption. If you create the KMS key in the stack, CDK will automatically add this permission to the Key when you creates eventSourceMapping. However, if you import the key using function like Key.fromKeyArn then you need to add the following permission to the KMS key before using it to encrypt Filter Criteria

json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "lambda.amazonaws.com"
            },
            "Action": "kms:Decrypt",
            "Resource": "*"
        }
    ]
}

Observability ​

Customers can now opt-in to get enhanced metrics for their event source mapping that capture each stage of processing using the MetricsConfig property.

The following code shows how to opt in for the enhanced metrics.

ts
import * as eventsources from 'aws-cdk-lib/aws-lambda-event-sources';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';

declare const fn: lambda.Function;
const table = new dynamodb.Table(this, 'Table', {
  partitionKey: {
    name: 'id',
    type: dynamodb.AttributeType.STRING,
  },
  stream: dynamodb.StreamViewType.NEW_IMAGE,
});

fn.addEventSource(new eventsources.DynamoEventSource(table, {
  startingPosition: lambda.StartingPosition.LATEST,
  metricsConfig: {
    metrics: [lambda.MetricType.EVENT_COUNT],
  }
}));
python
import aws_cdk.aws_lambda_event_sources as eventsources
import aws_cdk.aws_dynamodb as dynamodb

# fn: lambda.Function

table = dynamodb.Table(self, "Table",
    partition_key=dynamodb.Attribute(
        name="id",
        type=dynamodb.AttributeType.STRING
    ),
    stream=dynamodb.StreamViewType.NEW_IMAGE
)

fn.add_event_source(eventsources.DynamoEventSource(table,
    starting_position=lambda_.StartingPosition.LATEST,
    metrics_config=lambda.MetricsConfig(
        metrics=[lambda_.MetricType.EVENT_COUNT]
    )
))
java
import software.amazon.awscdk.services.lambda.eventsources.*;
import software.amazon.awscdk.services.dynamodb.*;

Function fn;

Table table = Table.Builder.create(this, "Table")
        .partitionKey(Attribute.builder()
                .name("id")
                .type(AttributeType.STRING)
                .build())
        .stream(StreamViewType.NEW_IMAGE)
        .build();

fn.addEventSource(DynamoEventSource.Builder.create(table)
        .startingPosition(StartingPosition.LATEST)
        .metricsConfig(MetricsConfig.builder()
                .metrics(List.of(MetricType.EVENT_COUNT))
                .build())
        .build());
csharp
using Amazon.CDK.AWS.Lambda.EventSources;
using Amazon.CDK.AWS.DynamoDB;

Function fn;

var table = new Table(this, "Table", new TableProps {
    PartitionKey = new Attribute {
        Name = "id",
        Type = AttributeType.STRING
    },
    Stream = StreamViewType.NEW_IMAGE
});

fn.AddEventSource(new DynamoEventSource(table, new DynamoEventSourceProps {
    StartingPosition = StartingPosition.LATEST,
    MetricsConfig = new MetricsConfig {
        Metrics = new [] { MetricType.EVENT_COUNT }
    }
}));
go
import eventsources "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

var fn Function

table := dynamodb.NewTable(this, jsii.String("Table"), &TableProps{
	PartitionKey: &Attribute{
		Name: jsii.String("id"),
		Type: dynamodb.AttributeType_STRING,
	},
	Stream: dynamodb.StreamViewType_NEW_IMAGE,
})

fn.AddEventSource(eventsources.NewDynamoEventSource(table, &DynamoEventSourceProps{
	StartingPosition: lambda.StartingPosition_LATEST,
	MetricsConfig: &MetricsConfig{
		Metrics: []MetricType{
			lambda.MetricType_EVENT_COUNT,
		},
	},
}))

See the documentation for the @aws-cdk/aws-lambda-event-sources module for more details.

Imported Lambdas ​

When referencing an imported lambda in the CDK, use fromFunctionArn() for most use cases:

ts
const fn = lambda.Function.fromFunctionArn(
  this,
  'Function',
  'arn:aws:lambda:us-east-1:123456789012:function:MyFn',
);
python
fn = lambda_.Function.from_function_arn(self, "Function", "arn:aws:lambda:us-east-1:123456789012:function:MyFn")
java
IFunction fn = Function.fromFunctionArn(this, "Function", "arn:aws:lambda:us-east-1:123456789012:function:MyFn");
csharp
var fn = Function.FromFunctionArn(this, "Function", "arn:aws:lambda:us-east-1:123456789012:function:MyFn");
go
fn := lambda.Function_FromFunctionArn(this, jsii.String("Function"), jsii.String("arn:aws:lambda:us-east-1:123456789012:function:MyFn"))

The fromFunctionAttributes() API is available for more specific use cases:

ts
const fn = lambda.Function.fromFunctionAttributes(this, 'Function', {
  functionArn: '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.
  sameEnvironment: 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.
  skipPermissions: true,
});
python
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
)
java
IFunction fn = Function.fromFunctionAttributes(this, "Function", FunctionAttributes.builder()
        .functionArn("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.
        .sameEnvironment(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.
        .skipPermissions(true)
        .build());
csharp
var fn = Function.FromFunctionAttributes(this, "Function", new FunctionAttributes {
    FunctionArn = "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.
    SameEnvironment = 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.
    SkipPermissions = true
});
go
fn := lambda.Function_FromFunctionAttributes(this, jsii.String("Function"), &FunctionAttributes{
	FunctionArn: jsii.String("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.
	SameEnvironment: jsii.Boolean(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.
	SkipPermissions: jsii.Boolean(true),
})

Function.fromFunctionArn() and Function.fromFunctionAttributes() will attempt to parse the Function's Region and Account ID from the ARN. addPermissions will only work on the Function object if the Region and Account ID are deterministically the same as the scope of the Stack the referenced Function object is created in. If the containing Stack is environment-agnostic or the Function ARN is a Token, this comparison will fail, and calls to Function.addPermission will do nothing. If you know Function permissions can safely be added, you can use Function.fromFunctionName() instead, or pass sameEnvironment: true to Function.fromFunctionAttributes().

ts
const fn = lambda.Function.fromFunctionName(this, 'Function', 'MyFn');
python
fn = lambda_.Function.from_function_name(self, "Function", "MyFn")
java
IFunction fn = Function.fromFunctionName(this, "Function", "MyFn");
csharp
var fn = Function.FromFunctionName(this, "Function", "MyFn");
go
fn := lambda.Function_FromFunctionName(this, jsii.String("Function"), jsii.String("MyFn"))

Lambda with DLQ ​

A dead-letter queue can be automatically created for a Lambda function by setting the deadLetterQueueEnabled: true configuration. In such case CDK creates a sqs.Queue as deadLetterQueue.

ts
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromInline('exports.handler = function(event, ctx, cb) { return cb(null, "hi"); }'),
  deadLetterQueueEnabled: true,
});
python
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    dead_letter_queue_enabled=True
)
java
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"))
        .deadLetterQueueEnabled(true)
        .build();
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    DeadLetterQueueEnabled = true
});
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromInline(jsii.String("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }")),
	DeadLetterQueueEnabled: jsii.Boolean(true),
})

It is also possible to provide a dead-letter queue instead of getting a new queue created:

ts
import * as sqs from 'aws-cdk-lib/aws-sqs';

const dlq = new sqs.Queue(this, 'DLQ');
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromInline('exports.handler = function(event, ctx, cb) { return cb(null, "hi"); }'),
  deadLetterQueue: dlq,
});
python
import aws_cdk.aws_sqs as sqs


dlq = sqs.Queue(self, "DLQ")
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    dead_letter_queue=dlq
)
java
import software.amazon.awscdk.services.sqs.*;


Queue dlq = new Queue(this, "DLQ");
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"))
        .deadLetterQueue(dlq)
        .build();
csharp
using Amazon.CDK.AWS.SQS;


var dlq = new Queue(this, "DLQ");
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    DeadLetterQueue = dlq
});
go
import sqs "github.com/aws/aws-cdk-go/awscdk"


dlq := sqs.NewQueue(this, jsii.String("DLQ"))
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromInline(jsii.String("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }")),
	DeadLetterQueue: dlq,
})

You can also use a sns.Topic instead of an sqs.Queue as dead-letter queue:

ts
import * as sns from 'aws-cdk-lib/aws-sns';

const dlt = new sns.Topic(this, 'DLQ');
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromInline('// your code here'),
  deadLetterTopic: dlt,
});
python
import aws_cdk.aws_sns as sns


dlt = sns.Topic(self, "DLQ")
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_inline("// your code here"),
    dead_letter_topic=dlt
)
java
import software.amazon.awscdk.services.sns.*;


Topic dlt = new Topic(this, "DLQ");
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromInline("// your code here"))
        .deadLetterTopic(dlt)
        .build();
csharp
using Amazon.CDK.AWS.SNS;


var dlt = new Topic(this, "DLQ");
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromInline("// your code here"),
    DeadLetterTopic = dlt
});
go
import sns "github.com/aws/aws-cdk-go/awscdk"


dlt := sns.NewTopic(this, jsii.String("DLQ"))
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromInline(jsii.String("// your code here")),
	DeadLetterTopic: dlt,
})

See the AWS documentation to learn more about AWS Lambdas and DLQs.

Lambda with X-Ray Tracing ​

ts
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromInline('exports.handler = function(event, ctx, cb) { return cb(null, "hi"); }'),
  tracing: lambda.Tracing.ACTIVE,
});
python
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    tracing=lambda_.Tracing.ACTIVE
)
java
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"))
        .tracing(Tracing.ACTIVE)
        .build();
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    Tracing = Tracing.ACTIVE
});
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromInline(jsii.String("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }")),
	Tracing: lambda.Tracing_ACTIVE,
})

See the AWS documentation to learn more about AWS Lambda's X-Ray support.

Lambda with AWS Distro for OpenTelemetry layer ​

You can add AWS Distro for OpenTelemetry (ADOT) Lambda layers to automatically instrument your Lambda functions with OpenTelemetry.

The recommended approach uses the optimized ADOT Lambda layers (the AWSOpenTelemetryDistro* layer family). These layers provide a plug-and-play experience with support for CloudWatch Application Signals and do not bundle an embedded collector, resulting in lower overhead.

To use the optimized layers, add the layer ARN for your region and runtime from the ADOT Lambda Layer ARNs table, set the AWS_LAMBDA_EXEC_WRAPPER environment variable to /opt/otel-instrument, and attach the CloudWatchLambdaApplicationSignalsExecutionRolePolicy managed IAM policy:

ts
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromInline('exports.handler = function(event, ctx, cb) { return cb(null, "hi"); }'),
  environment: {
    AWS_LAMBDA_EXEC_WRAPPER: '/opt/otel-instrument',
  },
});

fn.addLayers(lambda.LayerVersion.fromLayerVersionArn(this, 'AdotLayer',
  // Replace with the actual ARN for your region and runtime from:
  // https://aws-otel.github.io/docs/getting-started/lambda#adot-lambda-layer-arns
  'arn:aws:lambda:us-east-1:615299751070:layer:AWSOpenTelemetryDistroJs:7',
));

fn.role?.addManagedPolicy(
  iam.ManagedPolicy.fromAwsManagedPolicyName('CloudWatchLambdaApplicationSignalsExecutionRolePolicy'),
);
python
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    environment={
        "AWS_LAMBDA_EXEC_WRAPPER": "/opt/otel-instrument"
    }
)

fn.add_layers(lambda_.LayerVersion.from_layer_version_arn(self, "AdotLayer", "arn:aws:lambda:us-east-1:615299751070:layer:AWSOpenTelemetryDistroJs:7"))

fn.role.add_managed_policy(
    iam.ManagedPolicy.from_aws_managed_policy_name("CloudWatchLambdaApplicationSignalsExecutionRolePolicy"))
java
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"))
        .environment(Map.of(
                "AWS_LAMBDA_EXEC_WRAPPER", "/opt/otel-instrument"))
        .build();

fn.addLayers(LayerVersion.fromLayerVersionArn(this, "AdotLayer", "arn:aws:lambda:us-east-1:615299751070:layer:AWSOpenTelemetryDistroJs:7"));

fn.role.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("CloudWatchLambdaApplicationSignalsExecutionRolePolicy"));
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    Environment = new Dictionary<string, string> {
        { "AWS_LAMBDA_EXEC_WRAPPER", "/opt/otel-instrument" }
    }
});

fn.AddLayers(LayerVersion.FromLayerVersionArn(this, "AdotLayer", "arn:aws:lambda:us-east-1:615299751070:layer:AWSOpenTelemetryDistroJs:7"));

fn.Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("CloudWatchLambdaApplicationSignalsExecutionRolePolicy"));
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromInline(jsii.String("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }")),
	Environment: map[string]*string{
		"AWS_LAMBDA_EXEC_WRAPPER": jsii.String("/opt/otel-instrument"),
	},
})

fn.AddLayers(lambda.LayerVersion_FromLayerVersionArn(this, jsii.String("AdotLayer"), jsii.String("arn:aws:lambda:us-east-1:615299751070:layer:AWSOpenTelemetryDistroJs:7")))

fn.Role.AddManagedPolicy(iam.ManagedPolicy_FromAwsManagedPolicyName(jsii.String("CloudWatchLambdaApplicationSignalsExecutionRolePolicy")))

Legacy ADOT Lambda layers (using adotInstrumentation) ​

Note: The adotInstrumentation property and its associated helpers (AdotLayerVersion, AdotLambdaExecWrapper, and the AdotLambdaLayer*Version classes) use the legacy ADOT Lambda layers that bundle an embedded collector. The ADOT project considers these layers not recommended for the standard CloudWatch/X-Ray path. They may still be useful if you need to export telemetry to a non-CloudWatch endpoint via a custom collector configuration.

ts
import {
  AdotLambdaExecWrapper,
  AdotLayerVersion,
  AdotLambdaLayerJavaScriptSdkVersion,
} from 'aws-cdk-lib/aws-lambda';

const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromInline('exports.handler = function(event, ctx, cb) { return cb(null, "hi"); }'),
  adotInstrumentation: {
    layerVersion: AdotLayerVersion.fromJavaScriptSdkLayerVersion(AdotLambdaLayerJavaScriptSdkVersion.LATEST),
    execWrapper: AdotLambdaExecWrapper.REGULAR_HANDLER,
  },
});
python
from aws_cdk.aws_lambda import AdotLambdaExecWrapper, AdotLayerVersion, AdotLambdaLayerJavaScriptSdkVersion


fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    adot_instrumentation=lambda.AdotInstrumentationConfig(
        layer_version=AdotLayerVersion.from_java_script_sdk_layer_version(AdotLambdaLayerJavaScriptSdkVersion.LATEST),
        exec_wrapper=AdotLambdaExecWrapper.REGULAR_HANDLER
    )
)
java
import software.amazon.awscdk.services.lambda.AdotLambdaExecWrapper;
import software.amazon.awscdk.services.lambda.AdotLayerVersion;
import software.amazon.awscdk.services.lambda.AdotLambdaLayerJavaScriptSdkVersion;


Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"))
        .adotInstrumentation(AdotInstrumentationConfig.builder()
                .layerVersion(AdotLayerVersion.fromJavaScriptSdkLayerVersion(AdotLambdaLayerJavaScriptSdkVersion.LATEST))
                .execWrapper(AdotLambdaExecWrapper.REGULAR_HANDLER)
                .build())
        .build();
csharp
using Amazon.CDK.AWS.Lambda;


var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    AdotInstrumentation = new AdotInstrumentationConfig {
        LayerVersion = AdotLayerVersion.FromJavaScriptSdkLayerVersion(AdotLambdaLayerJavaScriptSdkVersion.LATEST),
        ExecWrapper = AdotLambdaExecWrapper.REGULAR_HANDLER
    }
});
go
import "github.com/aws/aws-cdk-go/awscdk"


fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromInline(jsii.String("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }")),
	AdotInstrumentation: &AdotInstrumentationConfig{
		LayerVersion: awscdk.AdotLayerVersion_FromJavaScriptSdkLayerVersion(awscdk.AdotLambdaLayerJavaScriptSdkVersion_LATEST()),
		ExecWrapper: awscdk.AdotLambdaExecWrapper_REGULAR_HANDLER,
	},
})

The legacy helper functions for the layerVersion prop are:

  • AdotLayerVersion.fromJavaScriptSdkLayerVersion
  • AdotLayerVersion.fromPythonSdkLayerVersion
  • AdotLayerVersion.fromJavaSdkLayerVersion
  • AdotLayerVersion.fromJavaAutoInstrumentationSdkLayerVersion
  • AdotLayerVersion.fromGenericSdkLayerVersion

Each helper function expects a version value from a corresponding enum-like class as below:

  • AdotLambdaLayerJavaScriptSdkVersion
  • AdotLambdaLayerPythonSdkVersion
  • AdotLambdaLayerJavaSdkVersion
  • AdotLambdaLayerJavaAutoInstrumentationSdkVersion
  • AdotLambdaLayerGenericSdkVersion

For more examples, see our the integration test.

If you want to retrieve the ARN of a legacy ADOT Lambda layer without enabling ADOT in a Lambda function:

ts
declare const fn: lambda.Function;
const layerArn = lambda.AdotLambdaLayerJavaSdkVersion.V1_19_0.layerArn(fn.stack, fn.architecture);
python
# fn: lambda.Function

layer_arn = lambda_.AdotLambdaLayerJavaSdkVersion.V1_19_0.layer_arn(fn.stack, fn.architecture)
java
Function fn;

String layerArn = AdotLambdaLayerJavaSdkVersion.V1_19_0.layerArn(fn.getStack(), fn.getArchitecture());
csharp
Function fn;

var layerArn = AdotLambdaLayerJavaSdkVersion.V1_19_0.LayerArn(fn.Stack, fn.Architecture);
go
var fn Function

layerArn := lambda.AdotLambdaLayerJavaSdkVersion_V1_19_0().layerArn(fn.stack, fn.Architecture)

When using the AdotLambdaLayerPythonSdkVersion the AdotLambdaExecWrapper needs to be AdotLambdaExecWrapper.INSTRUMENT_HANDLER as per AWS Distro for OpenTelemetry Lambda Support For Python

Lambda with Profiling ​

The following code configures the lambda function with CodeGuru profiling. By default, this creates a new CodeGuru profiling group -

ts
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.PYTHON_3_9,
  handler: 'index.handler',
  code: lambda.Code.fromAsset('lambda-handler'),
  profiling: true,
});
python
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.PYTHON_3_9,
    handler="index.handler",
    code=lambda_.Code.from_asset("lambda-handler"),
    profiling=True
)
java
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.PYTHON_3_9)
        .handler("index.handler")
        .code(Code.fromAsset("lambda-handler"))
        .profiling(true)
        .build();
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.PYTHON_3_9,
    Handler = "index.handler",
    Code = Code.FromAsset("lambda-handler"),
    Profiling = true
});
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_PYTHON_3_9(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(jsii.String("lambda-handler")),
	Profiling: jsii.Boolean(true),
})

The profilingGroup property can be used to configure an existing CodeGuru profiler group.

CodeGuru profiling is supported for all Java runtimes and Python3.6+ runtimes.

See the AWS documentation to learn more about AWS Lambda's Profiling support.

Lambda with Reserved Concurrent Executions ​

ts
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromInline('exports.handler = function(event, ctx, cb) { return cb(null, "hi"); }'),
  reservedConcurrentExecutions: 100,
});
python
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    reserved_concurrent_executions=100
)
java
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"))
        .reservedConcurrentExecutions(100)
        .build();
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    ReservedConcurrentExecutions = 100
});
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromInline(jsii.String("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }")),
	ReservedConcurrentExecutions: jsii.Number(100),
})

https://docs.aws.amazon.com/lambda/latest/dg/invocation-recursion.html

Lambda with SnapStart ​

SnapStart is currently supported on Python 3.12, Python 3.13, .NET 8, and Java 11 and later Java managed runtimes, as well as container image (OCI) deployments. SnapStart does not support provisioned concurrency, Amazon Elastic File System (Amazon EFS), or ephemeral storage greater than 512 MB. After you enable Lambda SnapStart for a particular Lambda function, publishing a new version of the function will trigger an optimization process.

See the AWS documentation to learn more about AWS Lambda SnapStart

ts
const fn = new lambda.Function(this, 'MyFunction', {
  code: lambda.Code.fromAsset(path.join(__dirname, 'handler.zip')),
  runtime: lambda.Runtime.JAVA_11,
  handler: 'example.Handler::handleRequest',
  snapStart: lambda.SnapStartConf.ON_PUBLISHED_VERSIONS,
  });

const version = fn.currentVersion;
python
fn = lambda_.Function(self, "MyFunction",
    code=lambda_.Code.from_asset(path.join(__dirname, "handler.zip")),
    runtime=lambda_.Runtime.JAVA_11,
    handler="example.Handler::handleRequest",
    snap_start=lambda_.SnapStartConf.ON_PUBLISHED_VERSIONS
)

version = fn.current_version
java
Function fn = Function.Builder.create(this, "MyFunction")
        .code(Code.fromAsset(join(__dirname, "handler.zip")))
        .runtime(Runtime.JAVA_11)
        .handler("example.Handler::handleRequest")
        .snapStart(SnapStartConf.ON_PUBLISHED_VERSIONS)
        .build();

Version version = fn.getCurrentVersion();
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Code = Code.FromAsset(Join(__dirname, "handler.zip")),
    Runtime = Runtime.JAVA_11,
    Handler = "example.Handler::handleRequest",
    SnapStart = SnapStartConf.ON_PUBLISHED_VERSIONS
});

var version = fn.CurrentVersion;
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("handler.zip"))),
	Runtime: lambda.Runtime_JAVA_11(),
	Handler: jsii.String("example.Handler::handleRequest"),
	SnapStart: lambda.SnapStartConf_ON_PUBLISHED_VERSIONS(),
})

version := fn.currentVersion

SnapStart can also be used with container image functions:

ts
const fn = new lambda.DockerImageFunction(this, 'MyFunction', {
  code: lambda.DockerImageCode.fromImageAsset(path.join(__dirname, 'docker-handler')),
  snapStart: lambda.SnapStartConf.ON_PUBLISHED_VERSIONS,
});

const version = fn.currentVersion;
python
fn = lambda_.DockerImageFunction(self, "MyFunction",
    code=lambda_.DockerImageCode.from_image_asset(path.join(__dirname, "docker-handler")),
    snap_start=lambda_.SnapStartConf.ON_PUBLISHED_VERSIONS
)

version = fn.current_version
java
DockerImageFunction fn = DockerImageFunction.Builder.create(this, "MyFunction")
        .code(DockerImageCode.fromImageAsset(join(__dirname, "docker-handler")))
        .snapStart(SnapStartConf.ON_PUBLISHED_VERSIONS)
        .build();

Version version = fn.getCurrentVersion();
csharp
var fn = new DockerImageFunction(this, "MyFunction", new DockerImageFunctionProps {
    Code = DockerImageCode.FromImageAsset(Join(__dirname, "docker-handler")),
    SnapStart = SnapStartConf.ON_PUBLISHED_VERSIONS
});

var version = fn.CurrentVersion;
go
fn := lambda.NewDockerImageFunction(this, jsii.String("MyFunction"), &DockerImageFunctionProps{
	Code: lambda.DockerImageCode_FromImageAsset(path.join(__dirname, jsii.String("docker-handler"))),
	SnapStart: lambda.SnapStartConf_ON_PUBLISHED_VERSIONS(),
})

version := fn.currentVersion

Lambda with Durable Configuration ​

Lambda functions can be configured with durability to enable long-running, stateful executions.

ts
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  durableConfig: { executionTimeout: Duration.hours(1), retentionPeriod: Duration.days(30) }, // 1 hour timeout, 30 days retention
});
python
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    durable_config=lambda.DurableConfig(execution_timeout=Duration.hours(1), retention_period=Duration.days(30))
)
java
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .durableConfig(DurableConfig.builder().executionTimeout(Duration.hours(1)).retentionPeriod(Duration.days(30)).build())
        .build();
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    DurableConfig = new DurableConfig { ExecutionTimeout = Duration.Hours(1), RetentionPeriod = Duration.Days(30) }
});
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	DurableConfig: &DurableConfig{
		ExecutionTimeout: awscdk.Duration_Hours(jsii.Number(1)),
		RetentionPeriod: awscdk.Duration_Days(jsii.Number(30)),
	},
})

Note: If adding the durableConfig property to an existing lambda function, a resource replacement will be triggered. For the resource replacement to succeed, you cannot explicitly set the functionName parameter, or else it will result in CloudFormation deployment errors. Modifying the parameters within durableConfig will not trigger a resource replacement.

Further Note: Deletion for durable functions will wait for all running executions to complete. CloudFormation will wait up to 1 hour, after which the stack update or deletion will timeout. If you have functions that are stuck deleting, please check if there are any running executions for the function.

AutoScaling ​

You 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:

ts
import * as appscaling from 'aws-cdk-lib/aws-applicationautoscaling';

declare const fn: lambda.Function;
const alias = fn.addAlias('prod');

// Create AutoScaling target
const as = alias.addAutoScaling({ maxCapacity: 50 });

// Configure Target Tracking
as.scaleOnUtilization({
  utilizationTarget: 0.5,
});

// Configure Scheduled Scaling
as.scaleOnSchedule('ScaleUpInTheMorning', {
  schedule: appscaling.Schedule.cron({ hour: '8', minute: '0'}),
  minCapacity: 20,
});
python
import aws_cdk.aws_applicationautoscaling as appscaling

# fn: lambda.Function

alias = fn.add_alias("prod")

# Create AutoScaling target
as = alias.add_auto_scaling(max_capacity=50)

# Configure Target Tracking
as.scale_on_utilization(
    utilization_target=0.5
)

# Configure Scheduled Scaling
as.scale_on_schedule("ScaleUpInTheMorning",
    schedule=appscaling.Schedule.cron(hour="8", minute="0"),
    min_capacity=20
)
java
import software.amazon.awscdk.services.applicationautoscaling.*;

Function fn;

Alias alias = fn.addAlias("prod");

// Create AutoScaling target
IScalableFunctionAttribute as = alias.addAutoScaling(AutoScalingOptions.builder().maxCapacity(50).build());

// Configure Target Tracking
as.scaleOnUtilization(UtilizationScalingOptions.builder()
        .utilizationTarget(0.5)
        .build());

// Configure Scheduled Scaling
as.scaleOnSchedule("ScaleUpInTheMorning", ScalingSchedule.builder()
        .schedule(Schedule.cron(CronOptions.builder().hour("8").minute("0").build()))
        .minCapacity(20)
        .build());
csharp
using Amazon.CDK.AWS.ApplicationAutoScaling;

Function fn;

var alias = fn.AddAlias("prod");

// Create AutoScaling target
var as = alias.AddAutoScaling(new AutoScalingOptions { MaxCapacity = 50 });

// Configure Target Tracking
as.ScaleOnUtilization(new UtilizationScalingOptions {
    UtilizationTarget = 0.5
});

// Configure Scheduled Scaling
as.ScaleOnSchedule("ScaleUpInTheMorning", new ScalingSchedule {
    Schedule = Schedule.Cron(new CronOptions { Hour = "8", Minute = "0" }),
    MinCapacity = 20
});
go
import appscaling "github.com/aws/aws-cdk-go/awscdk"

var fn Function

alias := fn.AddAlias(jsii.String("prod"))

// Create AutoScaling target
as := alias.AddAutoScaling(&AutoScalingOptions{
	MaxCapacity: jsii.Number(50),
})

// Configure Target Tracking
as.ScaleOnUtilization(&UtilizationScalingOptions{
	UtilizationTarget: jsii.Number(0.5),
})

// Configure Scheduled Scaling
as.ScaleOnSchedule(jsii.String("ScaleUpInTheMorning"), &ScalingSchedule{
	Schedule: appscaling.Schedule_Cron(&CronOptions{
		Hour: jsii.String("8"),
		Minute: jsii.String("0"),
	}),
	MinCapacity: jsii.Number(20),
})
ts
import * as appscaling from '../../aws-applicationautoscaling';
import * as cdk from '../../core';
import { LAMBDA_RECOGNIZE_LAYER_VERSION } from '../../cx-api';
import * as lambda from '../lib';

/**
 * 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
 */
class TestStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string) {
    super(scope, id);

    const fn = new lambda.Function(this, 'MyLambda', {
      code: new lambda.InlineCode('exports.handler = async () => { console.log(\'hello world\'); };'),
      handler: 'index.handler',
      runtime: lambda.Runtime.NODEJS_LATEST,
    });

    const version = fn.currentVersion;

    const alias = new lambda.Alias(this, 'Alias', {
      aliasName: 'prod',
      version,
    });

    const scalingTarget = alias.addAutoScaling({ minCapacity: 3, maxCapacity: 50 });

    scalingTarget.scaleOnUtilization({
      utilizationTarget: 0.5,
    });

    scalingTarget.scaleOnSchedule('ScaleUpInTheMorning', {
      schedule: appscaling.Schedule.cron({ hour: '8', minute: '0' }),
      minCapacity: 20,
    });

    scalingTarget.scaleOnSchedule('ScaleDownAtNight', {
      schedule: appscaling.Schedule.cron({ hour: '20', minute: '0' }),
      maxCapacity: 20,
    });

    new cdk.CfnOutput(this, 'FunctionName', {
      value: fn.functionName,
    });
  }
}

const app = new cdk.App();

const stack = new 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(new lambda.FunctionVersionUpgrade(LAMBDA_RECOGNIZE_LAYER_VERSION));

app.synth();
python
import aws_cdk.aws_applicationautoscaling as appscaling
import aws_cdk as cdk
from ......cx_api import LAMBDA_RECOGNIZE_LAYER_VERSION
import aws_cdk as lambda_

#
# 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
#
class TestStack(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_LATEST
        )

        version = fn.current_version

        alias = 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()
java
import software.amazon.awscdk.services.applicationautoscaling.*;
import software.amazon.awscdk.*;
import cx.api.LAMBDA_RECOGNIZE_LAYER_VERSION;
import software.amazon.awscdk.*;

/**
 * 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
 */
public class TestStack extends Stack {
    public TestStack(App scope, String id) {
        super(scope, id);

        Function fn = Function.Builder.create(this, "MyLambda")
                .code(new InlineCode("exports.handler = async () => { console.log('hello world'); };"))
                .handler("index.handler")
                .runtime(Runtime.NODEJS_LATEST)
                .build();

        Version version = fn.getCurrentVersion();

        Alias alias = Alias.Builder.create(this, "Alias")
                .aliasName("prod")
                .version(version)
                .build();

        IScalableFunctionAttribute scalingTarget = alias.addAutoScaling(AutoScalingOptions.builder().minCapacity(3).maxCapacity(50).build());

        scalingTarget.scaleOnUtilization(UtilizationScalingOptions.builder()
                .utilizationTarget(0.5)
                .build());

        scalingTarget.scaleOnSchedule("ScaleUpInTheMorning", ScalingSchedule.builder()
                .schedule(Schedule.cron(CronOptions.builder().hour("8").minute("0").build()))
                .minCapacity(20)
                .build());

        scalingTarget.scaleOnSchedule("ScaleDownAtNight", ScalingSchedule.builder()
                .schedule(Schedule.cron(CronOptions.builder().hour("20").minute("0").build()))
                .maxCapacity(20)
                .build());

        CfnOutput.Builder.create(this, "FunctionName")
                .value(fn.getFunctionName())
                .build();
    }
}

App app = new App();

TestStack stack = new TestStack(app, "aws-lambda-autoscaling");

// Changes the function description when the feature flag is present
// to validate the changed function hash.
Aspects.of(stack).add(new FunctionVersionUpgrade(LAMBDA_RECOGNIZE_LAYER_VERSION));

app.synth();
csharp
using Amazon.CDK.AWS.ApplicationAutoScaling;
using Amazon.CDK;
using Cx.Api;
using Amazon.CDK;

/**
 * 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
 */
class TestStack : Stack
{
    public TestStack(App scope, string id) : base(scope, id)
    {

        var fn = new Function(this, "MyLambda", new FunctionProps {
            Code = new InlineCode("exports.handler = async () => { console.log('hello world'); };"),
            Handler = "index.handler",
            Runtime = Runtime.NODEJS_LATEST
        });

        var version = fn.CurrentVersion;

        var alias = new Alias(this, "Alias", new AliasProps {
            AliasName = "prod",
            Version = version
        });

        var scalingTarget = alias.AddAutoScaling(new AutoScalingOptions { MinCapacity = 3, MaxCapacity = 50 });

        scalingTarget.ScaleOnUtilization(new UtilizationScalingOptions {
            UtilizationTarget = 0.5
        });

        scalingTarget.ScaleOnSchedule("ScaleUpInTheMorning", new ScalingSchedule {
            Schedule = Schedule.Cron(new CronOptions { Hour = "8", Minute = "0" }),
            MinCapacity = 20
        });

        scalingTarget.ScaleOnSchedule("ScaleDownAtNight", new ScalingSchedule {
            Schedule = Schedule.Cron(new CronOptions { Hour = "20", Minute = "0" }),
            MaxCapacity = 20
        });

        new CfnOutput(this, "FunctionName", new CfnOutputProps {
            Value = fn.FunctionName
        });
    }
}

var app = new App();

var stack = new TestStack(app, "aws-lambda-autoscaling");

// Changes the function description when the feature flag is present
// to validate the changed function hash.
Aspects.Of(stack).Add(new FunctionVersionUpgrade(LAMBDA_RECOGNIZE_LAYER_VERSION));

app.Synth();
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws-samples/dummy/cxapi"
import "github.com/aws/aws-cdk-go/awscdk"

/**
 * 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
 */
type testStack struct {
	Stack
}

func newTestStack(scope App, id *string) *testStack {
	this := &testStack{}
	cdk.NewStack_Override(this, scope, id)

	fn := lambda.NewFunction(this, jsii.String("MyLambda"), &FunctionProps{
		Code: lambda.NewInlineCode(jsii.String("exports.handler = async () => { console.log('hello world'); };")),
		Handler: jsii.String("index.handler"),
		Runtime: lambda.Runtime_NODEJS_LATEST(),
	})

	version := fn.currentVersion

	alias := lambda.NewAlias(this, jsii.String("Alias"), &AliasProps{
		AliasName: jsii.String("prod"),
		Version: Version,
	})

	scalingTarget := alias.AddAutoScaling(&AutoScalingOptions{
		MinCapacity: jsii.Number(3),
		MaxCapacity: jsii.Number(50),
	})

	scalingTarget.ScaleOnUtilization(&UtilizationScalingOptions{
		UtilizationTarget: jsii.Number(0.5),
	})

	scalingTarget.ScaleOnSchedule(jsii.String("ScaleUpInTheMorning"), &ScalingSchedule{
		Schedule: appscaling.Schedule_Cron(&CronOptions{
			Hour: jsii.String("8"),
			Minute: jsii.String("0"),
		}),
		MinCapacity: jsii.Number(20),
	})

	scalingTarget.ScaleOnSchedule(jsii.String("ScaleDownAtNight"), &ScalingSchedule{
		Schedule: appscaling.Schedule_*Cron(&CronOptions{
			Hour: jsii.String("20"),
			Minute: jsii.String("0"),
		}),
		MaxCapacity: jsii.Number(20),
	})

	cdk.NewCfnOutput(this, jsii.String("FunctionName"), &CfnOutputProps{
		Value: fn.functionName,
	})
	return this
}

app := cdk.NewApp()

stack := NewTestStack(app, jsii.String("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.NewFunctionVersionUpgrade(cxapi.LAMBDA_RECOGNIZE_LAYER_VERSION))

app.Synth()

See the AWS documentation on autoscaling lambda functions.

Log Group ​

By default, Lambda functions automatically create a log group with the name /aws/lambda/<function-name> upon first execution with log data set to never expire. This is convenient, but prevents you from changing any of the properties of this auto-created log group using the AWS CDK. For example you cannot set log retention or assign a data protection policy.

To fully customize the logging behavior of your Lambda function, create a logs.LogGroup ahead of time and use the logGroup property to instruct the Lambda function to send logs to it. This way you can use the full features set supported by Amazon CloudWatch Logs.

ts
import { LogGroup } from 'aws-cdk-lib/aws-logs';

const myLogGroup = new LogGroup(this, 'MyLogGroupWithLogGroupName', {
  logGroupName: 'customLogGroup',
});

new lambda.Function(this, 'Lambda', {
  code: new lambda.InlineCode('foo'),
  handler: 'index.handler',
  runtime: lambda.Runtime.NODEJS_LATEST,
  logGroup: myLogGroup,
});
python
from aws_cdk.aws_logs import LogGroup


my_log_group = LogGroup(self, "MyLogGroupWithLogGroupName",
    log_group_name="customLogGroup"
)

lambda_.Function(self, "Lambda",
    code=lambda_.InlineCode("foo"),
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    log_group=my_log_group
)
java
import software.amazon.awscdk.services.logs.LogGroup;


LogGroup myLogGroup = LogGroup.Builder.create(this, "MyLogGroupWithLogGroupName")
        .logGroupName("customLogGroup")
        .build();

Function.Builder.create(this, "Lambda")
        .code(new InlineCode("foo"))
        .handler("index.handler")
        .runtime(Runtime.NODEJS_LATEST)
        .logGroup(myLogGroup)
        .build();
csharp
using Amazon.CDK.AWS.Logs;


var myLogGroup = new LogGroup(this, "MyLogGroupWithLogGroupName", new LogGroupProps {
    LogGroupName = "customLogGroup"
});

new Function(this, "Lambda", new FunctionProps {
    Code = new InlineCode("foo"),
    Handler = "index.handler",
    Runtime = Runtime.NODEJS_LATEST,
    LogGroup = myLogGroup
});
go
import "github.com/aws/aws-cdk-go/awscdk"


myLogGroup := awscdk.NewLogGroup(this, jsii.String("MyLogGroupWithLogGroupName"), &LogGroupProps{
	LogGroupName: jsii.String("customLogGroup"),
})

lambda.NewFunction(this, jsii.String("Lambda"), &FunctionProps{
	Code: lambda.NewInlineCode(jsii.String("foo")),
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	LogGroup: myLogGroup,
})

Providing a user-controlled log group was rolled out to commercial regions on 2023-11-16. If you are deploying to another type of region, please check regional availability first.

Lambda with Recursive Loop protection ​

Recursive loop protection is to stop unintended loops. The customers are opted in by default for Lambda to detect and terminate unintended loops between Lambda and other AWS Services. The property can be assigned two values here, "Allow" and "Terminate".

The default value is set to "Terminate", which lets the Lambda to detect and terminate the recursive loops.

When the value is set to "Allow", the customers opt out of recursive loop detection and Lambda does not terminate recursive loops if any.

See the AWS documentation to learn more about AWS Lambda Recusrive Loop Detection

ts
const fn = new lambda.Function(this, 'MyFunction', {
  code: lambda.Code.fromAsset(path.join(__dirname, 'handler.zip')),
  runtime: lambda.Runtime.JAVA_11,
  handler: 'example.Handler::handleRequest',
  recursiveLoop: lambda.RecursiveLoop.TERMINATE,
  });
python
fn = lambda_.Function(self, "MyFunction",
    code=lambda_.Code.from_asset(path.join(__dirname, "handler.zip")),
    runtime=lambda_.Runtime.JAVA_11,
    handler="example.Handler::handleRequest",
    recursive_loop=lambda_.RecursiveLoop.TERMINATE
)
java
Function fn = Function.Builder.create(this, "MyFunction")
        .code(Code.fromAsset(join(__dirname, "handler.zip")))
        .runtime(Runtime.JAVA_11)
        .handler("example.Handler::handleRequest")
        .recursiveLoop(RecursiveLoop.TERMINATE)
        .build();
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Code = Code.FromAsset(Join(__dirname, "handler.zip")),
    Runtime = Runtime.JAVA_11,
    Handler = "example.Handler::handleRequest",
    RecursiveLoop = RecursiveLoop.TERMINATE
});
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("handler.zip"))),
	Runtime: lambda.Runtime_JAVA_11(),
	Handler: jsii.String("example.Handler::handleRequest"),
	RecursiveLoop: lambda.RecursiveLoop_TERMINATE,
})

Lambda with Tenant Isolation ​

Lambda functions can be configured with tenant isolation to ensure that different tenants never share the same execution environment. This is useful for SaaS applications where you need to guarantee compute isolation between untrusted tenants while using a single Lambda function.

ts
const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  tenancyConfig: lambda.TenancyConfig.PER_TENANT,
});
python
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    tenancy_config=lambda_.TenancyConfig.PER_TENANT
)
java
Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .tenancyConfig(TenancyConfig.PER_TENANT)
        .build();
csharp
var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    TenancyConfig = TenancyConfig.PER_TENANT
});
go
fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	TenancyConfig: lambda.TenancyConfig_PER_TENANT(),
})

Important considerations:

  • Immutable configuration: Tenant isolation can only be configured during function creation and cannot be modified on existing functions.
  • Incompatible features: The following features are not compatible with tenant isolation and will result in CloudFormation deployment errors:
    • Provisioned Concurrency
    • Function URLs
    • SnapStart
    • Event Source Mappings (except API Gateway):
      • ❌ SQS
      • ❌ DynamoDB
      • ❌ Kinesis
      • ❌ MSK
      • ❌ Self-managed Kafka
      • ✅ API Gateway (supported)

CDK validates these restrictions at synthesis time and provides clear error messages when incompatible features are configured.

Legacy Log Retention ​

As an alternative to providing a custom, user controlled log group, the legacy logRetention property can be used to set a different expiration period. This feature uses a Custom Resource to change the log retention of the automatically created log group.

By default, CDK uses the AWS SDK retry options when creating a log group. The logRetentionRetryOptions property allows you to customize the maximum number of retries and base backoff duration.

Note that a CloudFormation custom resource is 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). This Custom Resource will also create a log group to log events of the custom resource. The log retention period for this addtional log group is hard-coded to 1 day.

Further note that, if the log group already exists and the logRetention is not set, the custom resource will reset the log retention to never expire even if it was configured with a different value.

FileSystem Access ​

You can configure a function to mount an Amazon Elastic File System (Amazon EFS) to a directory in your runtime environment with the filesystem property. 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/msg in the runtime environment and access the filesystem with the POSIX identity defined in posixUser.

ts
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as efs from 'aws-cdk-lib/aws-efs';

// create a new VPC
const vpc = new ec2.Vpc(this, 'VPC');

// create a new Amazon EFS filesystem
const fileSystem = new efs.FileSystem(this, 'Efs', { vpc });

// create a new access point from the filesystem
const accessPoint = fileSystem.addAccessPoint('AccessPoint', {
  // set /export/lambda as the root of the access point
  path: '/export/lambda',
  // as /export/lambda does not exist in a new efs filesystem, the efs will create the directory with the following createAcl
  createAcl: {
    ownerUid: '1001',
    ownerGid: '1001',
    permissions: '750',
  },
  // enforce the POSIX identity so lambda function will access with this identity
  posixUser: {
    uid: '1001',
    gid: '1001',
  },
});

const fn = new lambda.Function(this, 'MyLambda', {
  // mount the access point to /mnt/msg in the lambda runtime environment
  filesystem: lambda.FileSystem.fromEfsAccessPoint(accessPoint, '/mnt/msg'),
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  vpc,
});
python
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_efs as efs


# create a new VPC
vpc = ec2.Vpc(self, "VPC")

# create a new Amazon EFS filesystem
file_system = efs.FileSystem(self, "Efs", vpc=vpc)

# create a new access point from the filesystem
access_point = file_system.add_access_point("AccessPoint",
    # set /export/lambda as the root of the access point
    path="/export/lambda",
    # as /export/lambda does not exist in a new efs filesystem, the efs will create the directory with the following createAcl
    create_acl=efs.Acl(
        owner_uid="1001",
        owner_gid="1001",
        permissions="750"
    ),
    # enforce the POSIX identity so lambda function will access with this identity
    posix_user=efs.PosixUser(
        uid="1001",
        gid="1001"
    )
)

fn = lambda_.Function(self, "MyLambda",
    # mount the access point to /mnt/msg in the lambda runtime environment
    filesystem=lambda_.FileSystem.from_efs_access_point(access_point, "/mnt/msg"),
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    vpc=vpc
)
java
import software.amazon.awscdk.services.ec2.*;
import software.amazon.awscdk.services.efs.*;


// create a new VPC
Vpc vpc = new Vpc(this, "VPC");

// create a new Amazon EFS filesystem
FileSystem fileSystem = FileSystem.Builder.create(this, "Efs").vpc(vpc).build();

// create a new access point from the filesystem
AccessPoint accessPoint = fileSystem.addAccessPoint("AccessPoint", AccessPointOptions.builder()
        // set /export/lambda as the root of the access point
        .path("/export/lambda")
        // as /export/lambda does not exist in a new efs filesystem, the efs will create the directory with the following createAcl
        .createAcl(Acl.builder()
                .ownerUid("1001")
                .ownerGid("1001")
                .permissions("750")
                .build())
        // enforce the POSIX identity so lambda function will access with this identity
        .posixUser(PosixUser.builder()
                .uid("1001")
                .gid("1001")
                .build())
        .build());

Function fn = Function.Builder.create(this, "MyLambda")
        // mount the access point to /mnt/msg in the lambda runtime environment
        .filesystem(FileSystem.fromEfsAccessPoint(accessPoint, "/mnt/msg"))
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .vpc(vpc)
        .build();
csharp
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.EFS;


// create a new VPC
var vpc = new Vpc(this, "VPC");

// create a new Amazon EFS filesystem
var fileSystem = new FileSystem(this, "Efs", new FileSystemProps { Vpc = vpc });

// create a new access point from the filesystem
var accessPoint = fileSystem.AddAccessPoint("AccessPoint", new AccessPointOptions {
    // set /export/lambda as the root of the access point
    Path = "/export/lambda",
    // as /export/lambda does not exist in a new efs filesystem, the efs will create the directory with the following createAcl
    CreateAcl = new Acl {
        OwnerUid = "1001",
        OwnerGid = "1001",
        Permissions = "750"
    },
    // enforce the POSIX identity so lambda function will access with this identity
    PosixUser = new PosixUser {
        Uid = "1001",
        Gid = "1001"
    }
});

var fn = new Function(this, "MyLambda", new FunctionProps {
    // mount the access point to /mnt/msg in the lambda runtime environment
    Filesystem = FileSystem.FromEfsAccessPoint(accessPoint, "/mnt/msg"),
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    Vpc = vpc
});
go
import ec2 "github.com/aws/aws-cdk-go/awscdk"
import efs "github.com/aws/aws-cdk-go/awscdk"


// create a new VPC
vpc := ec2.NewVpc(this, jsii.String("VPC"))

// create a new Amazon EFS filesystem
fileSystem := efs.NewFileSystem(this, jsii.String("Efs"), &FileSystemProps{
	Vpc: Vpc,
})

// create a new access point from the filesystem
accessPoint := fileSystem.AddAccessPoint(jsii.String("AccessPoint"), &AccessPointOptions{
	// set /export/lambda as the root of the access point
	Path: jsii.String("/export/lambda"),
	// as /export/lambda does not exist in a new efs filesystem, the efs will create the directory with the following createAcl
	CreateAcl: &Acl{
		OwnerUid: jsii.String("1001"),
		OwnerGid: jsii.String("1001"),
		Permissions: jsii.String("750"),
	},
	// enforce the POSIX identity so lambda function will access with this identity
	PosixUser: &PosixUser{
		Uid: jsii.String("1001"),
		Gid: jsii.String("1001"),
	},
})

fn := lambda.NewFunction(this, jsii.String("MyLambda"), &FunctionProps{
	// mount the access point to /mnt/msg in the lambda runtime environment
	Filesystem: lambda.FileSystem_FromEfsAccessPoint(accessPoint, jsii.String("/mnt/msg")),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	Vpc: Vpc,
})

S3 Files Filesystem ​

Amazon S3 Files provides a fully managed NFS file system backed by an S3 bucket. Lambda functions can mount an S3 Files file system to read and write files using standard filesystem operations, which is useful for workloads that need POSIX-compatible file access to S3 data — such as ML inference, media processing, or legacy applications that expect a local mount path.

Note: S3 Files currently only has L1 (CloudFormation) constructs. The setup below requires more manual wiring than the equivalent EFS integration. L2 constructs will simplify this in a future release.

S3 Files uses the same NFS infrastructure as Amazon EFS. To mount the file system in Lambda, you need:

  • File system (CfnFileSystem) — the NFS file system backed by your S3 bucket. The backing bucket must have versioning enabled, as S3 Files relies on object versions to maintain consistency between the file system and S3. The file system requires an IAM role with two sets of permissions:
    • S3 permissions — read/write access to the bucket and its objects so S3 Files can synchronize data.
    • EventBridge permissions — S3 Files creates and manages EventBridge rules (prefixed DO-NOT-DELETE-S3-Files) to detect S3 object changes and trigger data synchronization. The role needs permission to manage these rules, plus read-only access to list rules for monitoring.
  • Mount targets (CfnMountTarget) — ENIs placed in your VPC subnets that allow NFS clients (like Lambda) to connect. Each mount target needs a security group that permits inbound NFS traffic (TCP port 2049).
  • Access point (CfnAccessPoint) — defines the POSIX user identity and root directory path that Lambda uses when accessing the file system. This scopes and isolates the function's view of the file system.

You can optionally configure directS3Read to stream eligible reads directly from the S3 bucket for higher throughput instead of routing them through the file system mount using DirectS3Read.enabled(bucket), DirectS3Read.enabledWithoutGrant(), DirectS3Read.auto(), or DirectS3Read.disabled().

To use direct reads, the function's execution role needs the s3:GetObject and s3:GetObjectVersion permissions on the backing bucket for a direct read to succeed (if a direct read fails, Lambda falls back to reading through the file system). DirectS3Read.enabled(bucket) grants these permissions to the execution role automatically. Use DirectS3Read.enabledWithoutGrant() when the role already has read access through another policy; you are then responsible for the grant (and kms:Decrypt if the bucket is encrypted with a customer-managed key). DirectS3Read.auto() adds no permissions, so the role must already hold them for a service-initiated direct read to succeed.

Use DirectS3Read.disabled() to opt-out from this feature.

Visit S3FilesConfig for more details.

ts
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as s3files from 'aws-cdk-lib/aws-s3files';

const vpc = new ec2.Vpc(this, 'Vpc');

// Versioning is required — S3 Files relies on object versions for consistency.
const bucket = new s3.Bucket(this, 'Bucket', { versioned: true });

// S3 Files assumes this role to sync data between S3 and the file system.
const role = new iam.Role(this, 'S3FilesRole', {
  assumedBy: new iam.ServicePrincipal('elasticfilesystem.amazonaws.com'),
});

// S3 permissions: read/write access to the bucket and objects
role.addToPolicy(new iam.PolicyStatement({
  actions: ['s3:ListBucket*'],
  resources: [bucket.bucketArn],
}));
role.addToPolicy(new iam.PolicyStatement({
  actions: ['s3:AbortMultipartUpload', 's3:DeleteObject', 's3:GetObject*', 's3:List*', 's3:PutObject*'],
  resources: [bucket.arnForObjects('*')],
}));

// EventBridge permissions: S3 Files creates rules prefixed "DO-NOT-DELETE-S3-Files"
// to detect S3 object changes and trigger data synchronization.
role.addToPolicy(new iam.PolicyStatement({
  actions: [
    'events:DeleteRule', 'events:DisableRule', 'events:EnableRule',
    'events:PutRule', 'events:PutTargets', 'events:RemoveTargets',
  ],
  resources: [`arn:${cdk.Aws.PARTITION}:events:*:*:rule/DO-NOT-DELETE-S3-Files*`],
  conditions: { StringEquals: { 'events:ManagedBy': 'elasticfilesystem.amazonaws.com' } },
}));
role.addToPolicy(new iam.PolicyStatement({
  actions: ['events:DescribeRule', 'events:ListRuleNamesByTarget', 'events:ListRules', 'events:ListTargetsByRule'],
  resources: [`arn:${cdk.Aws.PARTITION}:events:*:*:rule/*`],
}));

const fileSystem = new s3files.CfnFileSystem(this, 'S3FilesFs', {
  bucket: bucket.bucketArn,
  roleArn: role.roleArn,
});

const sg = new ec2.SecurityGroup(this, 'MountTargetSG', { vpc });

// Create a mount target in each private subnet so Lambda can reach the file system via NFS.
vpc.privateSubnets.forEach((subnet, i) =>
  new s3files.CfnMountTarget(this, `MountTarget${i}`, {
    fileSystemId: fileSystem.attrFileSystemId,
    subnetId: subnet.subnetId,
    securityGroups: [sg.securityGroupId],
  }),
);

// The access point defines the POSIX identity and root path Lambda uses on the file system.
const accessPoint = new s3files.CfnAccessPoint(this, 'AccessPoint', {
  fileSystemId: fileSystem.attrFileSystemId,
  rootDirectory: {
    path: '/export/lambda',
    creationPermissions: { ownerGid: '1001', ownerUid: '1001', permissions: '750' },
  },
  posixUser: { gid: '1001', uid: '1001' },
});

const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  vpc,
  filesystem: lambda.FileSystem.fromS3FilesAccessPoint(accessPoint, '/mnt/s3files', {
    // Enables direct reads and grants s3:GetObject/s3:GetObjectVersion on the bucket to the execution role.
    directS3Read: lambda.DirectS3Read.enabled(bucket),
  }),
});
python
import aws_cdk as cdk
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_s3 as s3
import aws_cdk.aws_s3files as s3files


vpc = ec2.Vpc(self, "Vpc")

# Versioning is required — S3 Files relies on object versions for consistency.
bucket = s3.Bucket(self, "Bucket", versioned=True)

# S3 Files assumes this role to sync data between S3 and the file system.
role = iam.Role(self, "S3FilesRole",
    assumed_by=iam.ServicePrincipal("elasticfilesystem.amazonaws.com")
)

# S3 permissions: read/write access to the bucket and objects
role.add_to_policy(iam.PolicyStatement(
    actions=["s3:ListBucket*"],
    resources=[bucket.bucket_arn]
))
role.add_to_policy(iam.PolicyStatement(
    actions=["s3:AbortMultipartUpload", "s3:DeleteObject", "s3:GetObject*", "s3:List*", "s3:PutObject*"],
    resources=[bucket.arn_for_objects("*")]
))

# EventBridge permissions: S3 Files creates rules prefixed "DO-NOT-DELETE-S3-Files"
# to detect S3 object changes and trigger data synchronization.
role.add_to_policy(iam.PolicyStatement(
    actions=["events:DeleteRule", "events:DisableRule", "events:EnableRule", "events:PutRule", "events:PutTargets", "events:RemoveTargets"
    ],
    resources=[f"arn:{cdk.Aws.PARTITION}:events:*:*:rule/DO-NOT-DELETE-S3-Files*"],
    conditions={"StringEquals": {"events:ManagedBy": "elasticfilesystem.amazonaws.com"}}
))
role.add_to_policy(iam.PolicyStatement(
    actions=["events:DescribeRule", "events:ListRuleNamesByTarget", "events:ListRules", "events:ListTargetsByRule"],
    resources=[f"arn:{cdk.Aws.PARTITION}:events:*:*:rule/*"]
))

file_system = s3files.CfnFileSystem(self, "S3FilesFs",
    bucket=bucket.bucket_arn,
    role_arn=role.role_arn
)

sg = ec2.SecurityGroup(self, "MountTargetSG", vpc=vpc)

# Create a mount target in each private subnet so Lambda can reach the file system via NFS.
vpc.private_subnets.for_each((subnet, i) =>
      new s3files.CfnMountTarget(this, `MountTarget${i}`, {
        fileSystemId: fileSystem.attrFileSystemId,
        subnetId: subnet.subnetId,
        securityGroups: [sg.securityGroupId],
      }))

# The access point defines the POSIX identity and root path Lambda uses on the file system.
access_point = s3files.CfnAccessPoint(self, "AccessPoint",
    file_system_id=file_system.attr_file_system_id,
    root_directory=s3files.CfnAccessPoint.RootDirectoryProperty(
        path="/export/lambda",
        creation_permissions=s3files.CfnAccessPoint.CreationPermissionsProperty(owner_gid="1001", owner_uid="1001", permissions="750")
    ),
    posix_user=s3files.CfnAccessPoint.PosixUserProperty(gid="1001", uid="1001")
)

fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    vpc=vpc,
    filesystem=lambda_.FileSystem.from_s3_files_access_point(access_point, "/mnt/s3files",
        # Enables direct reads and grants s3:GetObject/s3:GetObjectVersion on the bucket to the execution role.
        direct_s3_read=lambda_.DirectS3Read.enabled(bucket)
    )
)
java
import software.amazon.awscdk.*;
import software.amazon.awscdk.services.ec2.*;
import software.amazon.awscdk.services.s3.*;
import software.amazon.awscdk.services.s3files.*;


Vpc vpc = new Vpc(this, "Vpc");

// Versioning is required — S3 Files relies on object versions for consistency.
Bucket bucket = Bucket.Builder.create(this, "Bucket").versioned(true).build();

// S3 Files assumes this role to sync data between S3 and the file system.
Role role = Role.Builder.create(this, "S3FilesRole")
        .assumedBy(new ServicePrincipal("elasticfilesystem.amazonaws.com"))
        .build();

// S3 permissions: read/write access to the bucket and objects
role.addToPolicy(PolicyStatement.Builder.create()
        .actions(List.of("s3:ListBucket*"))
        .resources(List.of(bucket.getBucketArn()))
        .build());
role.addToPolicy(PolicyStatement.Builder.create()
        .actions(List.of("s3:AbortMultipartUpload", "s3:DeleteObject", "s3:GetObject*", "s3:List*", "s3:PutObject*"))
        .resources(List.of(bucket.arnForObjects("*")))
        .build());

// EventBridge permissions: S3 Files creates rules prefixed "DO-NOT-DELETE-S3-Files"
// to detect S3 object changes and trigger data synchronization.
role.addToPolicy(PolicyStatement.Builder.create()
        .actions(List.of("events:DeleteRule", "events:DisableRule", "events:EnableRule", "events:PutRule", "events:PutTargets", "events:RemoveTargets"))
        .resources(List.of(String.format("arn:%s:events:*:*:rule/DO-NOT-DELETE-S3-Files*", Aws.PARTITION)))
        .conditions(Map.of("StringEquals", Map.of("events:ManagedBy", "elasticfilesystem.amazonaws.com")))
        .build());
role.addToPolicy(PolicyStatement.Builder.create()
        .actions(List.of("events:DescribeRule", "events:ListRuleNamesByTarget", "events:ListRules", "events:ListTargetsByRule"))
        .resources(List.of(String.format("arn:%s:events:*:*:rule/*", Aws.PARTITION)))
        .build());

CfnFileSystem fileSystem = CfnFileSystem.Builder.create(this, "S3FilesFs")
        .bucket(bucket.getBucketArn())
        .roleArn(role.getRoleArn())
        .build();

SecurityGroup sg = SecurityGroup.Builder.create(this, "MountTargetSG").vpc(vpc).build();

// Create a mount target in each private subnet so Lambda can reach the file system via NFS.
vpc.privateSubnets.forEach((subnet, i) =>
  new s3files.CfnMountTarget(this, `MountTarget${i}`, {
    fileSystemId: fileSystem.attrFileSystemId,
    subnetId: subnet.subnetId,
    securityGroups: [sg.securityGroupId],
  }));

// The access point defines the POSIX identity and root path Lambda uses on the file system.
CfnAccessPoint accessPoint = CfnAccessPoint.Builder.create(this, "AccessPoint")
        .fileSystemId(fileSystem.getAttrFileSystemId())
        .rootDirectory(RootDirectoryProperty.builder()
                .path("/export/lambda")
                .creationPermissions(CreationPermissionsProperty.builder().ownerGid("1001").ownerUid("1001").permissions("750").build())
                .build())
        .posixUser(PosixUserProperty.builder().gid("1001").uid("1001").build())
        .build();

Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .vpc(vpc)
        .filesystem(FileSystem.fromS3FilesAccessPoint(accessPoint, "/mnt/s3files", S3FilesOptions.builder()
                // Enables direct reads and grants s3:GetObject/s3:GetObjectVersion on the bucket to the execution role.
                .directS3Read(DirectS3Read.enabled(bucket))
                .build()))
        .build();
csharp
using Amazon.CDK;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.S3;
using Amazon.CDK.AWS.S3Files;


var vpc = new Vpc(this, "Vpc");

// Versioning is required — S3 Files relies on object versions for consistency.
var bucket = new Bucket(this, "Bucket", new BucketProps { Versioned = true });

// S3 Files assumes this role to sync data between S3 and the file system.
var role = new Role(this, "S3FilesRole", new RoleProps {
    AssumedBy = new ServicePrincipal("elasticfilesystem.amazonaws.com")
});

// S3 permissions: read/write access to the bucket and objects
role.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
    Actions = new [] { "s3:ListBucket*" },
    Resources = new [] { bucket.BucketArn }
}));
role.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
    Actions = new [] { "s3:AbortMultipartUpload", "s3:DeleteObject", "s3:GetObject*", "s3:List*", "s3:PutObject*" },
    Resources = new [] { bucket.ArnForObjects("*") }
}));

// EventBridge permissions: S3 Files creates rules prefixed "DO-NOT-DELETE-S3-Files"
// to detect S3 object changes and trigger data synchronization.
role.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
    Actions = new [] { "events:DeleteRule", "events:DisableRule", "events:EnableRule", "events:PutRule", "events:PutTargets", "events:RemoveTargets" },
    Resources = new [] { $"arn:{cdk.Aws.PARTITION}:events:*:*:rule/DO-NOT-DELETE-S3-Files*" },
    Conditions = new Dictionary<string, object> { { "StringEquals", new Dictionary<string, string> { { "events:ManagedBy", "elasticfilesystem.amazonaws.com" } } } }
}));
role.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
    Actions = new [] { "events:DescribeRule", "events:ListRuleNamesByTarget", "events:ListRules", "events:ListTargetsByRule" },
    Resources = new [] { $"arn:{cdk.Aws.PARTITION}:events:*:*:rule/*" }
}));

var fileSystem = new CfnFileSystem(this, "S3FilesFs", new CfnFileSystemProps {
    Bucket = bucket.BucketArn,
    RoleArn = role.RoleArn
});

var sg = new SecurityGroup(this, "MountTargetSG", new SecurityGroupProps { Vpc = vpc });

// Create a mount target in each private subnet so Lambda can reach the file system via NFS.
vpc.PrivateSubnets.ForEach((subnet, i) =>
  new s3files.CfnMountTarget(this, `MountTarget${i}`, {
    fileSystemId: fileSystem.attrFileSystemId,
    subnetId: subnet.subnetId,
    securityGroups: [sg.securityGroupId],
  }));

// The access point defines the POSIX identity and root path Lambda uses on the file system.
var accessPoint = new CfnAccessPoint(this, "AccessPoint", new CfnAccessPointProps {
    FileSystemId = fileSystem.AttrFileSystemId,
    RootDirectory = new RootDirectoryProperty {
        Path = "/export/lambda",
        CreationPermissions = new CreationPermissionsProperty { OwnerGid = "1001", OwnerUid = "1001", Permissions = "750" }
    },
    PosixUser = new PosixUserProperty { Gid = "1001", Uid = "1001" }
});

var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    Vpc = vpc,
    Filesystem = FileSystem.FromS3FilesAccessPoint(accessPoint, "/mnt/s3files", new S3FilesOptions {
        // Enables direct reads and grants s3:GetObject/s3:GetObjectVersion on the bucket to the execution role.
        DirectS3Read = DirectS3Read.Enabled(bucket)
    })
});
go
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import s3 "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("Vpc"))

// Versioning is required — S3 Files relies on object versions for consistency.
bucket := s3.NewBucket(this, jsii.String("Bucket"), &BucketProps{
	Versioned: jsii.Boolean(true),
})

// S3 Files assumes this role to sync data between S3 and the file system.
role := iam.NewRole(this, jsii.String("S3FilesRole"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("elasticfilesystem.amazonaws.com")),
})

// S3 permissions: read/write access to the bucket and objects
role.AddToPolicy(iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
		jsii.String("s3:ListBucket*"),
	},
	Resources: []*string{
		bucket.bucketArn,
	},
}))
role.AddToPolicy(iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
		jsii.String("s3:AbortMultipartUpload"),
		jsii.String("s3:DeleteObject"),
		jsii.String("s3:GetObject*"),
		jsii.String("s3:List*"),
		jsii.String("s3:PutObject*"),
	},
	Resources: []*string{
		bucket.ArnForObjects(jsii.String("*")),
	},
}))

// EventBridge permissions: S3 Files creates rules prefixed "DO-NOT-DELETE-S3-Files"
// to detect S3 object changes and trigger data synchronization.
role.AddToPolicy(iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
		jsii.String("events:DeleteRule"),
		jsii.String("events:DisableRule"),
		jsii.String("events:EnableRule"),
		jsii.String("events:PutRule"),
		jsii.String("events:PutTargets"),
		jsii.String("events:RemoveTargets"),
	},
	Resources: []*string{
		fmt.Sprintf("arn:%v:events:*:*:rule/DO-NOT-DELETE-S3-Files*", cdk.Aws_PARTITION()),
	},
	Conditions: map[string]interface{}{
		"StringEquals": map[string]*string{
			"events:ManagedBy": jsii.String("elasticfilesystem.amazonaws.com"),
		},
	},
}))
role.AddToPolicy(iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
		jsii.String("events:DescribeRule"),
		jsii.String("events:ListRuleNamesByTarget"),
		jsii.String("events:ListRules"),
		jsii.String("events:ListTargetsByRule"),
	},
	Resources: []*string{
		fmt.Sprintf("arn:%v:events:*:*:rule/*", cdk.Aws_PARTITION()),
	},
}))

fileSystem := s3files.NewCfnFileSystem(this, jsii.String("S3FilesFs"), &CfnFileSystemProps{
	Bucket: bucket.bucketArn,
	RoleArn: role.roleArn,
})

sg := ec2.NewSecurityGroup(this, jsii.String("MountTargetSG"), &SecurityGroupProps{
	Vpc: Vpc,
})

// Create a mount target in each private subnet so Lambda can reach the file system via NFS.
vpc.PrivateSubnets.forEach((subnet, i) =>
  new s3files.CfnMountTarget(this, `MountTarget${i}`, {
    fileSystemId: fileSystem.attrFileSystemId,
    subnetId: subnet.subnetId,
    securityGroups: [sg.securityGroupId],
  }))

// The access point defines the POSIX identity and root path Lambda uses on the file system.
accessPoint := s3files.NewCfnAccessPoint(this, jsii.String("AccessPoint"), &CfnAccessPointProps{
	FileSystemId: fileSystem.attrFileSystemId,
	RootDirectory: &RootDirectoryProperty{
		Path: jsii.String("/export/lambda"),
		CreationPermissions: &CreationPermissionsProperty{
			OwnerGid: jsii.String("1001"),
			OwnerUid: jsii.String("1001"),
			Permissions: jsii.String("750"),
		},
	},
	PosixUser: &PosixUserProperty{
		Gid: jsii.String("1001"),
		Uid: jsii.String("1001"),
	},
})

fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	Vpc: Vpc,
	Filesystem: lambda.FileSystem_FromS3FilesAccessPoint(accessPoint, jsii.String("/mnt/s3files"), &S3FilesOptions{
		// Enables direct reads and grants s3:GetObject/s3:GetObjectVersion on the bucket to the execution role.
		DirectS3Read: lambda.DirectS3Read_Enabled(bucket),
	}),
})

IPv6 support ​

You can configure IPv6 connectivity for lambda function by setting Ipv6AllowedForDualStack to true. It allows Lambda functions to specify whether the IPv6 traffic should be allowed when using dual-stack VPCs. To access IPv6 network using Lambda, Dual-stack VPC is required. Using dual-stack VPC a function communicates with subnet over either of IPv4 or IPv6.

ts
import * as ec2 from 'aws-cdk-lib/aws-ec2';

const natProvider = ec2.NatProvider.gateway();

// create dual-stack VPC
const vpc = new ec2.Vpc(this, 'DualStackVpc', {
  ipProtocol: ec2.IpProtocol.DUAL_STACK,
  subnetConfiguration: [
    {
      name: 'Ipv6Public1',
      subnetType: ec2.SubnetType.PUBLIC,
    },
    {
      name: 'Ipv6Public2',
      subnetType: ec2.SubnetType.PUBLIC,
    },
    {
      name: 'Ipv6Private1',
      subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
    },
  ],
  natGatewayProvider: natProvider,
});

const natGatewayId = natProvider.configuredGateways[0].gatewayId;
(vpc.privateSubnets[0] as ec2.PrivateSubnet).addIpv6Nat64Route(natGatewayId);

const fn = new lambda.Function(this, 'Lambda_with_IPv6_VPC', {
  code: new lambda.InlineCode('def main(event, context): pass'),
  handler: 'index.main',
  runtime: lambda.Runtime.PYTHON_3_9,
  vpc,
  ipv6AllowedForDualStack: true,
});
python
import aws_cdk.aws_ec2 as ec2


nat_provider = ec2.NatProvider.gateway()

# create dual-stack VPC
vpc = ec2.Vpc(self, "DualStackVpc",
    ip_protocol=ec2.IpProtocol.DUAL_STACK,
    subnet_configuration=[ec2.SubnetConfiguration(
        name="Ipv6Public1",
        subnet_type=ec2.SubnetType.PUBLIC
    ), ec2.SubnetConfiguration(
        name="Ipv6Public2",
        subnet_type=ec2.SubnetType.PUBLIC
    ), ec2.SubnetConfiguration(
        name="Ipv6Private1",
        subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS
    )
    ],
    nat_gateway_provider=nat_provider
)

nat_gateway_id = nat_provider.configured_gateways[0].gateway_id
(vpc.private_subnets[0]).add_ipv6_nat64_route(nat_gateway_id)

fn = lambda_.Function(self, "Lambda_with_IPv6_VPC",
    code=lambda_.InlineCode("def main(event, context): pass"),
    handler="index.main",
    runtime=lambda_.Runtime.PYTHON_3_9,
    vpc=vpc,
    ipv6_allowed_for_dual_stack=True
)
java
import software.amazon.awscdk.services.ec2.*;


NatProvider natProvider = NatProvider.gateway();

// create dual-stack VPC
Vpc vpc = Vpc.Builder.create(this, "DualStackVpc")
        .ipProtocol(IpProtocol.DUAL_STACK)
        .subnetConfiguration(List.of(SubnetConfiguration.builder()
                .name("Ipv6Public1")
                .subnetType(SubnetType.PUBLIC)
                .build(), SubnetConfiguration.builder()
                .name("Ipv6Public2")
                .subnetType(SubnetType.PUBLIC)
                .build(), SubnetConfiguration.builder()
                .name("Ipv6Private1")
                .subnetType(SubnetType.PRIVATE_WITH_EGRESS)
                .build()))
        .natGatewayProvider(natProvider)
        .build();

String natGatewayId = natProvider.getConfiguredGateways()[0].getGatewayId();
((PrivateSubnet)vpc.privateSubnets[0]).addIpv6Nat64Route(natGatewayId);

Function fn = Function.Builder.create(this, "Lambda_with_IPv6_VPC")
        .code(new InlineCode("def main(event, context): pass"))
        .handler("index.main")
        .runtime(Runtime.PYTHON_3_9)
        .vpc(vpc)
        .ipv6AllowedForDualStack(true)
        .build();
csharp
using Amazon.CDK.AWS.EC2;


var natProvider = NatProvider.Gateway();

// create dual-stack VPC
var vpc = new Vpc(this, "DualStackVpc", new VpcProps {
    IpProtocol = IpProtocol.DUAL_STACK,
    SubnetConfiguration = new [] { new SubnetConfiguration {
        Name = "Ipv6Public1",
        SubnetType = SubnetType.PUBLIC
    }, new SubnetConfiguration {
        Name = "Ipv6Public2",
        SubnetType = SubnetType.PUBLIC
    }, new SubnetConfiguration {
        Name = "Ipv6Private1",
        SubnetType = SubnetType.PRIVATE_WITH_EGRESS
    } },
    NatGatewayProvider = natProvider
});

var natGatewayId = natProvider.ConfiguredGateways[0].GatewayId;
((PrivateSubnet)vpc.PrivateSubnets[0]).AddIpv6Nat64Route(natGatewayId);

var fn = new Function(this, "Lambda_with_IPv6_VPC", new FunctionProps {
    Code = new InlineCode("def main(event, context): pass"),
    Handler = "index.main",
    Runtime = Runtime.PYTHON_3_9,
    Vpc = vpc,
    Ipv6AllowedForDualStack = true
});
go
import "github.com/aws/aws-cdk-go/awscdk"


natProvider := ec2.NatProvider_Gateway()

// create dual-stack VPC
vpc := ec2.NewVpc(this, jsii.String("DualStackVpc"), &VpcProps{
	IpProtocol: ec2.IpProtocol_DUAL_STACK,
	SubnetConfiguration: []SubnetConfiguration{
		&SubnetConfiguration{
			Name: jsii.String("Ipv6Public1"),
			SubnetType: ec2.SubnetType_PUBLIC,
		},
		&SubnetConfiguration{
			Name: jsii.String("Ipv6Public2"),
			SubnetType: ec2.SubnetType_PUBLIC,
		},
		&SubnetConfiguration{
			Name: jsii.String("Ipv6Private1"),
			SubnetType: ec2.SubnetType_PRIVATE_WITH_EGRESS,
		},
	},
	NatGatewayProvider: natProvider,
})

natGatewayId := natProvider.ConfiguredGateways[0].GatewayId
(vpc.PrivateSubnets[0].(PrivateSubnet)).AddIpv6Nat64Route(natGatewayId)

fn := lambda.NewFunction(this, jsii.String("Lambda_with_IPv6_VPC"), &FunctionProps{
	Code: lambda.NewInlineCode(jsii.String("def main(event, context): pass")),
	Handler: jsii.String("index.main"),
	Runtime: lambda.Runtime_PYTHON_3_9(),
	Vpc: Vpc,
	Ipv6AllowedForDualStack: jsii.Boolean(true),
})

Outbound traffic ​

By default, when creating a Lambda function, it would add a security group outbound rule to allow sending all network traffic (except IPv6). This is controlled by allowAllOutbound in function properties, which has a default value of true.

To allow outbound IPv6 traffic by default, explicitly set allowAllIpv6Outbound to true in function properties as shown below (the default value for allowAllIpv6Outbound is false):

ts
import * as ec2 from 'aws-cdk-lib/aws-ec2';

const vpc = new ec2.Vpc(this, 'Vpc');

const fn = new lambda.Function(this, 'LambdaWithIpv6Outbound', {
  code: new lambda.InlineCode('def main(event, context): pass'),
  handler: 'index.main',
  runtime: lambda.Runtime.PYTHON_3_9,
  vpc: vpc,
  allowAllIpv6Outbound: true,
});
python
import aws_cdk.aws_ec2 as ec2


vpc = ec2.Vpc(self, "Vpc")

fn = lambda_.Function(self, "LambdaWithIpv6Outbound",
    code=lambda_.InlineCode("def main(event, context): pass"),
    handler="index.main",
    runtime=lambda_.Runtime.PYTHON_3_9,
    vpc=vpc,
    allow_all_ipv6_outbound=True
)
java
import software.amazon.awscdk.services.ec2.*;


Vpc vpc = new Vpc(this, "Vpc");

Function fn = Function.Builder.create(this, "LambdaWithIpv6Outbound")
        .code(new InlineCode("def main(event, context): pass"))
        .handler("index.main")
        .runtime(Runtime.PYTHON_3_9)
        .vpc(vpc)
        .allowAllIpv6Outbound(true)
        .build();
csharp
using Amazon.CDK.AWS.EC2;


var vpc = new Vpc(this, "Vpc");

var fn = new Function(this, "LambdaWithIpv6Outbound", new FunctionProps {
    Code = new InlineCode("def main(event, context): pass"),
    Handler = "index.main",
    Runtime = Runtime.PYTHON_3_9,
    Vpc = vpc,
    AllowAllIpv6Outbound = true
});
go
import ec2 "github.com/aws/aws-cdk-go/awscdk"


vpc := ec2.NewVpc(this, jsii.String("Vpc"))

fn := lambda.NewFunction(this, jsii.String("LambdaWithIpv6Outbound"), &FunctionProps{
	Code: lambda.NewInlineCode(jsii.String("def main(event, context): pass")),
	Handler: jsii.String("index.main"),
	Runtime: lambda.Runtime_PYTHON_3_9(),
	Vpc: vpc,
	AllowAllIpv6Outbound: jsii.Boolean(true),
})

Do not specify allowAllOutbound or allowAllIpv6Outbound property if the securityGroups or securityGroup property is set. Instead, configure these properties directly on the security group.

Ephemeral Storage ​

You 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' /tmp directory.

ts
import { Size } from 'aws-cdk-lib';

const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
  ephemeralStorageSize: Size.mebibytes(1024),
});
python
from aws_cdk import Size


fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    ephemeral_storage_size=Size.mebibytes(1024)
)
java
import software.amazon.awscdk.Size;


Function fn = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .ephemeralStorageSize(Size.mebibytes(1024))
        .build();
csharp
using Amazon.CDK;


var fn = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
    EphemeralStorageSize = Size.Mebibytes(1024)
});
go
import "github.com/aws/aws-cdk-go/awscdk"


fn := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
	EphemeralStorageSize: awscdk.Size_Mebibytes(jsii.Number(1024)),
})

Read more about using this feature in this AWS blog post.

Singleton Function ​

The SingletonFunction construct 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 the uuid property and the optional lambdaPurpose property 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. Using SingletonFunction here with a fixed uuid will guarantee this.

For example, the AwsCustomResource construct requires only one single lambda function for all api calls that are made.

Bundling Asset Code ​

When using lambda.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-output will be zipped and used as Lambda code.

Example with Python:

ts
new lambda.Function(this, 'Function', {
  code: lambda.Code.fromAsset(path.join(__dirname, 'my-python-handler'), {
    bundling: {
      image: lambda.Runtime.PYTHON_3_9.bundlingImage,
      command: [
        'bash', '-c',
        'pip install -r requirements.txt -t /asset-output && cp -au . /asset-output'
      ],
    },
  }),
  runtime: lambda.Runtime.PYTHON_3_9,
  handler: 'index.handler',
});
python
from aws_cdk import BundlingOptions
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"
)
java
Function.Builder.create(this, "Function")
        .code(Code.fromAsset(join(__dirname, "my-python-handler"), AssetOptions.builder()
                .bundling(BundlingOptions.builder()
                        .image(Runtime.PYTHON_3_9.getBundlingImage())
                        .command(List.of("bash", "-c", "pip install -r requirements.txt -t /asset-output && cp -au . /asset-output"))
                        .build())
                .build()))
        .runtime(Runtime.PYTHON_3_9)
        .handler("index.handler")
        .build();
csharp
new Function(this, "Function", new FunctionProps {
    Code = Code.FromAsset(Join(__dirname, "my-python-handler"), new AssetOptions {
        Bundling = new BundlingOptions {
            Image = Runtime.PYTHON_3_9.BundlingImage,
            Command = new [] { "bash", "-c", "pip install -r requirements.txt -t /asset-output && cp -au . /asset-output" }
        }
    }),
    Runtime = Runtime.PYTHON_3_9,
    Handler = "index.handler"
});
go
lambda.NewFunction(this, jsii.String("Function"), &FunctionProps{
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("my-python-handler")), &AssetOptions{
		Bundling: &BundlingOptions{
			Image: lambda.Runtime_PYTHON_3_9().BundlingImage,
			Command: []*string{
				jsii.String("bash"),
				jsii.String("-c"),
				jsii.String("pip install -r requirements.txt -t /asset-output && cp -au . /asset-output"),
			},
		},
	}),
	Runtime: lambda.Runtime_PYTHON_3_9(),
	Handler: jsii.String("index.handler"),
})

Runtimes expose a bundlingImage property that points to the AWS SAM build image.

Use cdk.DockerImage.fromRegistry(image) to use an existing image or cdk.DockerImage.fromBuild(path) to build a specific image:

ts
new lambda.Function(this, 'Function', {
  code: lambda.Code.fromAsset('/path/to/handler', {
    bundling: {
      image: DockerImage.fromBuild('/path/to/dir/with/DockerFile', {
        buildArgs: {
          ARG1: 'value1',
        },
      }),
      command: ['my', 'cool', 'command'],
    },
  }),
  runtime: lambda.Runtime.PYTHON_3_9,
  handler: 'index.handler',
});
python
from aws_cdk import BundlingOptions
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"
)
java
Function.Builder.create(this, "Function")
        .code(Code.fromAsset("/path/to/handler", AssetOptions.builder()
                .bundling(BundlingOptions.builder()
                        .image(DockerImage.fromBuild("/path/to/dir/with/DockerFile", DockerBuildOptions.builder()
                                .buildArgs(Map.of(
                                        "ARG1", "value1"))
                                .build()))
                        .command(List.of("my", "cool", "command"))
                        .build())
                .build()))
        .runtime(Runtime.PYTHON_3_9)
        .handler("index.handler")
        .build();
csharp
new Function(this, "Function", new FunctionProps {
    Code = Code.FromAsset("/path/to/handler", new AssetOptions {
        Bundling = new BundlingOptions {
            Image = DockerImage.FromBuild("/path/to/dir/with/DockerFile", new DockerBuildOptions {
                BuildArgs = new Dictionary<string, string> {
                    { "ARG1", "value1" }
                }
            }),
            Command = new [] { "my", "cool", "command" }
        }
    }),
    Runtime = Runtime.PYTHON_3_9,
    Handler = "index.handler"
});
go
lambda.NewFunction(this, jsii.String("Function"), &FunctionProps{
	Code: lambda.Code_FromAsset(jsii.String("/path/to/handler"), &AssetOptions{
		Bundling: &BundlingOptions{
			Image: awscdk.DockerImage_FromBuild(jsii.String("/path/to/dir/with/DockerFile"), &DockerBuildOptions{
				BuildArgs: map[string]*string{
					"ARG1": jsii.String("value1"),
				},
			}),
			Command: []*string{
				jsii.String("my"),
				jsii.String("cool"),
				jsii.String("command"),
			},
		},
	}),
	Runtime: lambda.Runtime_PYTHON_3_9(),
	Handler: jsii.String("index.handler"),
})

Language-specific APIs ​

Language-specific higher level constructs are provided in separate modules:

Code Signing ​

Code 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, see Configuring code signing for AWS Lambda. The following code configures a function with code signing.

Please note the code will not be automatically signed before deployment. To ensure your code is properly signed, you'll need to conduct the code signing process either through the AWS CLI (Command Line Interface) start-signing-job or by accessing the AWS Signer console.

ts
import * as signer from 'aws-cdk-lib/aws-signer';

const signingProfile = new signer.SigningProfile(this, 'SigningProfile', {
  platform: signer.Platform.AWS_LAMBDA_SHA384_ECDSA,
});

const codeSigningConfig = new lambda.CodeSigningConfig(this, 'CodeSigningConfig', {
  signingProfiles: [signingProfile],
});

new lambda.Function(this, 'Function', {
  codeSigningConfig,
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});
python
import aws_cdk.aws_signer as signer


signing_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_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)
java
import software.amazon.awscdk.services.signer.*;


SigningProfile signingProfile = SigningProfile.Builder.create(this, "SigningProfile")
        .platform(Platform.AWS_LAMBDA_SHA384_ECDSA)
        .build();

CodeSigningConfig codeSigningConfig = CodeSigningConfig.Builder.create(this, "CodeSigningConfig")
        .signingProfiles(List.of(signingProfile))
        .build();

Function.Builder.create(this, "Function")
        .codeSigningConfig(codeSigningConfig)
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .build();
csharp
using Amazon.CDK.AWS.Signer;


var signingProfile = new SigningProfile(this, "SigningProfile", new SigningProfileProps {
    Platform = Platform.AWS_LAMBDA_SHA384_ECDSA
});

var codeSigningConfig = new CodeSigningConfig(this, "CodeSigningConfig", new CodeSigningConfigProps {
    SigningProfiles = new [] { signingProfile }
});

new Function(this, "Function", new FunctionProps {
    CodeSigningConfig = codeSigningConfig,
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
go
import "github.com/aws/aws-cdk-go/awscdk"


signingProfile := signer.NewSigningProfile(this, jsii.String("SigningProfile"), &SigningProfileProps{
	Platform: signer.Platform_AWS_LAMBDA_SHA384_ECDSA(),
})

codeSigningConfig := lambda.NewCodeSigningConfig(this, jsii.String("CodeSigningConfig"), &CodeSigningConfigProps{
	SigningProfiles: []ISigningProfile{
		signingProfile,
	},
})

lambda.NewFunction(this, jsii.String("Function"), &FunctionProps{
	CodeSigningConfig: CodeSigningConfig,
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
})

Runtime updates ​

Lambda runtime management controls help reduce the risk of impact to your workloads in the rare event of a runtime version incompatibility. For more information, see Runtime management controls

ts
new lambda.Function(this, 'Lambda', {
  runtimeManagementMode: lambda.RuntimeManagementMode.AUTO,
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});
python
lambda_.Function(self, "Lambda",
    runtime_management_mode=lambda_.RuntimeManagementMode.AUTO,
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)
java
Function.Builder.create(this, "Lambda")
        .runtimeManagementMode(RuntimeManagementMode.AUTO)
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .build();
csharp
new Function(this, "Lambda", new FunctionProps {
    RuntimeManagementMode = RuntimeManagementMode.AUTO,
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
go
lambda.NewFunction(this, jsii.String("Lambda"), &FunctionProps{
	RuntimeManagementMode: lambda.RuntimeManagementMode_AUTO(),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
})

If you want to set the "Manual" setting, using the ARN of the runtime version as the argument.

ts
new lambda.Function(this, 'Lambda', {
  runtimeManagementMode: lambda.RuntimeManagementMode.manual('runtimeVersion-arn'),
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});
python
lambda_.Function(self, "Lambda",
    runtime_management_mode=lambda_.RuntimeManagementMode.manual("runtimeVersion-arn"),
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)
java
Function.Builder.create(this, "Lambda")
        .runtimeManagementMode(RuntimeManagementMode.manual("runtimeVersion-arn"))
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .build();
csharp
new Function(this, "Lambda", new FunctionProps {
    RuntimeManagementMode = RuntimeManagementMode.Manual("runtimeVersion-arn"),
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
go
lambda.NewFunction(this, jsii.String("Lambda"), &FunctionProps{
	RuntimeManagementMode: lambda.RuntimeManagementMode_Manual(jsii.String("runtimeVersion-arn")),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
})

Exclude Patterns for Assets ​

When using lambda.Code.fromAsset(path) an exclude property allows you to ignore particular files for assets by providing patterns for file paths to exclude. Note that this has no effect on Assets bundled using the bundling property.

The ignoreMode property can be used with the exclude property to specify the file paths to ignore based on the .gitignore specification or the .dockerignore specification. The default behavior is to ignore file paths based on simple glob patterns.

ts
new lambda.Function(this, 'Function', {
  code: lambda.Code.fromAsset(path.join(__dirname, 'my-python-handler'), {
    exclude: ['*.ignore'],
    ignoreMode: IgnoreMode.DOCKER, // Default is IgnoreMode.GLOB
  }),
  runtime: lambda.Runtime.PYTHON_3_9,
  handler: 'index.handler',
});
python
lambda_.Function(self, "Function",
    code=lambda_.Code.from_asset(path.join(__dirname, "my-python-handler"),
        exclude=["*.ignore"],
        ignore_mode=IgnoreMode.DOCKER
    ),
    runtime=lambda_.Runtime.PYTHON_3_9,
    handler="index.handler"
)
java
Function.Builder.create(this, "Function")
        .code(Code.fromAsset(join(__dirname, "my-python-handler"), AssetOptions.builder()
                .exclude(List.of("*.ignore"))
                .ignoreMode(IgnoreMode.DOCKER)
                .build()))
        .runtime(Runtime.PYTHON_3_9)
        .handler("index.handler")
        .build();
csharp
new Function(this, "Function", new FunctionProps {
    Code = Code.FromAsset(Join(__dirname, "my-python-handler"), new AssetOptions {
        Exclude = new [] { "*.ignore" },
        IgnoreMode = IgnoreMode.DOCKER
    }),
    Runtime = Runtime.PYTHON_3_9,
    Handler = "index.handler"
});
go
lambda.NewFunction(this, jsii.String("Function"), &FunctionProps{
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("my-python-handler")), &AssetOptions{
		Exclude: []*string{
			jsii.String("*.ignore"),
		},
		IgnoreMode: awscdk.IgnoreMode_DOCKER,
	}),
	Runtime: lambda.Runtime_PYTHON_3_9(),
	Handler: jsii.String("index.handler"),
})

You can also write to include only certain files by using a negation.

ts
new lambda.Function(this, 'Function', {
  code: lambda.Code.fromAsset(path.join(__dirname, 'my-python-handler'), {
    exclude: ['*', '!index.py'],
  }),
  runtime: lambda.Runtime.PYTHON_3_9,
  handler: 'index.handler',
});
python
lambda_.Function(self, "Function",
    code=lambda_.Code.from_asset(path.join(__dirname, "my-python-handler"),
        exclude=["*", "!index.py"]
    ),
    runtime=lambda_.Runtime.PYTHON_3_9,
    handler="index.handler"
)
java
Function.Builder.create(this, "Function")
        .code(Code.fromAsset(join(__dirname, "my-python-handler"), AssetOptions.builder()
                .exclude(List.of("*", "!index.py"))
                .build()))
        .runtime(Runtime.PYTHON_3_9)
        .handler("index.handler")
        .build();
csharp
new Function(this, "Function", new FunctionProps {
    Code = Code.FromAsset(Join(__dirname, "my-python-handler"), new AssetOptions {
        Exclude = new [] { "*", "!index.py" }
    }),
    Runtime = Runtime.PYTHON_3_9,
    Handler = "index.handler"
});
go
lambda.NewFunction(this, jsii.String("Function"), &FunctionProps{
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("my-python-handler")), &AssetOptions{
		Exclude: []*string{
			jsii.String("*"),
			jsii.String("!index.py"),
		},
	}),
	Runtime: lambda.Runtime_PYTHON_3_9(),
	Handler: jsii.String("index.handler"),
})

Types ​

NameKindSummary
AliasConstruct (L2)A new alias to a particular version of a Lambda function.
CapacityProviderConstruct (L2)A Lambda capacity provider that manages compute resources for Lambda functions.
CodeSigningConfigConstruct (L2)Defines a Code Signing Config.
DockerImageFunctionConstruct (L2)Create a lambda function where the handler is a docker image.
EventInvokeConfigConstruct (L2)Configure options for asynchronous invocation on a version or an alias.
EventSourceMappingConstruct (L2)Defines a Lambda EventSourceMapping resource.
FunctionConstruct (L2)This construct does not yet reproduce all features from the underlying resource library.
FunctionBaseConstruct (L2)
FunctionUrlConstruct (L2)Defines a Lambda function url.
LayerVersionConstruct (L2)Defines a new Lambda Layer version.
QualifiedFunctionBaseConstruct (L2)
SingletonFunctionConstruct (L2)A Lambda that will only ever be added to a stack once.
VersionConstruct (L2)Tag the current state of a Function with a Version number.
CfnAliasConstruct (L1)The AWS::Lambda::Alias resource creates an alias for a Lambda function version. Use aliases to provide clients with a function identifier that you can update to invoke a different version.
CfnCapacityProviderConstruct (L1)Creates a capacity provider that manages compute resources for Lambda functions.
CfnCodeSigningConfigConstruct (L1)Details about a Code signing configuration .
CfnEventInvokeConfigConstruct (L1)The AWS::Lambda::EventInvokeConfig resource configures options for asynchronous invocation on a version or an alias.
CfnEventSourceMappingConstruct (L1)The AWS::Lambda::EventSourceMapping resource creates a mapping between an event source and an AWS Lambda function.
CfnFunctionConstruct (L1)The AWS::Lambda::Function resource creates a Lambda function.
CfnLayerVersionConstruct (L1)The AWS::Lambda::LayerVersion resource creates a Lambda layer from a ZIP archive.
CfnLayerVersionPermissionConstruct (L1)The AWS::Lambda::LayerVersionPermission resource adds permissions to the resource-based policy of a version of an Lambda layer . Use this action to grant layer usage permission to other accounts. You can grant permission to a single account, all AWS accounts, or all accounts in an organization.
CfnMicrovmImageConstruct (L1)Resource Type definition for AWS::Lambda::MicrovmImage.
CfnNetworkConnectorConstruct (L1)Resource Type definition for AWS::Lambda::NetworkConnector.
CfnPermissionConstruct (L1)The AWS::Lambda::Permission resource grants an AWS service or another account permission to use a function.
CfnResourcePolicyConstruct (L1)Use the AWS::Lambda::ResourcePolicy resource to attach a resource-based policy to a LAM resource.
CfnUrlConstruct (L1)The AWS::Lambda::Url resource creates a function URL with the specified configuration parameters.
CfnVersionConstruct (L1)The AWS::Lambda::Version resource creates a version from the current code and configuration of a function. Use versions to create a snapshot of your function code and configuration that doesn't change.
CfnWebFunctionConstruct (L1)Resource Type definition for AWS::Lambda::WebFunction.
CfnWebFunctionEndpointConstruct (L1)Resource Type definition for AWS::Lambda::WebFunctionEndpoint.
CfnWebFunctionRevisionConstruct (L1)Resource Type definition for AWS::Lambda::WebFunctionRevision.
AdotInstrumentationConfigStructProperties for an ADOT instrumentation in Lambda.
AdotLambdaExecWrapperEnumThe wrapper script to be used for the Lambda function in order to enable auto instrumentation with ADOT.
AdotLambdaLayerGenericVersionClassThe collection of versions of the ADOT Lambda Layer for generic purpose.
AdotLambdaLayerJavaAutoInstrumentationVersionClassThe collection of versions of the ADOT Lambda Layer for Java auto-instrumentation.
AdotLambdaLayerJavaScriptSdkVersionClassThe collection of versions of the ADOT Lambda Layer for JavaScript SDK.
AdotLambdaLayerJavaSdkVersionClassThe collection of versions of the ADOT Lambda Layer for Java SDK.
AdotLambdaLayerPythonSdkVersionClassThe collection of versions of the ADOT Lambda Layer for Python SDK.
AdotLayerVersionClassAn ADOT Lambda layer version that's specific to a lambda layer type and an architecture.
AliasAttributesStruct
AliasOptionsStructOptions for lambda.Alias.
AliasPropsStructProperties for a new Lambda alias.
ApplicationLogLevelEnumLambda service automatically captures logs generated by the function code (known as application logs) and sends these logs to a default CloudWatch log group named after the Lambda function.
ArchitectureClassArchitectures supported by AWS Lambda.
AssetCodeClassLambda code from a local directory.
AssetImageCodeClassRepresents an ECR image that will be constructed from the specified asset and can be bound as Lambda code.
AssetImageCodePropsStructProperties to initialize a new AssetImage.
AutoScalingOptionsStructProperties for enabling Lambda autoscaling.
BucketOptionsStructOptional parameters for creating code using bucket.
CapacityProviderAttributesStructAttributes for importing an existing Lambda capacity provider.
CapacityProviderFunctionOptionsStructOptions for creating a function associated with a capacity provider.
CapacityProviderPropsStructProperties for creating a Lambda capacity provider.
CfnAlias.AliasRoutingConfigurationPropertyStructThe traffic-shifting configuration of a Lambda function alias.
CfnAlias.ProvisionedConcurrencyConfigurationPropertyStructA provisioned concurrency configuration for a function's alias.
CfnAlias.VersionWeightPropertyStructThe traffic-shifting configuration of a Lambda function alias.
CfnAliasPropsStructProperties for defining a CfnAlias.
CfnCapacityProvider.CapacityProviderLoggingConfigPropertyStructThe capacity provider's Amazon CloudWatch Logs configuration settings.
CfnCapacityProvider.CapacityProviderPermissionsConfigPropertyStructConfiguration that specifies the permissions required for the capacity provider to manage compute resources.
CfnCapacityProvider.CapacityProviderScalingConfigPropertyStructConfiguration that defines how the capacity provider scales compute instances based on demand and policies.
CfnCapacityProvider.CapacityProviderTelemetryConfigPropertyStructConfiguration that specifies the telemetry collection for the capacity provider.
CfnCapacityProvider.CapacityProviderVpcConfigPropertyStructVPC configuration that specifies the network settings for compute instances managed by the capacity provider.
CfnCapacityProvider.InstanceRequirementsPropertyStructSpecifications that define the characteristics and constraints for compute instances used by the capacity provider.
CfnCapacityProvider.PropagateTagsConfigPropertyStructConfiguration that defines how tags are propagated to managed resources.
CfnCapacityProvider.TargetTrackingScalingPolicyPropertyStructA scaling policy for the capacity provider that automatically adjusts capacity to maintain a target value for a specific metric.
CfnCapacityProviderPropsStructProperties for defining a CfnCapacityProvider.
CfnCodeSigningConfig.AllowedPublishersPropertyStructList of signing profiles that can sign a code package.
CfnCodeSigningConfig.CodeSigningPoliciesPropertyStructCode signing configuration policies specify the validation failure action for signature mismatch or expiry.
CfnCodeSigningConfigPropsStructProperties for defining a CfnCodeSigningConfig.
CfnEventInvokeConfig.DestinationConfigPropertyStructA configuration object that specifies the destination of an event after Lambda processes it.
CfnEventInvokeConfig.OnFailurePropertyStructA destination for events that failed processing.
CfnEventInvokeConfig.OnSuccessPropertyStructA destination for events that were processed successfully.
CfnEventInvokeConfigPropsStructProperties for defining a CfnEventInvokeConfig.
CfnEventSourceMapping.AmazonManagedKafkaEventSourceConfigPropertyStructSpecific configuration settings for an Amazon Managed Streaming for Apache Kafka (Amazon MSK) event source.
CfnEventSourceMapping.DestinationConfigPropertyStructA configuration object that specifies the destination of an event after Lambda processes it.
CfnEventSourceMapping.DocumentDBEventSourceConfigPropertyStructSpecific configuration settings for a DocumentDB event source.
CfnEventSourceMapping.EndpointsPropertyStructThe list of bootstrap servers for your Kafka brokers in the following format: "KafkaBootstrapServers": ["abc.xyz.com:xxxx","abc2.xyz.com:xxxx"] .
CfnEventSourceMapping.FilterCriteriaPropertyStructAn object that contains the filters for an event source.
CfnEventSourceMapping.FilterPropertyStructA structure within a FilterCriteria object that defines an event filtering pattern.
CfnEventSourceMapping.LoggingConfigPropertyStructThe function's Amazon CloudWatch Logs configuration settings.
CfnEventSourceMapping.MetricsConfigPropertyStructThe metrics configuration for your event source.
CfnEventSourceMapping.OnFailurePropertyStructA destination for events that failed processing.
CfnEventSourceMapping.ProvisionedPollerConfigPropertyStructThe provisioned mode configuration for the event source. Use Provisioned Mode to customize the minimum and maximum number of event pollers for your event source.
CfnEventSourceMapping.ScalingConfigPropertyStruct(Amazon SQS only) The scaling configuration for the event source.
CfnEventSourceMapping.SchemaRegistryAccessConfigPropertyStructSpecific access configuration settings that tell Lambda how to authenticate with your schema registry.
CfnEventSourceMapping.SchemaRegistryConfigPropertyStructSpecific configuration settings for a Kafka schema registry.
CfnEventSourceMapping.SchemaValidationConfigPropertyStructSpecific schema validation configuration settings that tell Lambda the message attributes you want to validate and filter using your schema registry.
CfnEventSourceMapping.SelfManagedEventSourcePropertyStructThe self-managed Apache Kafka cluster for your event source.
CfnEventSourceMapping.SelfManagedKafkaEventSourceConfigPropertyStructSpecific configuration settings for a self-managed Apache Kafka event source.
CfnEventSourceMapping.SourceAccessConfigurationPropertyStructAn array of the authentication protocol, VPC components, or virtual host to secure and define your event source.
CfnEventSourceMappingPropsStructProperties for defining a CfnEventSourceMapping.
CfnFunction.CapacityProviderConfigPropertyStructConfiguration for the capacity provider that manages compute resources for Lambda functions.
CfnFunction.CodePropertyStructThe deployment package for a Lambda function. To deploy a function defined as a container image, you specify the location of a container image in the Amazon ECR registry. For a .zip file deployment package, you can specify the location of an object in Amazon S3. For Node.js and Python functions, you can specify the function code inline in the template.
CfnFunction.DeadLetterConfigPropertyStructThe dead-letter queue for failed asynchronous invocations.
CfnFunction.DurableConfigPropertyStructConfiguration settings for durable functions , including execution timeout and retention period for execution history.
CfnFunction.EnvironmentPropertyStructA function's environment variable settings.
CfnFunction.EphemeralStoragePropertyStructThe size of the function's /tmp directory in MB.
CfnFunction.FileSystemConfigPropertyStructDetails about the connection between a Lambda function and an Amazon EFS file system .
CfnFunction.FunctionScalingConfigPropertyStructConfiguration that defines the scaling behavior for a Lambda Managed Instances function, including the minimum and maximum number of execution environments that can be provisioned.
CfnFunction.ImageConfigPropertyStructConfiguration values that override the container image Dockerfile settings.
CfnFunction.LambdaManagedInstancesCapacityProviderConfigPropertyStructConfiguration for Lambda-managed instances used by the capacity provider.
CfnFunction.LoggingConfigPropertyStructThe function's Amazon CloudWatch Logs configuration settings.
CfnFunction.RuntimeManagementConfigPropertyStructSets the runtime management configuration for a function's version.
CfnFunction.S3FilesConfigPropertyStructSetting controls how your function accesses data from an Amazon S3 file system.
CfnFunction.SnapStartPropertyStructThe function's AWS Lambda SnapStart setting.
CfnFunction.SnapStartResponsePropertyStructThe function's SnapStart setting.
CfnFunction.TenancyConfigPropertyStructSpecifies the tenant isolation mode configuration for a Lambda function.
CfnFunction.TracingConfigPropertyStructThe function's AWS X-Ray tracing configuration. To sample and record incoming requests, set Mode to Active .
CfnFunction.VpcConfigPropertyStructThe VPC security groups and subnets that are attached to a Lambda function.
CfnFunctionPropsStructProperties for defining a CfnFunction.
CfnLayerVersion.ContentPropertyStructA ZIP archive that contains the contents of an Lambda layer .
CfnLayerVersionPermissionPropsStructProperties for defining a CfnLayerVersionPermission.
CfnLayerVersionPropsStructProperties for defining a CfnLayerVersion.
CfnMicrovmImage.CloudWatchLoggingPropertyStruct
CfnMicrovmImage.CodeArtifactPropertyStruct
CfnMicrovmImage.CpuConfigurationPropertyStruct
CfnMicrovmImage.EnvironmentVariablePropertyStruct
CfnMicrovmImage.HooksPropertyStruct
CfnMicrovmImage.LoggingPropertyStruct
CfnMicrovmImage.MicrovmHooksPropertyStruct
CfnMicrovmImage.MicrovmImageHooksPropertyStruct
CfnMicrovmImage.ResourcesPropertyStruct
CfnMicrovmImagePropsStructProperties for defining a CfnMicrovmImage.
CfnNetworkConnector.ConfigPropertyStructThe network configuration for the connector.
CfnNetworkConnector.VpcEgressConfigurationPropertyStructThe VPC egress configuration for the network connector.
CfnNetworkConnectorPropsStructProperties for defining a CfnNetworkConnector.
CfnParametersCodeClassLambda code defined using 2 CloudFormation parameters.
CfnParametersCodePropsStructConstruction properties for CfnParametersCode.
CfnPermissionPropsStructProperties for defining a CfnPermission.
CfnResourcePolicyPropsStructProperties for defining a CfnResourcePolicy.
CfnUrl.CorsPropertyStructThe Cross-Origin Resource Sharing (CORS) settings for your function URL. Use CORS to grant access to your function URL from any origin. You can also use CORS to control access for specific HTTP headers and methods in requests to your function URL.
CfnUrlPropsStructProperties for defining a CfnUrl.
CfnVersion.FunctionScalingConfigPropertyStructConfiguration that defines the scaling behavior for a Lambda Managed Instances function, including the minimum and maximum number of execution environments that can be provisioned.
CfnVersion.ProvisionedConcurrencyConfigurationPropertyStructA provisioned concurrency configuration for a function's version.
CfnVersion.RuntimePolicyPropertyStructSets the runtime management configuration for a function's version.
CfnVersionPropsStructProperties for defining a CfnVersion.
CfnWebFunctionEndpoint.RegionalEndpointPropertyStructPer-region endpoint information.
CfnWebFunctionEndpoint.RevisionWeightPropertyStructA revision routing entry.
CfnWebFunctionEndpoint.ScalingConfigPropertyStructThe scaling configuration for the endpoint.
CfnWebFunctionEndpoint.ThrottleConfigPropertyStructThe throttling configuration for the endpoint.
CfnWebFunctionEndpointPropsStructProperties for defining a CfnWebFunctionEndpoint.
CfnWebFunctionPropsStructProperties for defining a CfnWebFunction.
CfnWebFunctionRevision.BuildConfigPropertyStructThe build configuration for the revision.
CfnWebFunctionRevision.CodeConfigPropertyStructThe code configuration for the revision.
CfnWebFunctionRevision.LoggingConfigPropertyStructThe logging configuration.
CfnWebFunctionRevision.RuntimeConfigPropertyStructThe runtime configuration for the revision.
CfnWebFunctionRevision.S3ObjectPropertyStructThe S3 location of the function code.
CfnWebFunctionRevision.ServiceConfigPropertyStructThe service configuration for the revision.
CfnWebFunctionRevision.TelemetryConfigPropertyStructThe telemetry configuration.
CfnWebFunctionRevisionPropsStructProperties for defining a CfnWebFunctionRevision.
CodeClassRepresents the Lambda Handler Code.
CodeConfigStructResult of binding Code into a Function.
CodeImageConfigStructResult of the bind when an ECR image is used.
CodeSigningConfigPropsStructConstruction properties for a Code Signing Config object.
CustomCommandOptionsStructOptions for creating AssetCode with a custom command, such as running a buildfile.
DestinationConfigStructA destination configuration.
DestinationOptionsStructOptions when binding a destination to a function.
DestinationTypeEnumThe type of destination.
DirectS3ReadClassThe DirectS3Read configuration for an S3 Files filesystem mount.
DlqDestinationConfigStructA destination configuration.
DockerBuildAssetOptionsStructOptions when creating an asset from a Docker build.
DockerImageCodeClassCode property for the DockerImageFunction construct.
DockerImageFunctionPropsStructProperties to configure a new DockerImageFunction construct.
DurableConfigStructConfiguration for durable functions.
EcrImageCodeClassRepresents a Docker image in ECR that can be bound as Lambda Code.
EcrImageCodePropsStructProperties to initialize a new EcrImageCode.
EnvironmentOptionsStructEnvironment variables options.
EventInvokeConfigOptionsStructOptions to add an EventInvokeConfig to a function.
EventInvokeConfigPropsStructProperties for an EventInvokeConfig.
EventRecordFormatClassThe format target function should receive record in.
EventSourceMappingLogLevelEnumThe log level for the event source mapping poller.
EventSourceMappingOptionsStruct
EventSourceMappingPropsStructProperties for declaring a new event source mapping.
FileSystemClassRepresents the filesystem for the Lambda function.
FileSystemConfigStructFileSystem configurations for the Lambda function.
FilterCriteriaClassFilter criteria for Lambda event filtering.
FilterRuleClassFilter rules for Lambda event filtering.
FunctionAttributesStructRepresents a Lambda function defined outside of this stack.
FunctionOptionsStructNon runtime options.
FunctionPropsStruct
FunctionUrlAuthTypeEnumThe auth types for a function url.
FunctionUrlCorsOptionsStructSpecifies a cross-origin access property for a function URL.
FunctionUrlOptionsStructOptions to add a url to a Lambda function.
FunctionUrlPropsStructProperties for a FunctionUrl.
FunctionVersionUpgradeClassAspect for upgrading function versions when the provided feature flag is enabled.
HandlerClassLambda function handler.
HttpMethodEnumAll http request methods.
IAliasInterface
ICapacityProviderInterfaceRepresents a Lambda capacity provider.
ICodeSigningConfigInterfaceA Code Signing Config.
IDestinationInterfaceA Lambda destination.
IEventSourceInterfaceAn abstract class which represents an AWS Lambda event source.
IEventSourceDlqInterfaceA DLQ for an event source.
IEventSourceMappingInterfaceRepresents an event source mapping for a lambda function.
IFunctionInterface
IFunctionUrlInterfaceA Lambda function Url.
ILayerVersionInterface
InlineCodeClassLambda code from an inline string.
InstanceTypeFilterClassConfiguration for filtering instance types that a capacity provider can use.
InvokeModeEnumThe invoke modes for a Lambda function.
IScalableFunctionAttributeInterfaceInterface for scalable attributes.
ISchemaRegistryInterfaceA schema registry for an event source.
IVersionInterface
KafkaSchemaRegistryAccessConfigStructSpecific access configuration settings that tell Lambda how to authenticate with your schema registry.
KafkaSchemaRegistryAccessConfigTypeClassThe type of authentication protocol for your schema registry.
KafkaSchemaRegistryConfigStruct(Amazon MSK and self-managed Apache Kafka only) Specific configuration settings for a Kafka schema registry.
KafkaSchemaValidationAttributeClassSpecific schema validation configuration settings that tell Lambda the message attributes you want to validate and filter using your schema registry.
KafkaSchemaValidationConfigStructSpecific schema validation configuration settings that tell Lambda the message attributes you want to validate and filter using your schema registry.
LambdaInsightsVersionClassVersion of CloudWatch Lambda Insights.
LambdaRuntimePropsStruct
LatestPublishedScalingConfigStructThe scaling configuration that will be applied to the $LATEST.PUBLISHED version.
LayerVersionAttributesStructProperties necessary to import a LayerVersion.
LayerVersionOptionsStructNon runtime options.
LayerVersionPermissionStructIdentification of an account (or organization) that is allowed to access a Lambda Layer Version.
LayerVersionPropsStruct
LogFormatEnumThis field takes in 2 values either Text or JSON.
LoggingFormatEnumThis field takes in 2 values either Text or JSON.
LogRetentionRetryOptionsStructRetry options for all AWS API calls.
MetricsConfigStructConfiguration for collecting metrics from the event source.
MetricTypeEnum
ParamsAndSecretsLayerVersionClassParameters and Secrets Extension layer version.
ParamsAndSecretsLogLevelEnumLogging levels for the Parametes and Secrets Extension.
ParamsAndSecretsOptionsStructParameters and Secrets Extension configuration options.
ParamsAndSecretsVersionsEnumParameters and Secrets Extension versions.
PermissionStructRepresents a permission statement that can be added to a Lambda function's resource policy via the addPermission() method.
PropagateTagsClassConfiguration for propagating tags to managed resources created by a capacity provider.
ProvisionedPollerConfigStruct(Amazon MSK and self-managed Apache Kafka only) The provisioned mode configuration for the event source.
RecursiveLoopEnum
ResourceBindOptionsStruct
RuntimeClassLambda function runtime environment.
RuntimeFamilyEnum
RuntimeManagementModeClassSpecify the runtime update mode.
S3CodeClassLambda code from an S3 archive.
S3CodeV2ClassLambda code from an S3 archive.
S3FilesOptionsStructOptions for mounting an S3 Files filesystem.
S3ObjectStorageModeEnumHow Lambda manages the storage of your code package.
ScalingOptionsClassConfiguration options for scaling a capacity provider, including scaling mode and policies.
SchemaRegistryPropsStructProperties for schema registry configuration.
SingletonFunctionPropsStructProperties for a newly created singleton Lambda.
SnapStartConfClass
SourceAccessConfigurationStructSpecific settings like the authentication protocol or the VPC components to secure access to your event source.
SourceAccessConfigurationTypeClassThe type of authentication protocol or the VPC components for your event source's SourceAccessConfiguration.
StartingPositionEnumThe position in the DynamoDB, Kinesis or MSK stream where AWS Lambda should start reading.
SystemLogLevelEnumLambda service will automatically captures system logs about function invocation generated by the Lambda service (known as system logs) and sends these logs to a default CloudWatch log group named after the Lambda function.
TargetTrackingScalingPolicyClassA target tracking scaling policy that automatically adjusts the capacity provider's compute resources to maintain a specified target value by tracking the required CloudWatch metric.
TenancyConfigClassSpecify the tenant isolation mode for Lambda functions.
TracingEnumX-Ray Tracing Modes (https://docs.aws.amazon.com/lambda/latest/dg/API_TracingConfig.html).
UntrustedArtifactOnDeploymentEnumCode signing configuration policy for deployment validation failure.
UtilizationScalingOptionsStructOptions for enabling Lambda utilization tracking.
VersionAttributesStruct
VersionOptionsStructOptions for lambda.Version.
VersionPropsStructProperties for a new Lambda version.
VersionWeightStructA version/weight pair for routing traffic to Lambda functions.