| Interface | Description |
|---|---|
| AliasAttributes | |
| AliasOptions |
(experimental) Options for `lambda.Alias`.
|
| AliasProps |
(experimental) Properties for a new Lambda alias.
|
| AssetImageCodeProps |
(experimental) Properties to initialize a new AssetImage.
|
| AutoScalingOptions |
(experimental) Properties for enabling Lambda autoscaling.
|
| CfnAlias.AliasRoutingConfigurationProperty | |
| CfnAlias.ProvisionedConcurrencyConfigurationProperty | |
| CfnAlias.VersionWeightProperty | |
| CfnAliasProps |
Properties for defining a `AWS::Lambda::Alias`.
|
| CfnCodeSigningConfig.AllowedPublishersProperty | |
| CfnCodeSigningConfig.CodeSigningPoliciesProperty | |
| CfnCodeSigningConfigProps |
Properties for defining a `AWS::Lambda::CodeSigningConfig`.
|
| CfnEventInvokeConfig.DestinationConfigProperty | |
| CfnEventInvokeConfig.OnFailureProperty | |
| CfnEventInvokeConfig.OnSuccessProperty | |
| CfnEventInvokeConfigProps |
Properties for defining a `AWS::Lambda::EventInvokeConfig`.
|
| CfnEventSourceMapping.DestinationConfigProperty | |
| CfnEventSourceMapping.EndpointsProperty | |
| CfnEventSourceMapping.OnFailureProperty | |
| CfnEventSourceMapping.SelfManagedEventSourceProperty | |
| CfnEventSourceMapping.SourceAccessConfigurationProperty | |
| CfnEventSourceMappingProps |
Properties for defining a `AWS::Lambda::EventSourceMapping`.
|
| CfnFunction.CodeProperty | |
| CfnFunction.DeadLetterConfigProperty | |
| CfnFunction.EnvironmentProperty | |
| CfnFunction.FileSystemConfigProperty | |
| CfnFunction.ImageConfigProperty | |
| CfnFunction.TracingConfigProperty | |
| CfnFunction.VpcConfigProperty | |
| CfnFunctionProps |
Properties for defining a `AWS::Lambda::Function`.
|
| CfnLayerVersion.ContentProperty | |
| CfnLayerVersionPermissionProps |
Properties for defining a `AWS::Lambda::LayerVersionPermission`.
|
| CfnLayerVersionProps |
Properties for defining a `AWS::Lambda::LayerVersion`.
|
| CfnParametersCodeProps |
(experimental) Construction properties for
CfnParametersCode. |
| CfnPermissionProps |
Properties for defining a `AWS::Lambda::Permission`.
|
| CfnVersion.ProvisionedConcurrencyConfigurationProperty | |
| CfnVersionProps |
Properties for defining a `AWS::Lambda::Version`.
|
| CodeConfig |
(experimental) Result of binding `Code` into a `Function`.
|
| CodeImageConfig |
(experimental) Result of the bind when an ECR image is used.
|
| CodeSigningConfigProps |
(experimental) Construction properties for a Code Signing Config object.
|
| DestinationConfig |
(experimental) A destination configuration.
|
| DestinationOptions |
(experimental) Options when binding a destination to a function.
|
| DlqDestinationConfig |
(experimental) A destination configuration.
|
| DockerBuildAssetOptions |
(experimental) Options when creating an asset from a Docker build.
|
| DockerImageFunctionProps |
(experimental) Properties to configure a new DockerImageFunction construct.
|
| EcrImageCodeProps |
(experimental) Properties to initialize a new EcrImageCode.
|
| EnvironmentOptions |
(experimental) Environment variables options.
|
| EventInvokeConfigOptions |
(experimental) Options to add an EventInvokeConfig to a function.
|
| EventInvokeConfigProps |
(experimental) Properties for an EventInvokeConfig.
|
| EventSourceMappingOptions | |
| EventSourceMappingProps |
(experimental) Properties for declaring a new event source mapping.
|
| FileSystemConfig |
(experimental) FileSystem configurations for the Lambda function.
|
| FunctionAttributes |
(experimental) Represents a Lambda function defined outside of this stack.
|
| FunctionOptions |
(experimental) Non runtime options.
|
| FunctionProps | |
| IAlias | |
| IAlias.Jsii$Default |
Internal default implementation for
IAlias. |
| ICodeSigningConfig |
(experimental) A Code Signing Config.
|
| ICodeSigningConfig.Jsii$Default |
Internal default implementation for
ICodeSigningConfig. |
| IDestination |
(experimental) A Lambda destination.
|
| IDestination.Jsii$Default |
Internal default implementation for
IDestination. |
| IEventSource |
(experimental) An abstract class which represents an AWS Lambda event source.
|
| IEventSource.Jsii$Default |
Internal default implementation for
IEventSource. |
| IEventSourceDlq |
(experimental) A DLQ for an event source.
|
| IEventSourceDlq.Jsii$Default |
Internal default implementation for
IEventSourceDlq. |
| IEventSourceMapping |
(experimental) Represents an event source mapping for a lambda function.
|
| IEventSourceMapping.Jsii$Default |
Internal default implementation for
IEventSourceMapping. |
| IFunction | |
| IFunction.Jsii$Default |
Internal default implementation for
IFunction. |
| ILayerVersion | |
| ILayerVersion.Jsii$Default |
Internal default implementation for
ILayerVersion. |
| IScalableFunctionAttribute |
(experimental) Interface for scalable attributes.
|
| IScalableFunctionAttribute.Jsii$Default |
Internal default implementation for
IScalableFunctionAttribute. |
| IVersion | |
| IVersion.Jsii$Default |
Internal default implementation for
IVersion. |
| LambdaRuntimeProps | |
| LayerVersionAttributes |
(experimental) Properties necessary to import a LayerVersion.
|
| LayerVersionOptions |
(experimental) Non runtime options.
|
| LayerVersionPermission |
(experimental) Identification of an account (or organization) that is allowed to access a Lambda Layer Version.
|
| LayerVersionProps | |
| LogRetentionRetryOptions |
(experimental) Retry options for all AWS API calls.
|
| Permission |
(experimental) Represents a permission statement that can be added to a Lambda's resource policy via the `addToResourcePolicy` method.
|
| ResourceBindOptions | |
| SingletonFunctionProps |
(experimental) Properties for a newly created singleton Lambda.
|
| SourceAccessConfiguration |
(experimental) Specific settings like the authentication protocol or the VPC components to secure access to your event source.
|
| UtilizationScalingOptions |
(experimental) Options for enabling Lambda utilization tracking.
|
| VersionAttributes | |
| VersionOptions |
(experimental) Options for `lambda.Version`.
|
| VersionProps |
(experimental) Properties for a new Lambda version.
|
| VersionWeight |
(experimental) A version/weight pair for routing traffic to Lambda functions.
|
| Enum | Description |
|---|---|
| DestinationType |
(experimental) The type of destination.
|
| RuntimeFamily | |
| StartingPosition |
(experimental) The position in the DynamoDB, Kinesis or MSK stream where AWS Lambda should start reading.
|
| Tracing |
(experimental) X-Ray Tracing Modes (https://docs.aws.amazon.com/lambda/latest/dg/API_TracingConfig.html).
|
| UntrustedArtifactOnDeployment |
(experimental) Code signing configuration policy for deployment validation failure.
|
---
This construct library allows you to define AWS Lambda Functions.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_lambda;
import path.*;
Function fn = new Function(this, "MyFunction", new FunctionProps()
.runtime(lambda.Runtime.getNODEJS_12_X())
.handler("index.handler")
.code(lambda.Code.fromAsset(path.join(__dirname, "lambda-handler"))));
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.fromInline(code) - inline the handle code as a string. This is
limited to supported runtimes and the code cannot exceed 4KiB.lambda.Code.fromAsset(path) - specify a directory or a .zip file in the local
filesystem which will be zipped and uploaded to S3 before deployment. See 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.
The following example shows how to define a Python function and deploy the code
from the local directory my-lambda-handler to it:
Example of Lambda Code from Local Assets
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.
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.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
new DockerImageFunction(this, "AssetFunction", new DockerImageFunctionProps()
.code(lambda.DockerImageCode.fromImageAsset(path.join(__dirname, "docker-handler"))));
You can also specify an image that already exists in ECR as the function handler.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_ecr;
Repository repo = new Repository(this, "Repository");
new DockerImageFunction(this, "ECRFunction", new DockerImageFunctionProps()
.code(lambda.DockerImageCode.fromEcr(repo)));
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:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
fn = Function(this, "MyFunction",
.runtime(lambda.Runtime.getNODEJS_12_X())
.handler("index.handler")
.code(lambda.Code.fromAsset(path.join(__dirname, "lambda-handler")))
.fn(fn).(.getRole()));
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:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Function fn = new Function(this, "MyFunction", new FunctionProps()
.runtime(lambda.Runtime.getNODEJS_12_X())
.handler("index.handler")
.code(lambda.Code.fromAsset(path.join(__dirname, "lambda-handler")))
.role(myRole));
myRole.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"));
myRole.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole"));
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 and other AWS accounts to modify and invoke your functions. You can also restrict permissions given to AWS services by providing a source account or ARN (representing the account and identifier of the resource that accesses the function or layer).
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_iam;
ServicePrincipal principal = new ServicePrincipal("my-service");
fn.grantInvoke(principal);
// Equivalent to:
fn.addPermission("my-service Invocation", Map.of(
"principal", principal));
For more information, see Resource-based policies in the AWS Lambda Developer Guide.
Providing an unowned principal (such as account principals, generic ARN
principals, service principals, and principals in other accounts) to a call 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.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_iam;
ServicePrincipal servicePrincipal = new ServicePrincipal("my-service");
String sourceArn = "arn:aws:s3:::my-bucket";
String sourceAccount = "111122223333";
IPrincipal servicePrincipalWithConditions = servicePrincipal.withConditions(Map.of(
"ArnLike", Map.of(
"aws:SourceArn", sourceArn),
"StringEquals", Map.of(
"aws:SourceAccount", sourceAccount)));
fn.grantInvoke(servicePrincipalWithConditions);
// Equivalent to:
fn.addPermission("my-service Invocation", Map.of(
"principal", servicePrincipal,
"sourceArn", sourceArn,
"sourceAccount", sourceAccount));
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:
You could create a version to your lambda function using the Version construct.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Function fn = new Function(this, "MyFunction", ...);
Object version = Version.Builder.create(this, "MyVersion")
.lambda(fn)
.build();
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 -
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
String codeVersion = "stringOrMethodToGetCodeVersion";
Function fn = new Function(this, "MyFunction", new FunctionProps()
.environment(Map.of(
"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.
Existing users will need to enable the feature flag
@aws-cdk/aws-lambda:recognizeVersionProps. 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. Any trivial change such as
a whitespace change in the code or a no-op environment variable will suffice.
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.
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.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Function fn = new Function(this, "MyFunction", new FunctionProps()
.currentVersionOptions(new VersionOptions()
.removalPolicy(RemovalPolicy.getRETAIN())// retain old versions
.retryAttempts(1)));
fn.currentVersion.addAlias("live");
The lambda.LayerVersion class can be used to define Lambda layers and manage
granting permissions to other AWS accounts or organizations.
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:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws.cdk.lib.aws.lambda.LayerVersion;
new LayerVersion(this, "MyLayer", new LayerVersionProps()
.removalPolicy(RemovalPolicy.getRETAIN()));
You can use an AWS Lambda function as a target for an Amazon CloudWatch event rule:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import software.amazon.awscdk.aws_events_targets; rule.addTarget(new LambdaFunction(myFunction));
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:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import aws.cdk.lib.aws.lambda.event.sources.SqsEventSource; fn.addEventSource(new SqsEventSource(queue));
The following code adds an S3 bucket notification as an event source:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws.cdk.lib.aws.lambda.event.sources.S3EventSource;
fn.addEventSource(new S3EventSource(bucket, new S3EventSourceProps()
.events(asList(s3.EventType.getOBJECT_CREATED(), s3.EventType.getOBJECT_DELETED()))
.filters(asList(new NotificationKeyFilter().prefix("subdir/")))));
See the documentation for the @aws-cdk/aws-lambda-event-sources module for more details.
A dead-letter queue can be automatically created for a Lambda function by
setting the deadLetterQueueEnabled: true configuration.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_lambda;
Function fn = new Function(this, "MyFunction", new FunctionProps()
.runtime(lambda.Runtime.getNODEJS_12_X())
.handler("index.handler")
.code(lambda.Code.fromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"))
.deadLetterQueueEnabled(true));
It is also possible to provide a dead-letter queue instead of getting a new queue created:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_lambda;
import software.amazon.awscdk.aws_sqs;
Queue dlq = new Queue(this, "DLQ");
Function fn = new Function(this, "MyFunction", new FunctionProps()
.runtime(lambda.Runtime.getNODEJS_12_X())
.handler("index.handler")
.code(lambda.Code.fromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"))
.deadLetterQueue(dlq));
See the AWS documentation to learn more about AWS Lambdas and DLQs.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_lambda;
Function fn = new Function(this, "MyFunction", new FunctionProps()
.runtime(lambda.Runtime.getNODEJS_12_X())
.handler("index.handler")
.code(lambda.Code.fromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"))
.tracing(lambda.Tracing.getACTIVE()));
See the AWS documentation to learn more about AWS Lambda's X-Ray support.
The following code configures the lambda function with CodeGuru profiling. By default, this creates a new CodeGuru profiling group -
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_lambda;
Function fn = new Function(this, "MyFunction", new FunctionProps()
.runtime(lambda.Runtime.getPYTHON_3_6())
.handler("index.handler")
.code(lambda.Code.fromAsset("lambda-handler"))
.profiling(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.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_lambda;
Function fn = new Function(this, "MyFunction", new FunctionProps()
.runtime(lambda.Runtime.getNODEJS_12_X())
.handler("index.handler")
.code(lambda.Code.fromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"))
.reservedConcurrentExecutions(100));
See the AWS documentation managing concurrency.
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:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Alias alias = new Alias(stack, "Alias", new AliasProps()
.aliasName("prod")
.version(version));
// Create AutoScaling target
IScalableFunctionAttribute 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(appscaling.Schedule.cron(Map.of("hour", "8", "minute", "0")))
.minCapacity(20));
Example of Lambda AutoScaling usage
See the AWS documentation on autoscaling lambda functions.
Lambda functions automatically create a log group with the name /aws/lambda/<function-name> upon first execution with
log data set to never expire.
The logRetention property can be used to set a different expiration period.
It is possible to obtain the function's log group as a logs.ILogGroup by calling the logGroup property of the
Function construct.
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, if either logRetention is set or logGroup property is called, 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).
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.
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.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
// create a new Amazon EFS filesystem
Object fileSystem = FileSystem.Builder.create(stack, "Efs").vpc(vpc).build();
// create a new access point from the filesystem
Object accessPoint = fileSystem.addAccessPoint("AccessPoint", Map.of(
// 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", Map.of(
"ownerUid", "1001",
"ownerGid", "1001",
"permissions", "750"),
// enforce the POSIX identity so lambda function will access with this identity
"posixUser", Map.of(
"uid", "1001",
"gid", "1001")));
Function fn = new Function(stack, "MyLambda", new FunctionProps()
.code(code)
.handler(handler)
.runtime(runtime)
.vpc(vpc)
// mount the access point to /mnt/msg in the lambda runtime environment
.filesystem(lambda.FileSystem.fromEfsAccessPoint(accessPoint, "/mnt/msg")));
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 LogRetention construct requires only one single lambda function for all different log groups whose
retention it seeks to manage.
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:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
new Function(this, "Function", new FunctionProps()
.code(lambda.Code.fromAsset(path.join(__dirname, "my-python-handler"), new AssetOptions()
.bundling(new BundlingOptions()
.image(lambda.Runtime.PYTHON_3_8.getBundlingImage())
.command(asList("bash", "-c", "pip install -r requirements.txt -t /asset-output && cp -au . /asset-output")))))
.runtime(lambda.Runtime.getPYTHON_3_8())
.handler("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:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.*;
new Function(this, "Function", new FunctionProps()
.code(lambda.Code.fromAsset("/path/to/handler", new AssetOptions()
.bundling(new BundlingOptions()
.image(cdk.DockerImage.fromBuild("/path/to/dir/with/DockerFile", new DockerBuildOptions()
.buildArgs(Map.of(
"ARG1", "value1"))))
.command(asList("my", "cool", "command"))))));
Language-specific higher level constructs are provided in separate modules:
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.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_signer;
Object signerProfile = signer.SigningProfile(this, "SigningProfile", Map.of(
"platform", Platform.getAWS_LAMBDA_SHA384_ECDSA()));
CodeSigningConfig codeSigningConfig = new CodeSigningConfig(stack, "CodeSigningConfig", new CodeSigningConfigProps()
.signingProfiles(asList(signingProfile)));
new Function(this, "Function", new FunctionProps()
.codeSigningConfig(codeSigningConfig));
Copyright © 2021. All rights reserved.