Metadata-Version: 2.1
Name: aws-cdk.aws-lambda
Version: 1.94.0
Summary: The CDK Construct Library for AWS::Lambda
Home-page: https://github.com/aws/aws-cdk
Author: Amazon Web Services
License: Apache-2.0
Project-URL: Source, https://github.com/aws/aws-cdk.git
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: JavaScript
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Typing :: Typed
Classifier: Development Status :: 5 - Production/Stable
Classifier: License :: OSI Approved
Classifier: Framework :: AWS CDK
Classifier: Framework :: AWS CDK :: 1
Requires-Python: >=3.6
Description-Content-Type: text/markdown
Requires-Dist: aws-cdk.aws-applicationautoscaling (==1.94.0)
Requires-Dist: aws-cdk.aws-cloudwatch (==1.94.0)
Requires-Dist: aws-cdk.aws-codeguruprofiler (==1.94.0)
Requires-Dist: aws-cdk.aws-ec2 (==1.94.0)
Requires-Dist: aws-cdk.aws-ecr-assets (==1.94.0)
Requires-Dist: aws-cdk.aws-ecr (==1.94.0)
Requires-Dist: aws-cdk.aws-efs (==1.94.0)
Requires-Dist: aws-cdk.aws-events (==1.94.0)
Requires-Dist: aws-cdk.aws-iam (==1.94.0)
Requires-Dist: aws-cdk.aws-kms (==1.94.0)
Requires-Dist: aws-cdk.aws-logs (==1.94.0)
Requires-Dist: aws-cdk.aws-s3-assets (==1.94.0)
Requires-Dist: aws-cdk.aws-s3 (==1.94.0)
Requires-Dist: aws-cdk.aws-signer (==1.94.0)
Requires-Dist: aws-cdk.aws-sqs (==1.94.0)
Requires-Dist: aws-cdk.core (==1.94.0)
Requires-Dist: aws-cdk.cx-api (==1.94.0)
Requires-Dist: constructs (<4.0.0,>=3.2.0)
Requires-Dist: jsii (<2.0.0,>=1.24.0)
Requires-Dist: publication (>=0.0.3)

# AWS Lambda Construct Library

<!--BEGIN STABILITY BANNER-->---


![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)

![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)

---
<!--END STABILITY BANNER-->

This construct library allows you to define AWS Lambda Functions.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_lambda as lambda_
import path as path

fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_12_X,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)
```

## Handler Code

The `lambda.Code` class includes static convenience methods for various types of
runtime code.

* `lambda.Code.fromBucket(bucket, key[, objectVersion])` - specify an S3 object
  that contains the archive of your runtime code.
* `lambda.Code.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](#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:

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
lambda_.Function(self, "MyLambda",
    code=lambda_.Code.from_asset(path.join(__dirname, "my-lambda-handler")),
    handler="index.main",
    runtime=lambda_.Runtime.PYTHON_3_6
)
```

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.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
lambda_.DockerImageFunction(self, "AssetFunction",
    code=lambda_.DockerImageCode.from_image_asset(path.join(__dirname, "docker-handler"))
)
```

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

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_ecr as ecr
repo = ecr.Repository(self, "Repository")

lambda_.DockerImageFunction(self, "ECRFunction",
    code=lambda_.DockerImageCode.from_ecr(repo)
)
```

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

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_12_X,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),

    fn=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:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_12_X,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler")),
    role=my_role
)

my_role.add_managed_policy(ManagedPolicy.from_aws_managed_policy_name("service-role/AWSLambdaBasicExecutionRole"))
my_role.add_managed_policy(ManagedPolicy.from_aws_managed_policy_name("service-role/AWSLambdaVPCAccessExecutionRole"))
```

## Versions and Aliases

You can use
[versions](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html)
to manage the deployment of your AWS Lambda functions. For example, you can
publish a new version of a function for beta testing without affecting users of
the stable production version.

The function version includes the following information:

* The function code and all associated dependencies.
* The Lambda runtime that executes the function.
* All of the function settings, including the environment variables.
* A unique Amazon Resource Name (ARN) to identify this version of the function.

You can define one or more
[aliases](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html)
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 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.
>
> An alternative to defining a `lambda.Version` 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.
>
> ```python
> # Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
> code_version = "stringOrMethodToGetCodeVersion"
> fn = lambda_.Function(self, "MyFunction",
>     environment={
>         "CodeVersionString": code_version
>     }
> )
> ```

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.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
fn = lambda_.Function(self, "MyFunction",
    current_version_options={
        "removal_policy": RemovalPolicy.RETAIN, # retain old versions
        "retry_attempts": 1
    }
)

fn.current_version.add_alias("live")
```

> NOTE: The `fn.latestVersion` property returns a `lambda.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 use `lambda.currentVersion`.

## Layers

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

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
layer = lambda_.LayerVersion(stack, "MyLayer",
    code=lambda_.Code.from_asset(path.join(__dirname, "layer-code")),
    compatible_runtimes=[lambda_.Runtime.NODEJS_10_X],
    license="Apache-2.0",
    description="A layer to test the L2 construct"
)

# To grant usage by other AWS accounts
layer.add_permission("remote-account-grant", account_id=aws_account_id)

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

lambda_.Function(stack, "MyLayeredLambda",
    code=lambda_.InlineCode("foo"),
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_10_X,
    layers=[layer]
)
```

By default, updating a layer creates a new layer version, and CloudFormation will delete the old version as part of the stack update.

Alternatively, a removal policy can be used to retain the old version:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
from aws_cdk.aws_lambda import LayerVersion
LayerVersion(self, "MyLayer",
    removal_policy=RemovalPolicy.RETAIN
)
```

## Event Rule Target

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

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_events_targets as targets
rule.add_target(targets.LambdaFunction(my_function))
```

## Event Sources

AWS Lambda supports a [variety of event sources](https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html).

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:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
from aws_cdk.aws_lambda_event_sources import SqsEventSource
fn.add_event_source(SqsEventSource(queue))
```

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

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
from aws_cdk.aws_lambda_event_sources import S3EventSource
fn.add_event_source(S3EventSource(bucket,
    events=[s3.EventType.OBJECT_CREATED, s3.EventType.OBJECT_DELETED],
    filters=[NotificationKeyFilter(prefix="subdir/")]
))
```

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

## Lambda with DLQ

A dead-letter queue can be automatically created for a Lambda function by
setting the `deadLetterQueueEnabled: true` configuration.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_lambda as lambda_

fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_12_X,
    handler="index.handler",
    code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    dead_letter_queue_enabled=True
)
```

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

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_lambda as lambda_
import aws_cdk.aws_sqs as sqs

dlq = sqs.Queue(self, "DLQ")
fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_12_X,
    handler="index.handler",
    code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    dead_letter_queue=dlq
)
```

See [the AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/dlq.html)
to learn more about AWS Lambdas and DLQs.

## Lambda with X-Ray Tracing

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_lambda as lambda_

fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_12_X,
    handler="index.handler",
    code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    tracing=lambda_.Tracing.ACTIVE
)
```

See [the AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html)
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 -

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_lambda as lambda_

fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.PYTHON_3_6,
    handler="index.handler",
    code=lambda_.Code.from_asset("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](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/setting-up-lambda.html)
to learn more about AWS Lambda's Profiling support.

## Lambda with Reserved Concurrent Executions

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_lambda as lambda_

fn = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_12_X,
    handler="index.handler",
    code=lambda_.Code.from_inline("exports.handler = function(event, ctx, cb) { return cb(null, \"hi\"); }"),
    reserved_concurrent_executions=100
)
```

See [the AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/concurrent-executions.html)
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:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
alias = lambda_.Alias(stack, "Alias",
    alias_name="prod",
    version=version
)

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

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

# Configure Scheduled Scaling
as.scale_on_schedule("ScaleUpInTheMorning",
    schedule=appscaling.Schedule.cron(hour="8", minute="0"),
    min_capacity=20
)
```

```python
# Example automatically generated. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_applicationautoscaling as appscaling
import aws_cdk.core as cdk
import ...lib as lambda_

#
# Stack verification steps:
# aws application-autoscaling describe-scalable-targets --service-namespace lambda --resource-ids function:<function name>:prod
# has a minCapacity of 3 and maxCapacity of 50
#
class TestStack(cdk.Stack):
    def __init__(self, scope, id):
        super().__init__(scope, id)

        fn = lambda_.Function(self, "MyLambda",
            code=lambda_.InlineCode("exports.handler = async () => { console.log('hello world'); };"),
            handler="index.handler",
            runtime=lambda_.Runtime.NODEJS_10_X
        )

        version = fn.add_version("1", undefined, "integ-test")

        alias = lambda_.Alias(self, "Alias",
            alias_name="prod",
            version=version
        )

        scaling_target = alias.add_auto_scaling(min_capacity=3, max_capacity=50)

        scaling_target.scale_on_utilization(
            utilization_target=0.5
        )

        scaling_target.scale_on_schedule("ScaleUpInTheMorning",
            schedule=appscaling.Schedule.cron(hour="8", minute="0"),
            min_capacity=20
        )

        scaling_target.scale_on_schedule("ScaleDownAtNight",
            schedule=appscaling.Schedule.cron(hour="20", minute="0"),
            max_capacity=20
        )

        cdk.CfnOutput(self, "FunctionName",
            value=fn.function_name
        )

app = cdk.App()

TestStack(app, "aws-lambda-autoscaling")

app.synth()
```

See [the AWS documentation](https://docs.aws.amazon.com/lambda/latest/dg/invocation-scaling.html) 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](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html) 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`.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# create a new Amazon EFS filesystem
file_system = efs.FileSystem(stack, "Efs", vpc=vpc)

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

fn = lambda_.Function(stack, "MyLambda",
    code=code,
    handler=handler,
    runtime=runtime,
    vpc=vpc,
    # mount the access point to /mnt/msg in the lambda runtime environment
    filesystem=lambda_.FileSystem.from_efs_access_point(access_point, "/mnt/msg")
)
```

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

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
lambda_.Function(self, "Function",
    code=lambda_.Code.from_asset(path.join(__dirname, "my-python-handler"),
        bundling={
            "image": lambda_.Runtime.PYTHON_3_6.bundling_docker_image,
            "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](https://github.com/awslabs/aws-sam-cli) build image.

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

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.core as cdk

lambda_.Function(self, "Function",
    code=lambda_.Code.from_asset("/path/to/handler",
        bundling={
            "image": cdk.DockerImage.from_build("/path/to/dir/with/DockerFile",
                build_args={
                    "ARG1": "value1"
                }
            ),
            "command": ["my", "cool", "command"]
        }
    )
)
```

## Language-specific APIs

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

* `@aws-cdk/aws-lambda-nodejs`: [Github](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/aws-lambda-nodejs) & [CDK Docs](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-lambda-nodejs-readme.html)
* `@aws-cdk/aws-lambda-python`: [Github](https://github.com/aws/aws-cdk/tree/master/packages/%40aws-cdk/aws-lambda-python) & [CDK Docs](https://docs.aws.amazon.com/cdk/api/latest/docs/aws-lambda-python-readme.html)

## 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](https://docs.aws.amazon.com/lambda/latest/dg/configuration-codesigning.html).
The following code configures a function with code signing.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_signer as signer

signer_profile = signer.SigningProfile(self, "SigningProfile",
    platform=Platform.AWS_LAMBDA_SHA384_ECDSA
)

code_signing_config = lambda_.CodeSigningConfig(stack, "CodeSigningConfig",
    signing_profiles=[signing_profile]
)

lambda_.Function(self, "Function",
    code_signing_config=code_signing_config
)
```


