Skip to content
v2.274.0

EdgeFunction L2 construct ​

A Lambda@Edge function.

Convenience resource for requesting a Lambda function in the 'us-east-1' region for use with Lambda@Edge. Implements several restrictions enforced by Lambda@Edge.

Note that this construct requires that the 'us-east-1' region has been bootstrapped. See https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html or 'cdk bootstrap --help' for options.

Example ​

ts
// A Lambda@Edge function added to default behavior of a Distribution
// and triggered on every request
const myFunc = new cloudfront.experimental.EdgeFunction(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});

declare const myBucket: s3.Bucket;
new cloudfront.Distribution(this, 'myDist', {
  defaultBehavior: {
    origin: new origins.S3Origin(myBucket),
    edgeLambdas: [
      {
        functionVersion: myFunc.currentVersion,
        eventType: cloudfront.LambdaEdgeEventType.VIEWER_REQUEST,
      }
    ],
  },
});
python
# my_bucket: s3.Bucket
# A Lambda@Edge function added to default behavior of a Distribution
# and triggered on every request
my_func = cloudfront.experimental.EdgeFunction(self, "MyFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.Code.from_asset(path.join(__dirname, "lambda-handler"))
)
cloudfront.Distribution(self, "myDist",
    default_behavior=cloudfront.BehaviorOptions(
        origin=origins.S3Origin(my_bucket),
        edge_lambdas=[cloudfront.EdgeLambda(
            function_version=my_func.current_version,
            event_type=cloudfront.LambdaEdgeEventType.VIEWER_REQUEST
        )
        ]
    )
)
java
Bucket myBucket;
// A Lambda@Edge function added to default behavior of a Distribution
// and triggered on every request
EdgeFunction myFunc = EdgeFunction.Builder.create(this, "MyFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(Code.fromAsset(join(__dirname, "lambda-handler")))
        .build();
Distribution.Builder.create(this, "myDist")
        .defaultBehavior(BehaviorOptions.builder()
                .origin(new S3Origin(myBucket))
                .edgeLambdas(List.of(EdgeLambda.builder()
                        .functionVersion(myFunc.getCurrentVersion())
                        .eventType(LambdaEdgeEventType.VIEWER_REQUEST)
                        .build()))
                .build())
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
Bucket myBucket;
// A Lambda@Edge function added to default behavior of a Distribution
// and triggered on every request
var myFunc = new Experimental.EdgeFunction(this, "MyFunction", new EdgeFunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = Code.FromAsset(Join(__dirname, "lambda-handler"))
});
new Distribution(this, "myDist", new DistributionProps {
    DefaultBehavior = new BehaviorOptions {
        Origin = new S3Origin(myBucket),
        EdgeLambdas = new [] { new EdgeLambda {
            FunctionVersion = myFunc.CurrentVersion,
            EventType = LambdaEdgeEventType.VIEWER_REQUEST
        } }
    }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var myBucket Bucket
// A Lambda@Edge function added to default behavior of a Distribution
// and triggered on every request
myFunc := experimental.NewEdgeFunction(this, jsii.String("MyFunction"), &EdgeFunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromAsset(path.join(__dirname, jsii.String("lambda-handler"))),
})
cloudfront.NewDistribution(this, jsii.String("myDist"), &DistributionProps{
	DefaultBehavior: &BehaviorOptions{
		Origin: origins.NewS3Origin(myBucket),
		EdgeLambdas: []EdgeLambda{
			&EdgeLambda{
				FunctionVersion: myFunc.currentVersion,
				EventType: cloudfront.LambdaEdgeEventType_VIEWER_REQUEST,
			},
		},
	},
})

Initializer ​

ts
new EdgeFunction(scope: Construct, id: string, props: EdgeFunctionProps)
python
EdgeFunction(scope: Construct, id: str, props: EdgeFunctionProps)
java
new EdgeFunction(Construct scope, String id, EdgeFunctionProps props)
csharp
new EdgeFunction(Construct scope, string id, EdgeFunctionProps props)
go
NewEdgeFunction(Scope Construct, Id *string, Props EdgeFunctionProps)

Construct Props ​

adotInstrumentationoptionalAdotInstrumentationConfigadot_instrumentationoptionalAdotInstrumentationConfigadotInstrumentationoptionalAdotInstrumentationConfigAdotInstrumentationoptionalAdotInstrumentationConfigAdotInstrumentationoptionalAdotInstrumentationConfig#
Specify the configuration of AWS Distro for OpenTelemetry (ADOT) instrumentation.

Default: No ADOT instrumentation

allowAllIpv6Outboundoptionalbooleanallow_all_ipv6_outboundoptionalboolallowAllIpv6OutboundoptionalBooleanAllowAllIpv6OutboundoptionalboolAllowAllIpv6Outboundoptional*bool= false#
Whether to allow the Lambda to send all ipv6 network traffic.
notes

If set to true, there will only be a single egress rule which allows all outbound ipv6 traffic. If set to false, you must individually add traffic rules to allow the Lambda to connect to network targets using ipv6.

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

allowAllOutboundoptionalbooleanallow_all_outboundoptionalboolallowAllOutboundoptionalBooleanAllowAllOutboundoptionalboolAllowAllOutboundoptional*bool= true#
Whether to allow the Lambda to send all network traffic (except ipv6).
notes

If set to false, you must individually add traffic rules to allow the Lambda to connect to network targets.

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

allowPublicSubnetoptionalbooleanallow_public_subnetoptionalboolallowPublicSubnetoptionalBooleanAllowPublicSubnetoptionalboolAllowPublicSubnetoptional*bool= false#
Lambda Functions in a public subnet can NOT access the internet.

Use this property to acknowledge this limitation and still place the function in a public subnet.

applicationLogLeveloptionalstringapplication_log_leveloptionalstrapplicationLogLeveloptionalStringApplicationLogLeveloptionalstringApplicationLogLeveloptional*string= "INFO"deprecated#
Use `applicationLogLevelV2` as a property instead.
applicationLogLevelV2optionalApplicationLogLevelapplication_log_level_v2optionalApplicationLogLevelapplicationLogLevelV2optionalApplicationLogLevelApplicationLogLevelV2optionalApplicationLogLevelApplicationLogLevelV2optionalApplicationLogLevel= ApplicationLogLevel.INFO#
Sets the application log level for the function.
architectureoptionalArchitecturearchitectureoptionalArchitecturearchitectureoptionalArchitectureArchitectureoptionalArchitectureArchitectureoptionalArchitecture= Architecture.X86_64#
The system architectures compatible with this lambda function.
codeCodecodeCodecodeCodeCodeCodeCodeCoderequired#
The source code of your Lambda function.

You can point to a file in an Amazon Simple Storage Service (Amazon S3) bucket or specify your source code as inline text.

codeSigningConfigoptionalICodeSigningConfigRefcode_signing_configoptionalICodeSigningConfigRefcodeSigningConfigoptionalICodeSigningConfigRefCodeSigningConfigoptionalICodeSigningConfigRefCodeSigningConfigoptionalICodeSigningConfigRef#
Code signing config associated with this function.

Default: Not Sign the Code

currentVersionOptionsoptionalVersionOptionscurrent_version_optionsoptionalVersionOptionscurrentVersionOptionsoptionalVersionOptionsCurrentVersionOptionsoptionalVersionOptionsCurrentVersionOptionsoptionalVersionOptions#
Options for the `lambda.Version` resource automatically created by the `fn.currentVersion` method.

Default: default options as described in VersionOptions

deadLetterQueueoptionalIQueuedead_letter_queueoptionalIQueuedeadLetterQueueoptionalIQueueDeadLetterQueueoptionalIQueueDeadLetterQueueoptionalIQueue#
The SQS queue to use if DLQ is enabled.

Default: SQS queue with 14 day retention period if deadLetterQueueEnabled is true

If SNS topic is desired, specify deadLetterTopic property instead.

deadLetterQueueEnabledoptionalbooleandead_letter_queue_enabledoptionalbooldeadLetterQueueEnabledoptionalBooleanDeadLetterQueueEnabledoptionalboolDeadLetterQueueEnabledoptional*bool#
Enabled DLQ.

Default: false unless deadLetterQueue is set, which implies DLQ is enabled.

If deadLetterQueue is undefined, an SQS queue with default options will be defined for your Function.

deadLetterTopicoptionalITopicdead_letter_topicoptionalITopicdeadLetterTopicoptionalITopicDeadLetterTopicoptionalITopicDeadLetterTopicoptionalITopic#
The SNS topic to use as a DLQ.

Default: no SNS topic

Note that if deadLetterQueueEnabled is set to true, an SQS queue will be created rather than an SNS topic. Using an SNS topic as a DLQ requires this property to be set explicitly.

descriptionoptionalstringdescriptionoptionalstrdescriptionoptionalStringDescriptionoptionalstringDescriptionoptional*string#
A description of the function.

Default: No description.

durableConfigoptionalDurableConfigdurable_configoptionalDurableConfigdurableConfigoptionalDurableConfigDurableConfigoptionalDurableConfigDurableConfigoptionalDurableConfig#
The durable configuration for the function.

Default: No durable configuration

If durability is added to an existing function, a resource replacement will be triggered. See the 'durableConfig' section in the module README for more details.

environmentoptional{ [key: string]: string }environmentoptionaltyping.Mapping[str, str]environmentoptionalMap<String, String>EnvironmentoptionalIDictionary<string, string>Environmentoptional*map[string]*string#
Key-value pairs that Lambda caches and makes available for your Lambda functions.

Default: No environment variables.

Use environment variables to apply configuration changes, such as test and production environment configurations, without changing your Lambda function source code.

environmentEncryptionoptionalIKeyRefenvironment_encryptionoptionalIKeyRefenvironmentEncryptionoptionalIKeyRefEnvironmentEncryptionoptionalIKeyRefEnvironmentEncryptionoptionalIKeyRef#
The AWS KMS key that's used to encrypt your function's environment variables.

Default: AWS Lambda creates and uses an AWS managed customer master key (CMK).

ephemeralStorageSizeoptionalSizeephemeral_storage_sizeoptionalSizeephemeralStorageSizeoptionalSizeEphemeralStorageSizeoptionalSizeEphemeralStorageSizeoptionalSize#
The size of the function’s /tmp directory in MiB.

Default: 512 MiB

eventsoptionalIEventSource[]eventsoptionaltyping.List[IEventSource]eventsoptionalList<IEventSource>EventsoptionalIEventSource[]Eventsoptional*[]IEventSource#
Event sources for this function.

Default: No event sources.

You can also add event sources using addEventSource.

filesystemoptionalFileSystemfilesystemoptionalFileSystemfilesystemoptionalFileSystemFilesystemoptionalFileSystemFilesystemoptionalFileSystem#
The filesystem configuration for the lambda function.

Default: will not mount any filesystem

functionNameoptionalstringfunction_nameoptionalstrfunctionNameoptionalStringFunctionNameoptionalstringFunctionNameoptional*string#
A name for the function.

Default: AWS CloudFormation generates a unique physical ID and uses that ID for the function's name. For more information, see Name Type.

handlerstringhandlerstrhandlerStringHandlerstringHandler*stringrequired#
The name of the method within your code that Lambda calls to execute your function.
notes

The format includes the file name. It can also include namespaces and other qualifiers, depending on the runtime. For more information, see https://docs.aws.amazon.com/lambda/latest/dg/foundation-progmodel.html.

Use Handler.FROM_IMAGE when defining a function from a Docker image.

NOTE: If you specify your source code as inline text by specifying the ZipFile property within the Code property, specify index.function_name as the handler.

initialPolicyoptionalPolicyStatement[]initial_policyoptionaltyping.List[PolicyStatement]initialPolicyoptionalList<PolicyStatement>InitialPolicyoptionalPolicyStatement[]InitialPolicyoptional*[]PolicyStatement#
Initial policy statements to add to the created Lambda Role.

Default: No policy statements are added to the created Lambda role.

You can call addToRolePolicy to the created lambda to add statements post creation.

insightsVersionoptionalLambdaInsightsVersioninsights_versionoptionalLambdaInsightsVersioninsightsVersionoptionalLambdaInsightsVersionInsightsVersionoptionalLambdaInsightsVersionInsightsVersionoptionalLambdaInsightsVersion#
Specify the version of CloudWatch Lambda insights to use for monitoring.

Default: No Lambda Insights

ipv6AllowedForDualStackoptionalbooleanipv6_allowed_for_dual_stackoptionalboolipv6AllowedForDualStackoptionalBooleanIpv6AllowedForDualStackoptionalboolIpv6AllowedForDualStackoptional*bool= false#
Allows outbound IPv6 traffic on VPC functions that are connected to dual-stack subnets.

Only used if 'vpc' is supplied.

layersoptionalILayerVersion[]layersoptionaltyping.List[ILayerVersion]layersoptionalList<ILayerVersion>LayersoptionalILayerVersion[]Layersoptional*[]ILayerVersion#
A list of layers to add to the function's execution environment.

Default: No layers.

You can configure your Lambda function to pull in additional code during initialization in the form of layers. Layers are packages of libraries or other dependencies that can be used by multiple functions.

logFormatoptionalstringlog_formatoptionalstrlogFormatoptionalStringLogFormatoptionalstringLogFormatoptional*string= "Text"deprecated#
Use `loggingFormat` as a property instead.
loggingFormatoptionalLoggingFormatlogging_formatoptionalLoggingFormatloggingFormatoptionalLoggingFormatLoggingFormatoptionalLoggingFormatLoggingFormatoptionalLoggingFormat= LoggingFormat.TEXT#
Sets the loggingFormat for the function.
logGroupoptionalILogGroupReflog_groupoptionalILogGroupReflogGroupoptionalILogGroupRefLogGroupoptionalILogGroupRefLogGroupoptionalILogGroupRef#
The log group the function sends logs to.

Default: /aws/lambda/${this.functionName} - default log group created by Lambda

notes

By default, Lambda functions send logs to an automatically created default log group named /aws/lambda/&lt;function name>. However you cannot change the properties of this auto-created log group using the AWS CDK, e.g. you cannot set a different log retention.

Use the logGroup property to create a fully customizable LogGroup ahead of time, and instruct the Lambda function to send logs to it.

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

logRemovalPolicyoptionalRemovalPolicylog_removal_policyoptionalRemovalPolicylogRemovalPolicyoptionalRemovalPolicyLogRemovalPolicyoptionalRemovalPolicyLogRemovalPolicyoptionalRemovalPolicy= RemovalPolicy.Retaindeprecated#
use `logGroup` instead

Normally you want to retain the log group so you can diagnose issues from logs even after a deployment that no longer includes the log group. In that case, use the normal date-based retention policy to age out your logs.

logRetentionoptionalRetentionDayslog_retentionoptionalRetentionDayslogRetentionoptionalRetentionDaysLogRetentionoptionalRetentionDaysLogRetentionoptionalRetentionDays= logs.RetentionDays.INFINITEdeprecated#
use `logGroup` instead
notes

When updating this property, unsetting it doesn't remove the log retention policy. To remove the retention policy, set the value to INFINITE.

This is a legacy API and we strongly recommend you move away from it if you can. Instead create a fully customizable log group with logs.LogGroup and use the logGroup property to instruct the Lambda function to send logs to it. Migrating from logRetention to logGroup will cause the name of the log group to change. Users and code and referencing the name verbatim will have to adjust.

In AWS CDK code, you can access the log group name directly from the LogGroup construct:

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

declare const myLogGroup: logs.LogGroup;
myLogGroup.logGroupName;
logRetentionRetryOptionsoptionalLogRetentionRetryOptionslog_retention_retry_optionsoptionalLogRetentionRetryOptionslogRetentionRetryOptionsoptionalLogRetentionRetryOptionsLogRetentionRetryOptionsoptionalLogRetentionRetryOptionsLogRetentionRetryOptionsoptionalLogRetentionRetryOptions#
When log retention is specified, a custom resource attempts to create the CloudWatch log group.

Default: Default AWS SDK retry options.

notes

These options control the retry policy when interacting with CloudWatch APIs.

This is a legacy API and we strongly recommend you migrate to logGroup if you can. logGroup allows you to create a fully customizable log group and instruct the Lambda function to send logs to it.

logRetentionRoleoptionalIRolelog_retention_roleoptionalIRolelogRetentionRoleoptionalIRoleLogRetentionRoleoptionalIRoleLogRetentionRoleoptionalIRole#
The IAM role for the Lambda function associated with the custom resource that sets the retention policy.

Default: A new role is created.

This is a legacy API and we strongly recommend you migrate to logGroup if you can. logGroup allows you to create a fully customizable log group and instruct the Lambda function to send logs to it.

maxEventAgeoptionalDurationmax_event_ageoptionalDurationmaxEventAgeoptionalDurationMaxEventAgeoptionalDurationMaxEventAgeoptionalDuration= Duration.hours(6)#
The maximum age of a request that Lambda sends to a function for processing.

Minimum: 60 seconds Maximum: 6 hours

memorySizeoptionalnumbermemory_sizeoptionalint | floatmemorySizeoptionalNumberMemorySizeoptionaldoubleMemorySizeoptional*float64= 128#
The amount of memory, in MB, that is allocated to your Lambda function.

Lambda uses this value to proportionally allocate the amount of CPU power. For more information, see Resource Model in the AWS Lambda Developer Guide.

onFailureoptionalIDestinationon_failureoptionalIDestinationonFailureoptionalIDestinationOnFailureoptionalIDestinationOnFailureoptionalIDestination#
The destination for failed invocations.

Default: no destination

onSuccessoptionalIDestinationon_successoptionalIDestinationonSuccessoptionalIDestinationOnSuccessoptionalIDestinationOnSuccessoptionalIDestination#
The destination for successful invocations.

Default: no destination

paramsAndSecretsoptionalParamsAndSecretsLayerVersionparams_and_secretsoptionalParamsAndSecretsLayerVersionparamsAndSecretsoptionalParamsAndSecretsLayerVersionParamsAndSecretsoptionalParamsAndSecretsLayerVersionParamsAndSecretsoptionalParamsAndSecretsLayerVersion#
Specify the configuration of Parameters and Secrets Extension.

Default: No Parameters and Secrets Extension

profilingoptionalbooleanprofilingoptionalboolprofilingoptionalBooleanProfilingoptionalboolProfilingoptional*bool#
Enable profiling.

Default: No profiling.

profilingGroupoptionalIProfilingGroupprofiling_groupoptionalIProfilingGroupprofilingGroupoptionalIProfilingGroupProfilingGroupoptionalIProfilingGroupProfilingGroupoptionalIProfilingGroup#
Profiling Group.

Default: A new profiling group will be created if profiling is set.

recursiveLoopoptionalRecursiveLooprecursive_loopoptionalRecursiveLooprecursiveLoopoptionalRecursiveLoopRecursiveLoopoptionalRecursiveLoopRecursiveLoopoptionalRecursiveLoop= RecursiveLoop.Terminate#
Sets the Recursive Loop Protection for Lambda Function.

It lets Lambda detect and terminate unintended recursive loops.

reservedConcurrentExecutionsoptionalnumberreserved_concurrent_executionsoptionalint | floatreservedConcurrentExecutionsoptionalNumberReservedConcurrentExecutionsoptionaldoubleReservedConcurrentExecutionsoptional*float64#
The maximum of concurrent executions you want to reserve for the function.

Default: No specific limit - account limit.

retryAttemptsoptionalnumberretry_attemptsoptionalint | floatretryAttemptsoptionalNumberRetryAttemptsoptionaldoubleRetryAttemptsoptional*float64= 2#
The maximum number of times to retry when the function returns an error.

Minimum: 0 Maximum: 2

roleoptionalIRoleroleoptionalIRoleroleoptionalIRoleRoleoptionalIRoleRoleoptionalIRole#
Lambda execution role.

Default: A unique role will be generated for this lambda function. Both supplied and generated roles can always be changed by calling addToRolePolicy.

notes

This is the role that will be assumed by the function upon execution. It controls the permissions that the function will have. The Role must be assumable by the 'lambda.amazonaws.com' service principal.

The default Role automatically has permissions granted for Lambda execution. If you provide a Role, you must add the relevant AWS managed policies yourself.

The relevant managed policies are "service-role/AWSLambdaBasicExecutionRole" and "service-role/AWSLambdaVPCAccessExecutionRole".

runtimeRuntimeruntimeRuntimeruntimeRuntimeRuntimeRuntimeRuntimeRuntimerequired#
The runtime environment for the Lambda function that you are uploading.

For valid values, see the Runtime property in the AWS Lambda Developer Guide.

Use Runtime.FROM_IMAGE when defining a function from a Docker image.

runtimeManagementModeoptionalRuntimeManagementModeruntime_management_modeoptionalRuntimeManagementModeruntimeManagementModeoptionalRuntimeManagementModeRuntimeManagementModeoptionalRuntimeManagementModeRuntimeManagementModeoptionalRuntimeManagementMode= Auto#
Sets the runtime management configuration for a function's version.
securityGroupsoptionalISecurityGroup[]security_groupsoptionaltyping.List[ISecurityGroup]securityGroupsoptionalList<ISecurityGroup>SecurityGroupsoptionalISecurityGroup[]SecurityGroupsoptional*[]ISecurityGroup#
The list of security groups to associate with the Lambda's network interfaces.

Default: If the function is placed within a VPC and a security group is not specified, either by this or securityGroup prop, a dedicated security group will be created for this function.

Only used if 'vpc' is supplied.

snapStartoptionalSnapStartConfsnap_startoptionalSnapStartConfsnapStartoptionalSnapStartConfSnapStartoptionalSnapStartConfSnapStartoptionalSnapStartConf#
Enable SnapStart for Lambda Function.

Default: No snapstart

SnapStart is currently supported for Java 11, Java 17, Python 3.12, Python 3.13, and .NET 8 runtime, as well as container image (OCI) deployments.

stackIdoptionalstringstack_idoptionalstrstackIdoptionalStringStackIdoptionalstringStackIdoptional*string= `edge-lambda-stack-${region}`#
The stack ID of Lambda@Edge function.
systemLogLeveloptionalstringsystem_log_leveloptionalstrsystemLogLeveloptionalStringSystemLogLeveloptionalstringSystemLogLeveloptional*string= "INFO"deprecated#
Use `systemLogLevelV2` as a property instead.
systemLogLevelV2optionalSystemLogLevelsystem_log_level_v2optionalSystemLogLevelsystemLogLevelV2optionalSystemLogLevelSystemLogLevelV2optionalSystemLogLevelSystemLogLevelV2optionalSystemLogLevel= SystemLogLevel.INFO#
Sets the system log level for the function.
tenancyConfigoptionalTenancyConfigtenancy_configoptionalTenancyConfigtenancyConfigoptionalTenancyConfigTenancyConfigoptionalTenancyConfigTenancyConfigoptionalTenancyConfig#
The tenancy configuration for the function.

Default: Tenant isolation is not enabled

timeoutoptionalDurationtimeoutoptionalDurationtimeoutoptionalDurationTimeoutoptionalDurationTimeoutoptionalDuration= Duration.seconds(3)#
The function execution time (in seconds) after which Lambda terminates the function.

Because the execution time affects cost, set this value based on the function's expected execution time.

tracingoptionalTracingtracingoptionalTracingtracingoptionalTracingTracingoptionalTracingTracingoptionalTracing= Tracing.Disabled#
Enable AWS X-Ray Tracing for Lambda Function.
vpcoptionalIVpcvpcoptionalIVpcvpcoptionalIVpcVpcoptionalIVpcVpcoptionalIVpc#
VPC network to place Lambda network interfaces.

Default: Function is not placed within a VPC.

Specify this if the Lambda function needs to access resources in a VPC. This is required when vpcSubnets is specified.

vpcSubnetsoptionalSubnetSelectionvpc_subnetsoptionalSubnetSelectionvpcSubnetsoptionalSubnetSelectionVpcSubnetsoptionalSubnetSelectionVpcSubnetsoptionalSubnetSelection#
Where to place the network interfaces within the VPC.

Default: the Vpc default strategy if not specified

notes

This requires vpc to be specified in order for interfaces to actually be placed in the subnets. If vpc is not specify, this will raise an error.

Note: Internet access for Lambda Functions requires a NAT Gateway, so picking public subnets is not allowed (unless allowPublicSubnet is set to true).

Properties ​

architectureArchitecturearchitectureArchitecturearchitectureArchitectureArchitectureArchitectureArchitectureArchitecturerequired#
The system architectures compatible with this lambda function.
connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#
Not supported.

Connections are only applicable to VPC-enabled functions.

currentVersionIVersioncurrent_versionIVersioncurrentVersionIVersionCurrentVersionIVersionCurrentVersionIVersionrequired#
Convenience method to make `EdgeFunction` conform to the same interface as `Function`.
edgeArnstringedge_arnstredgeArnStringEdgeArnstringEdgeArn*stringrequired#
The ARN of the version for Lambda@Edge.
The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

functionArnstringfunction_arnstrfunctionArnStringFunctionArnstringFunctionArn*stringrequired#
The ARN of the function.
functionNamestringfunction_namestrfunctionNameStringFunctionNamestringFunctionName*stringrequired#
The name of the function.
functionRefFunctionReferencefunction_refFunctionReferencefunctionRefFunctionReferenceFunctionRefFunctionReferenceFunctionRefFunctionReferencerequired#
A reference to a Function resource.
grantPrincipalIPrincipalgrant_principalIPrincipalgrantPrincipalIPrincipalGrantPrincipalIPrincipalGrantPrincipalIPrincipalrequired#
The principal to grant permissions to.
isBoundToVpcbooleanis_bound_to_vpcboolisBoundToVpcBooleanIsBoundToVpcboolIsBoundToVpc*boolrequired#
Whether or not this Lambda function was bound to a VPC.

If this is false, trying to access the connections object will fail.

lambdaIFunctionlambdaIFunctionlambdaIFunctionLambdaIFunctionLambdaIFunctionrequired#
The underlying AWS Lambda function.
latestVersionIVersionlatest_versionIVersionlatestVersionIVersionLatestVersionIVersionLatestVersionIVersionrequired#
The `$LATEST` version of this function.
notes

Note that this is reference to a non-specific AWS Lambda version, which means the function this version refers to can return different results in different invocations.

To obtain a reference to an explicit version which references the current function configuration, use lambdaFunction.currentVersion instead.

nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
permissionsNodeNodepermissions_nodeNodepermissionsNodeNodePermissionsNodeNodePermissionsNodeNoderequired#
The construct node where permissions are attached.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
resourceArnsForGrantInvokestring[]resource_arns_for_grant_invoketyping.List[str]resourceArnsForGrantInvokeList<String>ResourceArnsForGrantInvokestring[]ResourceArnsForGrantInvoke*[]*stringrequired#
The ARN(s) to put into the resource field of the generated IAM policy for grantInvoke().

This property is for cdk modules to consume only. You should not need to use this property. Instead, use grantInvoke() directly.

rolemay be undefinedIRolerolemay be undefinedIRolerolemay be undefinedIRoleRolemay be undefinedIRoleRolemay be undefinedIRole#
The IAM role associated with this function.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
versionstringversionstrversionStringVersionstringVersion*stringrequired#
The most recently deployed version of this function.
versionRefVersionReferenceversion_refVersionReferenceversionRefVersionReferenceVersionRefVersionReferenceVersionRefVersionReferencerequired#
A reference to a Version resource.

Methods ​

addAlias(aliasName: string, options?: AliasOptions): Aliasdef add_alias(self, alias_name: str, options: typing.Optional[AliasOptions] = None) -> Aliaspublic Alias addAlias(String aliasName, AliasOptions options)public Alias AddAlias(string aliasName, AliasOptions? options = null)func AddAlias(AliasName *string, Options AliasOptions) Alias#
Defines an alias for this version.
addEventSource(source: IEventSource): voiddef add_event_source(self, source: IEventSource) -> Nonepublic void addEventSource(IEventSource source)public void AddEventSource(IEventSource source)func AddEventSource(Source IEventSource)#
Adds an event source to this function.
addEventSourceMapping(id: string, options: EventSourceMappingOptions): EventSourceMappingdef add_event_source_mapping(self, id: str, options: EventSourceMappingOptions) -> EventSourceMappingpublic EventSourceMapping addEventSourceMapping(String id, EventSourceMappingOptions options)public EventSourceMapping AddEventSourceMapping(string id, EventSourceMappingOptions options)func AddEventSourceMapping(Id *string, Options EventSourceMappingOptions) EventSourceMapping#
Adds an event source that maps to this AWS Lambda function.
addFunctionUrl(options?: FunctionUrlOptions): FunctionUrldef add_function_url(self, options: typing.Optional[FunctionUrlOptions] = None) -> FunctionUrlpublic FunctionUrl addFunctionUrl(FunctionUrlOptions options)public FunctionUrl AddFunctionUrl(FunctionUrlOptions? options = null)func AddFunctionUrl(Options FunctionUrlOptions) FunctionUrl#
Adds a url to this lambda function.
addPermission(id: string, permission: Permission): voiddef add_permission(self, id: str, permission: Permission) -> Nonepublic void addPermission(String id, Permission permission)public void AddPermission(string id, Permission permission)func AddPermission(Id *string, Permission Permission)#
Adds a permission to the Lambda resource policy.
addToRolePolicy(statement: PolicyStatement): voiddef add_to_role_policy(self, statement: PolicyStatement) -> Nonepublic void addToRolePolicy(PolicyStatement statement)public void AddToRolePolicy(PolicyStatement statement)func AddToRolePolicy(Statement PolicyStatement)#
Adds a statement to the IAM role assumed by the instance.
applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

configureAsyncInvoke(options: EventInvokeConfigOptions): voiddef configure_async_invoke(self, options: EventInvokeConfigOptions) -> Nonepublic void configureAsyncInvoke(EventInvokeConfigOptions options)public void ConfigureAsyncInvoke(EventInvokeConfigOptions options)func ConfigureAsyncInvoke(Options EventInvokeConfigOptions)#
Configures options for asynchronous invocation.
grantInvoke(identity: IGrantable): Grantdef grant_invoke(self, identity: IGrantable) -> Grantpublic Grant grantInvoke(IGrantable identity)public Grant GrantInvoke(IGrantable identity)func GrantInvoke(Identity IGrantable) Grant#
[disable-awslint:no-grants].
grantInvokeCompositePrincipal(compositePrincipal: CompositePrincipal): Grant[]def grant_invoke_composite_principal(self, composite_principal: CompositePrincipal) -> typing.List[Grant]public List<Grant> grantInvokeCompositePrincipal(CompositePrincipal compositePrincipal)public Grant[] GrantInvokeCompositePrincipal(CompositePrincipal compositePrincipal)func GrantInvokeCompositePrincipal(CompositePrincipal CompositePrincipal) *[]Grant#
[disable-awslint:no-grants].
grantInvokeLatestVersion(identity: IGrantable): Grantdef grant_invoke_latest_version(self, identity: IGrantable) -> Grantpublic Grant grantInvokeLatestVersion(IGrantable identity)public Grant GrantInvokeLatestVersion(IGrantable identity)func GrantInvokeLatestVersion(Identity IGrantable) Grant#
[disable-awslint:no-grants].
grantInvokeUrl(identity: IGrantable): Grantdef grant_invoke_url(self, identity: IGrantable) -> Grantpublic Grant grantInvokeUrl(IGrantable identity)public Grant GrantInvokeUrl(IGrantable identity)func GrantInvokeUrl(Identity IGrantable) Grant#
[disable-awslint:no-grants].
grantInvokeVersion(identity: IGrantable, version: IVersion): Grantdef grant_invoke_version(self, identity: IGrantable, version: IVersion) -> Grantpublic Grant grantInvokeVersion(IGrantable identity, IVersion version)public Grant GrantInvokeVersion(IGrantable identity, IVersion version)func GrantInvokeVersion(Identity IGrantable, Version IVersion) Grant#
[disable-awslint:no-grants].
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
metric(metricName: string, props?: MetricOptions): Metricdef metric(self, metric_name: str, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric(String metricName, MetricOptions props)public Metric Metric(string metricName, MetricOptions? props = null)func Metric(MetricName *string, Props MetricOptions) Metric#
Return the given named metric for this Lambda Return the given named metric for this Function.
metricDuration(props?: MetricOptions): Metricdef metric_duration(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricDuration(MetricOptions props)public Metric MetricDuration(MetricOptions? props = null)func MetricDuration(Props MetricOptions) Metric#
Metric for the Duration of this Lambda How long execution of this Lambda takes.

Average over 5 minutes

metricErrors(props?: MetricOptions): Metricdef metric_errors(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricErrors(MetricOptions props)public Metric MetricErrors(MetricOptions? props = null)func MetricErrors(Props MetricOptions) Metric#
How many invocations of this Lambda fail.

Sum over 5 minutes

metricInvocations(props?: MetricOptions): Metricdef metric_invocations(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricInvocations(MetricOptions props)public Metric MetricInvocations(MetricOptions? props = null)func MetricInvocations(Props MetricOptions) Metric#
Metric for the number of invocations of this Lambda How often this Lambda is invoked.

Sum over 5 minutes

metricThrottles(props?: MetricOptions): Metricdef metric_throttles(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricThrottles(MetricOptions props)public Metric MetricThrottles(MetricOptions? props = null)func MetricThrottles(Props MetricOptions) Metric#
Metric for the number of throttled invocations of this Lambda How often this Lambda is throttled.

Sum over 5 minutes

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.