Security News
NIST Misses 2024 Deadline to Clear NVD Backlog
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
@aws-cdk/aws-lambda
Advanced tools
@aws-cdk/aws-lambda is an AWS Cloud Development Kit (CDK) module that allows you to define AWS Lambda functions and manage their configurations using code. It provides a high-level, object-oriented abstraction to define and deploy Lambda functions, making it easier to integrate with other AWS services and manage infrastructure as code.
Define a Lambda Function
This code defines a simple AWS Lambda function using the AWS CDK. The function uses Node.js 14.x runtime, specifies the handler, and points to the code directory.
const lambda = require('@aws-cdk/aws-lambda');
const cdk = require('@aws-cdk/core');
class MyStack extends cdk.Stack {
constructor(scope, id, props) {
super(scope, id, props);
new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('lambda'),
});
}
}
const app = new cdk.App();
new MyStack(app, 'MyStack');
Add Environment Variables
This code demonstrates how to add environment variables to an AWS Lambda function using the AWS CDK.
const lambda = require('@aws-cdk/aws-lambda');
const cdk = require('@aws-cdk/core');
class MyStack extends cdk.Stack {
constructor(scope, id, props) {
super(scope, id, props);
new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('lambda'),
environment: {
KEY: 'value',
},
});
}
}
const app = new cdk.App();
new MyStack(app, 'MyStack');
Add Permissions to Lambda Function
This code shows how to add permissions to an AWS Lambda function using the AWS CDK. In this example, the Lambda function is granted permission to get objects from an S3 bucket.
const lambda = require('@aws-cdk/aws-lambda');
const cdk = require('@aws-cdk/core');
const iam = require('@aws-cdk/aws-iam');
class MyStack extends cdk.Stack {
constructor(scope, id, props) {
super(scope, id, props);
const myFunction = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('lambda'),
});
myFunction.addToRolePolicy(new iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: ['arn:aws:s3:::my-bucket/*'],
}));
}
}
const app = new cdk.App();
new MyStack(app, 'MyStack');
The Serverless Framework is a popular open-source framework for building and deploying serverless applications. It supports multiple cloud providers, including AWS, and provides a rich set of features for managing serverless functions, APIs, and events. Compared to @aws-cdk/aws-lambda, Serverless Framework offers a more provider-agnostic approach and a higher-level abstraction for defining serverless applications.
The AWS SDK for JavaScript provides a set of tools for interacting with AWS services, including Lambda. While it is not specifically designed for infrastructure as code, it allows developers to programmatically manage AWS resources. Compared to @aws-cdk/aws-lambda, the AWS SDK is more low-level and requires more manual setup and configuration.
Claudia.js is a tool for deploying Node.js projects to AWS Lambda and API Gateway. It simplifies the process of setting up and managing serverless applications. Compared to @aws-cdk/aws-lambda, Claudia.js is more focused on Node.js and provides a simpler, more streamlined deployment process.
This construct library allows you to define AWS Lambda Functions.
import * as lambda from '@aws-cdk/aws-lambda';
import * as path from 'path';
const fn = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_10_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.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.
new lambda.DockerImageFunction(this, 'AssetFunction', {
code: lambda.DockerImageCode.fromImageAsset(path.join(__dirname, 'docker-handler')),
});
You can also specify an image that already exists in ECR as the function handler.
import * as ecr from '@aws-cdk/aws-ecr';
const repo = new ecr.Repository(this, 'Repository');
new lambda.DockerImageFunction(this, 'ECRFunction', {
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:
const fn = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_10_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
fn.role // the 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:
const fn = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_10_X,
handler: 'index.handler',
code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
role: myRole // user-provided role
});
myRole.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"));
myRole.addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole")); // only required if your function lives in a VPC
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 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 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.
The
currentVersion
property is only supported when your AWS Lambda function uses eitherlambda.Code.fromAsset
orlambda.Code.fromInline
. Other types of code providers (such aslambda.Code.fromBucket
) require that you define alambda.Version
resource directly since the CDK is unable to determine if their contents had changed.
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.
const fn = new lambda.Function(this, 'MyFunction', {
currentVersionOptions: {
removalPolicy: RemovalPolicy.RETAIN, // retain old versions
retryAttempts: 1 // async retry attempts
}
});
fn.currentVersion.addAlias('live');
NOTE: The
fn.latestVersion
property returns alambda.IVersion
which represents the$LATEST
pseudo-version. Most AWS services require a specific AWS Lambda version, and won't allow you to use$LATEST
. Therefore, you would normally want to uselambda.currentVersion
.
The lambda.LayerVersion
class can be used to define Lambda layers and manage
granting permissions to other AWS accounts or organizations.
You can use an AWS Lambda function as a target for an Amazon CloudWatch event rule:
import * as targets from '@aws-cdk/aws-events-targets';
rule.addTarget(new targets.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:
import { SqsEventSource } from '@aws-cdk/aws-lambda-event-sources';
fn.addEventSource(new SqsEventSource(queue));
The following code adds an S3 bucket notification as an event source:
import { S3EventSource } from '@aws-cdk/aws-lambda-event-sources';
fn.addEventSource(new S3EventSource(bucket, {
events: [ s3.EventType.OBJECT_CREATED, s3.EventType.OBJECT_DELETED ],
filters: [ { prefix: 'subdir/' } ] // optional
}));
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.
import * as lambda from '@aws-cdk/aws-lambda';
const fn = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_10_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:
import * as lambda from '@aws-cdk/aws-lambda';
import * as sqs from '@aws-cdk/aws-sqs';
const dlq = new sqs.Queue(this, 'DLQ');
const fn = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_10_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.
import * as lambda from '@aws-cdk/aws-lambda';
const fn = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_10_X,
handler: 'index.handler',
code: lambda.Code.fromInline('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.
import * as lambda from '@aws-cdk/aws-lambda';
const fn = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_10_X,
handler: 'index.handler',
code: lambda.Code.fromInline('exports.handler = function(event, ctx, cb) { return cb(null, "hi"); }'),
profiling: true
});
See the AWS documentation to learn more about AWS Lambda's Profiling support.
import * as lambda from '@aws-cdk/aws-lambda';
const fn = new lambda.Function(this, 'MyFunction', {
runtime: lambda.Runtime.NODEJS_10_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:
const alias = new lambda.Alias(stack, 'Alias', {
aliasName: 'prod',
version,
});
// 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,
});
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
.
// create a new Amazon EFS filesystem
const fileSystem = new efs.FileSystem(stack, '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(stack, 'MyLambda', {
code,
handler,
runtime,
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:
new lambda.Function(this, 'Function', {
code: lambda.Code.fromAsset(path.join(__dirname, 'my-python-handler'), {
bundling: {
image: lambda.Runtime.PYTHON_3_6.bundlingDockerImage,
command: [
'bash', '-c', `
pip install -r requirements.txt -t /asset-output &&
cp -au . /asset-output
`,
],
},
}),
runtime: lambda.Runtime.PYTHON_3_6,
handler: 'index.handler',
});
Runtimes expose a bundlingDockerImage
property that points to the AWS SAM build image.
Use cdk.BundlingDockerImage.fromRegistry(image)
to use an existing image or
cdk.BundlingDockerImage.fromAsset(path)
to build a specific image:
import * as cdk from '@aws-cdk/core';
new lambda.Function(this, 'Function', {
code: lambda.Code.fromAsset('/path/to/handler', {
bundling: {
image: cdk.BundlingDockerImage.fromAsset('/path/to/dir/with/DockerFile', {
buildArgs: {
ARG1: 'value1',
},
}),
command: ['my', 'cool', 'command'],
},
}),
// ...
});
Language-specific higher level constructs are provided in separate modules:
@aws-cdk/aws-lambda-nodejs
@aws-cdk/aws-lambda-python
1.78.0 (2020-12-11)
HttpOrigin
and LoadBalancerOrigin
changed from SSLv3 to TLSv1.2.domainName
property under DomainName
has been
renamed to name
.dnsHostName
and awsCloudMap
of VirtualNodeProps
have been replaced with the property serviceDiscovery
metricFailed
uses Average
instead of Sum
by default (#11941) (3530e8c)FAQs
The CDK Construct Library for AWS::Lambda
The npm package @aws-cdk/aws-lambda receives a total of 118,832 weekly downloads. As such, @aws-cdk/aws-lambda popularity was classified as popular.
We found that @aws-cdk/aws-lambda demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.