Namespace Amazon.CDK.AWS.Lambda
AWS Lambda Construct Library
---AWS CDK v1 has reached End-of-Support on 2023-06-01.
This package is no longer being updated, and users should migrate to AWS CDK v2.
For more information on how to migrate, see the Migrating to AWS CDK v2 guide.
This construct library allows you to define AWS Lambda Functions.
var fn = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
Handler Code
The lambda.Code
class includes static convenience methods for various types of
runtime code.
The following example shows how to define a Python function and deploy the code
from the local directory my-lambda-handler
to it:
new Function(this, "MyLambda", new FunctionProps {
Code = Code.FromAsset(Join(__dirname, "my-lambda-handler")),
Handler = "index.main",
Runtime = 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.
new DockerImageFunction(this, "AssetFunction", new DockerImageFunctionProps {
Code = DockerImageCode.FromImageAsset(Join(__dirname, "docker-handler"))
});
You can also specify an image that already exists in ECR as the function handler.
using Amazon.CDK.AWS.ECR;
var repo = new Repository(this, "Repository");
new DockerImageFunction(this, "ECRFunction", new DockerImageFunctionProps {
Code = 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.
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:
var fn = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
var 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:
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_16_X,
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"));
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:
using Amazon.CDK;
using Amazon.CDK.AWS.CloudWatch;
var fn = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
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"
});
}
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 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).
Function fn;
var principal = new ServicePrincipal("my-service");
fn.GrantInvoke(principal);
// Equivalent to:
fn.AddPermission("my-service Invocation", new Permission {
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.
Function fn;
var servicePrincipal = new ServicePrincipal("my-service");
var sourceArn = "arn:aws:s3:::my-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);
// Equivalent to:
fn.AddPermission("my-service Invocation", new Permission {
Principal = servicePrincipal,
SourceArn = sourceArn,
SourceAccount = sourceAccount
});
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:
You could create a version to your lambda function using the Version
construct.
Function fn;
var version = new Version(this, "MyVersion", new 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 -
var codeVersion = "stringOrMethodToGetCodeVersion";
var fn = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
Environment = new Dictionary<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.
var stack = new Stack();
Aspects.Of(stack).Add(new FunctionVersionUpgrade(LAMBDA_RECOGNIZE_VERSION_PROPS));
When the new logic is in effect, you may rarely come across the following error:
The following properties are not recognized as version properties
. This will
occur, typically 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.
var stack = new Stack();
Aspects.Of(stack).Add(new FunctionVersionUpgrade(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.
var fn = new Function(this, "MyFunction", new FunctionProps {
CurrentVersionOptions = new VersionOptions {
RemovalPolicy = RemovalPolicy.RETAIN, // retain old versions
RetryAttempts = 1
},
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
fn.AddAlias("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()
:
// 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
});
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()
:
// 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
});
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):
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" }
}
});
Layers
The lambda.LayerVersion
class can be used to define Lambda layers and manage
granting permissions to other AWS accounts or organizations.
var layer = new LayerVersion(stack, "MyLayer", new LayerVersionProps {
Code = Code.FromAsset(Join(__dirname, "layer-code")),
CompatibleRuntimes = new [] { Runtime.NODEJS_14_X },
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_14_X,
Layers = new [] { 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:
new LayerVersion(this, "MyLayer", new LayerVersionProps {
RemovalPolicy = RemovalPolicy.RETAIN,
Code = Code.FromAsset(Join(__dirname, "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:
new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
Architecture = Architecture.ARM_64
});
Similarly, lambda layer versions can also be tagged with architectures it is compatible with.
new LayerVersion(this, "MyLayer", new LayerVersionProps {
RemovalPolicy = RemovalPolicy.RETAIN,
Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
CompatibleArchitectures = new [] { Architecture.X86_64, Architecture.ARM_64 }
});
Lambda Insights
Lambda functions can be configured to use CloudWatch Lambda Insights which provides low-level runtime metrics for a Lambda functions.
new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
InsightsVersion = 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 -
var layerArn = "arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:14";
new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
InsightsVersion = LambdaInsightsVersion.FromInsightVersionArn(layerArn)
});
If you are deploying an ARM_64 Lambda Function, you must specify a
Lambda Insights Version >= 1_0_119_0
.
new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Architecture = Architecture.ARM_64,
Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
InsightsVersion = LambdaInsightsVersion.VERSION_1_0_119_0
});
Event Rule Target
You can use an AWS Lambda function as a target for an Amazon CloudWatch event rule:
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));
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:
using Amazon.CDK.AWS.Lambda.EventSources;
using Amazon.CDK.AWS.SQS;
Function fn;
var queue = new Queue(this, "Queue");
fn.AddEventSource(new SqsEventSource(queue));
The following code adds an S3 bucket notification as an event source:
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/" } }
}));
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:
var fn = Function.FromFunctionArn(this, "Function", "arn:aws:lambda:us-east-1:123456789012:function:MyFn");
The fromFunctionAttributes()
API is available for more specific use cases:
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
});
If fromFunctionArn()
causes an error related to having to provide an account and/or region in a different construct,
and the lambda is in the same account and region as the stack you're importing it into,
you can use Function.fromFunctionName()
instead:
var fn = Function.FromFunctionName(this, "Function", "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
.
var fn = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = 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:
using Amazon.CDK.AWS.SQS;
var dlq = new Queue(this, "DLQ");
var fn = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromInline("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:
using Amazon.CDK.AWS.SNS;
var dlt = new Topic(this, "DLQ");
var fn = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromInline("// your code here"),
DeadLetterTopic = dlt
});
See the AWS documentation to learn more about AWS Lambdas and DLQs.
Lambda with X-Ray Tracing
var fn = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
Tracing = Tracing.ACTIVE
});
See the AWS documentation to learn more about AWS Lambda's X-Ray support.
Lambda with Profiling
The following code configures the lambda function with CodeGuru profiling. By default, this creates a new CodeGuru profiling group -
var fn = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.PYTHON_3_9,
Handler = "index.handler",
Code = 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.
Lambda with Reserved Concurrent Executions
var fn = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromInline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
ReservedConcurrentExecutions = 100
});
See the AWS documentation managing concurrency.
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:
using Amazon.CDK.AWS.AutoScaling;
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
});
using Amazon.CDK.AWS.ApplicationAutoScaling;
using Amazon.CDK;
using Aws.Cdk.Cx.Api;
using Amazon.CDK.AWS.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 : 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_14_X
});
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();
See the AWS documentation on autoscaling lambda functions.
Log Group
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.
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
.
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_16_X,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
Vpc = vpc
});
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.
using Amazon.CDK;
var fn = new Function(this, "MyFunction", new FunctionProps {
Runtime = Runtime.NODEJS_16_X,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler")),
EphemeralStorageSize = Size.Mebibytes(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 LogRetention
construct requires only one single lambda function for all different log groups whose
retention it seeks to manage.
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:
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"
});
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:
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"
});
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.
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_16_X,
Handler = "index.handler",
Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
Classes
Alias | A new alias to a particular version of a Lambda function. |
AliasAttributes | |
AliasOptions | Options for |
AliasProps | Properties for a new Lambda alias. |
Architecture | Architectures supported by AWS Lambda. |
AssetCode | Lambda code from a local directory. |
AssetImageCode | Represents an ECR image that will be constructed from the specified asset and can be bound as Lambda code. |
AssetImageCodeProps | Properties to initialize a new AssetImage. |
AutoScalingOptions | Properties for enabling Lambda autoscaling. |
CfnAlias | A CloudFormation |
CfnAlias.AliasRoutingConfigurationProperty | The traffic-shifting configuration of a Lambda function alias. |
CfnAlias.ProvisionedConcurrencyConfigurationProperty | A provisioned concurrency configuration for a function's alias. |
CfnAlias.VersionWeightProperty | The traffic-shifting configuration of a Lambda function alias. |
CfnAliasProps | Properties for defining a |
CfnCodeSigningConfig | A CloudFormation |
CfnCodeSigningConfig.AllowedPublishersProperty | List of signing profiles that can sign a code package. |
CfnCodeSigningConfig.CodeSigningPoliciesProperty | Code signing configuration policies specify the validation failure action for signature mismatch or expiry. |
CfnCodeSigningConfigProps | Properties for defining a |
CfnEventInvokeConfig | A CloudFormation |
CfnEventInvokeConfig.DestinationConfigProperty | A configuration object that specifies the destination of an event after Lambda processes it. |
CfnEventInvokeConfig.OnFailureProperty | A destination for events that failed processing. |
CfnEventInvokeConfig.OnSuccessProperty | A destination for events that were processed successfully. |
CfnEventInvokeConfigProps | Properties for defining a |
CfnEventSourceMapping | A CloudFormation |
CfnEventSourceMapping.AmazonManagedKafkaEventSourceConfigProperty | Specific configuration settings for an Amazon Managed Streaming for Apache Kafka (Amazon MSK) event source. |
CfnEventSourceMapping.DestinationConfigProperty | A configuration object that specifies the destination of an event after Lambda processes it. |
CfnEventSourceMapping.DocumentDBEventSourceConfigProperty | Specific configuration settings for a DocumentDB event source. |
CfnEventSourceMapping.EndpointsProperty | The list of bootstrap servers for your Kafka brokers in the following format: |
CfnEventSourceMapping.FilterCriteriaProperty | An object that contains the filters for an event source. |
CfnEventSourceMapping.FilterProperty | A structure within a |
CfnEventSourceMapping.OnFailureProperty | A destination for events that failed processing. |
CfnEventSourceMapping.ScalingConfigProperty | (Amazon SQS only) The scaling configuration for the event source. |
CfnEventSourceMapping.SelfManagedEventSourceProperty | The self-managed Apache Kafka cluster for your event source. |
CfnEventSourceMapping.SelfManagedKafkaEventSourceConfigProperty | Specific configuration settings for a self-managed Apache Kafka event source. |
CfnEventSourceMapping.SourceAccessConfigurationProperty | An array of the authentication protocol, VPC components, or virtual host to secure and define your event source. |
CfnEventSourceMappingProps | Properties for defining a |
CfnFunction | A CloudFormation |
CfnFunction.CodeProperty | The 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.DeadLetterConfigProperty | The dead-letter queue for failed asynchronous invocations. |
CfnFunction.EnvironmentProperty | A function's environment variable settings. |
CfnFunction.EphemeralStorageProperty | The size of the function's |
CfnFunction.FileSystemConfigProperty | Details about the connection between a Lambda function and an Amazon EFS file system . |
CfnFunction.ImageConfigProperty | Configuration values that override the container image Dockerfile settings. |
CfnFunction.RuntimeManagementConfigProperty | Sets the runtime management configuration for a function's version. |
CfnFunction.SnapStartProperty | The function's AWS Lambda SnapStart setting. |
CfnFunction.SnapStartResponseProperty | The function's SnapStart setting. |
CfnFunction.TracingConfigProperty | The function's AWS X-Ray tracing configuration. To sample and record incoming requests, set |
CfnFunction.VpcConfigProperty | The VPC security groups and subnets that are attached to a Lambda function. |
CfnFunctionProps | Properties for defining a |
CfnLayerVersion | A CloudFormation |
CfnLayerVersion.ContentProperty | A ZIP archive that contains the contents of an Lambda layer . |
CfnLayerVersionPermission | A CloudFormation |
CfnLayerVersionPermissionProps | Properties for defining a |
CfnLayerVersionProps | Properties for defining a |
CfnParametersCode | Lambda code defined using 2 CloudFormation parameters. |
CfnParametersCodeProps | Construction properties for {@link CfnParametersCode}. |
CfnPermission | A CloudFormation |
CfnPermissionProps | Properties for defining a |
CfnUrl | A CloudFormation |
CfnUrl.CorsProperty | The 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. |
CfnUrlProps | Properties for defining a |
CfnVersion | A CloudFormation |
CfnVersion.ProvisionedConcurrencyConfigurationProperty | A provisioned concurrency configuration for a function's version. |
CfnVersionProps | Properties for defining a |
Code | Represents the Lambda Handler Code. |
CodeConfig | Result of binding |
CodeImageConfig | Result of the bind when an ECR image is used. |
CodeSigningConfig | Defines a Code Signing Config. |
CodeSigningConfigProps | Construction properties for a Code Signing Config object. |
DestinationConfig | A destination configuration. |
DestinationOptions | Options when binding a destination to a function. |
DestinationType | The type of destination. |
DlqDestinationConfig | A destination configuration. |
DockerBuildAssetOptions | Options when creating an asset from a Docker build. |
DockerImageCode | Code property for the DockerImageFunction construct. |
DockerImageFunction | Create a lambda function where the handler is a docker image. |
DockerImageFunctionProps | Properties to configure a new DockerImageFunction construct. |
EcrImageCode | Represents a Docker image in ECR that can be bound as Lambda Code. |
EcrImageCodeProps | Properties to initialize a new EcrImageCode. |
EnvironmentOptions | Environment variables options. |
EventInvokeConfig | Configure options for asynchronous invocation on a version or an alias. |
EventInvokeConfigOptions | Options to add an EventInvokeConfig to a function. |
EventInvokeConfigProps | Properties for an EventInvokeConfig. |
EventSourceMapping | Defines a Lambda EventSourceMapping resource. |
EventSourceMappingOptions | |
EventSourceMappingProps | Properties for declaring a new event source mapping. |
FileSystem | Represents the filesystem for the Lambda function. |
FileSystemConfig | FileSystem configurations for the Lambda function. |
Function | Deploys a file from inside the construct library as a function. |
FunctionAttributes | Represents a Lambda function defined outside of this stack. |
FunctionBase | |
FunctionOptions | Non runtime options. |
FunctionProps | |
FunctionUrl | Defines a Lambda function url. |
FunctionUrlAuthType | The auth types for a function url. |
FunctionUrlCorsOptions | Specifies a cross-origin access property for a function URL. |
FunctionUrlOptions | Options to add a url to a Lambda function. |
FunctionUrlProps | Properties for a FunctionUrl. |
FunctionVersionUpgrade | Aspect for upgrading function versions when the feature flag provided feature flag present. |
Handler | Lambda function handler. |
HttpMethod | All http request methods. |
InlineCode | Lambda code from an inline string (limited to 4KiB). |
LambdaInsightsVersion | Version of CloudWatch Lambda Insights. |
LambdaRuntimeProps | |
LayerVersion | Defines a new Lambda Layer version. |
LayerVersionAttributes | Properties necessary to import a LayerVersion. |
LayerVersionOptions | Non runtime options. |
LayerVersionPermission | Identification of an account (or organization) that is allowed to access a Lambda Layer Version. |
LayerVersionProps | |
LogRetention | (deprecated) Creates a custom resource to control the retention policy of a CloudWatch Logs log group. |
LogRetentionProps | (deprecated) Construction properties for a LogRetention. |
LogRetentionRetryOptions | Retry options for all AWS API calls. |
Permission | Represents a permission statement that can be added to a Lambda function's resource policy via the |
QualifiedFunctionBase | |
ResourceBindOptions | |
Runtime | Lambda function runtime environment. |
RuntimeFamily | |
S3Code | Lambda code from an S3 archive. |
SingletonFunction | A Lambda that will only ever be added to a stack once. |
SingletonFunctionProps | Properties for a newly created singleton Lambda. |
SourceAccessConfiguration | Specific settings like the authentication protocol or the VPC components to secure access to your event source. |
SourceAccessConfigurationType | The type of authentication protocol or the VPC components for your event source's SourceAccessConfiguration. |
StartingPosition | The position in the DynamoDB, Kinesis or MSK stream where AWS Lambda should start reading. |
Tracing | X-Ray Tracing Modes (https://docs.aws.amazon.com/lambda/latest/dg/API_TracingConfig.html). |
UntrustedArtifactOnDeployment | Code signing configuration policy for deployment validation failure. |
UtilizationScalingOptions | Options for enabling Lambda utilization tracking. |
Version_ | Tag the current state of a Function with a Version number. |
VersionAttributes | |
VersionOptions | Options for |
VersionProps | Properties for a new Lambda version. |
VersionWeight | A version/weight pair for routing traffic to Lambda functions. |
Interfaces
CfnAlias.IAliasRoutingConfigurationProperty | The traffic-shifting configuration of a Lambda function alias. |
CfnAlias.IProvisionedConcurrencyConfigurationProperty | A provisioned concurrency configuration for a function's alias. |
CfnAlias.IVersionWeightProperty | The traffic-shifting configuration of a Lambda function alias. |
CfnCodeSigningConfig.IAllowedPublishersProperty | List of signing profiles that can sign a code package. |
CfnCodeSigningConfig.ICodeSigningPoliciesProperty | Code signing configuration policies specify the validation failure action for signature mismatch or expiry. |
CfnEventInvokeConfig.IDestinationConfigProperty | A configuration object that specifies the destination of an event after Lambda processes it. |
CfnEventInvokeConfig.IOnFailureProperty | A destination for events that failed processing. |
CfnEventInvokeConfig.IOnSuccessProperty | A destination for events that were processed successfully. |
CfnEventSourceMapping.IAmazonManagedKafkaEventSourceConfigProperty | Specific configuration settings for an Amazon Managed Streaming for Apache Kafka (Amazon MSK) event source. |
CfnEventSourceMapping.IDestinationConfigProperty | A configuration object that specifies the destination of an event after Lambda processes it. |
CfnEventSourceMapping.IDocumentDBEventSourceConfigProperty | Specific configuration settings for a DocumentDB event source. |
CfnEventSourceMapping.IEndpointsProperty | The list of bootstrap servers for your Kafka brokers in the following format: |
CfnEventSourceMapping.IFilterCriteriaProperty | An object that contains the filters for an event source. |
CfnEventSourceMapping.IFilterProperty | A structure within a |
CfnEventSourceMapping.IOnFailureProperty | A destination for events that failed processing. |
CfnEventSourceMapping.IScalingConfigProperty | (Amazon SQS only) The scaling configuration for the event source. |
CfnEventSourceMapping.ISelfManagedEventSourceProperty | The self-managed Apache Kafka cluster for your event source. |
CfnEventSourceMapping.ISelfManagedKafkaEventSourceConfigProperty | Specific configuration settings for a self-managed Apache Kafka event source. |
CfnEventSourceMapping.ISourceAccessConfigurationProperty | An array of the authentication protocol, VPC components, or virtual host to secure and define your event source. |
CfnFunction.ICodeProperty | The 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.IDeadLetterConfigProperty | The dead-letter queue for failed asynchronous invocations. |
CfnFunction.IEnvironmentProperty | A function's environment variable settings. |
CfnFunction.IEphemeralStorageProperty | The size of the function's |
CfnFunction.IFileSystemConfigProperty | Details about the connection between a Lambda function and an Amazon EFS file system . |
CfnFunction.IImageConfigProperty | Configuration values that override the container image Dockerfile settings. |
CfnFunction.IRuntimeManagementConfigProperty | Sets the runtime management configuration for a function's version. |
CfnFunction.ISnapStartProperty | The function's AWS Lambda SnapStart setting. |
CfnFunction.ISnapStartResponseProperty | The function's SnapStart setting. |
CfnFunction.ITracingConfigProperty | The function's AWS X-Ray tracing configuration. To sample and record incoming requests, set |
CfnFunction.IVpcConfigProperty | The VPC security groups and subnets that are attached to a Lambda function. |
CfnLayerVersion.IContentProperty | A ZIP archive that contains the contents of an Lambda layer . |
CfnUrl.ICorsProperty | The 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. |
CfnVersion.IProvisionedConcurrencyConfigurationProperty | A provisioned concurrency configuration for a function's version. |
IAlias | |
IAliasAttributes | |
IAliasOptions | Options for |
IAliasProps | Properties for a new Lambda alias. |
IAssetImageCodeProps | Properties to initialize a new AssetImage. |
IAutoScalingOptions | Properties for enabling Lambda autoscaling. |
ICfnAliasProps | Properties for defining a |
ICfnCodeSigningConfigProps | Properties for defining a |
ICfnEventInvokeConfigProps | Properties for defining a |
ICfnEventSourceMappingProps | Properties for defining a |
ICfnFunctionProps | Properties for defining a |
ICfnLayerVersionPermissionProps | Properties for defining a |
ICfnLayerVersionProps | Properties for defining a |
ICfnParametersCodeProps | Construction properties for {@link CfnParametersCode}. |
ICfnPermissionProps | Properties for defining a |
ICfnUrlProps | Properties for defining a |
ICfnVersionProps | Properties for defining a |
ICodeConfig | Result of binding |
ICodeImageConfig | Result of the bind when an ECR image is used. |
ICodeSigningConfig | A Code Signing Config. |
ICodeSigningConfigProps | Construction properties for a Code Signing Config object. |
IDestination | A Lambda destination. |
IDestinationConfig | A destination configuration. |
IDestinationOptions | Options when binding a destination to a function. |
IDlqDestinationConfig | A destination configuration. |
IDockerBuildAssetOptions | Options when creating an asset from a Docker build. |
IDockerImageFunctionProps | Properties to configure a new DockerImageFunction construct. |
IEcrImageCodeProps | Properties to initialize a new EcrImageCode. |
IEnvironmentOptions | Environment variables options. |
IEventInvokeConfigOptions | Options to add an EventInvokeConfig to a function. |
IEventInvokeConfigProps | Properties for an EventInvokeConfig. |
IEventSource | An abstract class which represents an AWS Lambda event source. |
IEventSourceDlq | A DLQ for an event source. |
IEventSourceMapping | Represents an event source mapping for a lambda function. |
IEventSourceMappingOptions | |
IEventSourceMappingProps | Properties for declaring a new event source mapping. |
IFileSystemConfig | FileSystem configurations for the Lambda function. |
IFunction | |
IFunctionAttributes | Represents a Lambda function defined outside of this stack. |
IFunctionOptions | Non runtime options. |
IFunctionProps | |
IFunctionUrl | A Lambda function Url. |
IFunctionUrlCorsOptions | Specifies a cross-origin access property for a function URL. |
IFunctionUrlOptions | Options to add a url to a Lambda function. |
IFunctionUrlProps | Properties for a FunctionUrl. |
ILambdaRuntimeProps | |
ILayerVersion | |
ILayerVersionAttributes | Properties necessary to import a LayerVersion. |
ILayerVersionOptions | Non runtime options. |
ILayerVersionPermission | Identification of an account (or organization) that is allowed to access a Lambda Layer Version. |
ILayerVersionProps | |
ILogRetentionProps | (deprecated) Construction properties for a LogRetention. |
ILogRetentionRetryOptions | Retry options for all AWS API calls. |
IPermission | Represents a permission statement that can be added to a Lambda function's resource policy via the |
IResourceBindOptions | |
IScalableFunctionAttribute | Interface for scalable attributes. |
ISingletonFunctionProps | Properties for a newly created singleton Lambda. |
ISourceAccessConfiguration | Specific settings like the authentication protocol or the VPC components to secure access to your event source. |
IUtilizationScalingOptions | Options for enabling Lambda utilization tracking. |
IVersion | |
IVersionAttributes | |
IVersionOptions | Options for |
IVersionProps | Properties for a new Lambda version. |
IVersionWeight | A version/weight pair for routing traffic to Lambda functions. |