Skip to content
v2.273.0

Function L2 construct ​

This construct does not yet reproduce all features from the underlying resource library.

Example ​

ts
// Create or reference an existing L1 CfnApplicationInferenceProfile
const cfnProfile = new aws_bedrock_cfn.CfnApplicationInferenceProfile(this, 'CfnProfile', {
  inferenceProfileName: 'my-cfn-profile',
  modelSource: {
    copyFrom: bedrock.BedrockFoundationModel.ANTHROPIC_CLAUDE_3_5_SONNET_V1_0.invokableArn,
  },
  description: 'Profile created via L1 construct',
});

// Import the L1 construct as an L2 ApplicationInferenceProfile
const importedFromCfn = bedrock.ApplicationInferenceProfile.fromCfnApplicationInferenceProfile(cfnProfile);

// Grant permissions to use the imported profile
const lambdaFunction = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.PYTHON_3_11,
  handler: 'index.handler',
  code: lambda.Code.fromInline('def handler(event, context): return "Hello"'),
});

importedFromCfn.grantProfileUsage(lambdaFunction);
python
# Create or reference an existing L1 CfnApplicationInferenceProfile
cfn_profile = aws_bedrock_cfn.CfnApplicationInferenceProfile(self, "CfnProfile",
    inference_profile_name="my-cfn-profile",
    model_source=aws_bedrock_cfn.CfnApplicationInferenceProfile.InferenceProfileModelSourceProperty(
        copy_from=bedrock.BedrockFoundationModel.ANTHROPIC_CLAUDE_3_5_SONNET_V1_0.invokable_arn
    ),
    description="Profile created via L1 construct"
)

# Import the L1 construct as an L2 ApplicationInferenceProfile
imported_from_cfn = bedrock.ApplicationInferenceProfile.from_cfn_application_inference_profile(cfn_profile)

# Grant permissions to use the imported profile
lambda_function = lambda_.Function(self, "MyFunction",
    runtime=lambda_.Runtime.PYTHON_3_11,
    handler="index.handler",
    code=lambda_.Code.from_inline("def handler(event, context): return \"Hello\"")
)

imported_from_cfn.grant_profile_usage(lambda_function)
java
// Create or reference an existing L1 CfnApplicationInferenceProfile
CfnApplicationInferenceProfile cfnProfile = CfnApplicationInferenceProfile.Builder.create(this, "CfnProfile")
        .inferenceProfileName("my-cfn-profile")
        .modelSource(InferenceProfileModelSourceProperty.builder()
                .copyFrom(BedrockFoundationModel.ANTHROPIC_CLAUDE_3_5_SONNET_V1_0.getInvokableArn())
                .build())
        .description("Profile created via L1 construct")
        .build();

// Import the L1 construct as an L2 ApplicationInferenceProfile
IInferenceProfile importedFromCfn = ApplicationInferenceProfile.fromCfnApplicationInferenceProfile(cfnProfile);

// Grant permissions to use the imported profile
Function lambdaFunction = Function.Builder.create(this, "MyFunction")
        .runtime(Runtime.PYTHON_3_11)
        .handler("index.handler")
        .code(Code.fromInline("def handler(event, context): return \"Hello\""))
        .build();

importedFromCfn.grantProfileUsage(lambdaFunction);
csharp
// Install: dotnet add package Amazon.CDK.Lib
// Create or reference an existing L1 CfnApplicationInferenceProfile
var cfnProfile = new CfnApplicationInferenceProfile(this, "CfnProfile", new CfnApplicationInferenceProfileProps {
    InferenceProfileName = "my-cfn-profile",
    ModelSource = new InferenceProfileModelSourceProperty {
        CopyFrom = BedrockFoundationModel.ANTHROPIC_CLAUDE_3_5_SONNET_V1_0.InvokableArn
    },
    Description = "Profile created via L1 construct"
});

// Import the L1 construct as an L2 ApplicationInferenceProfile
var importedFromCfn = ApplicationInferenceProfile.FromCfnApplicationInferenceProfile(cfnProfile);

// Grant permissions to use the imported profile
var lambdaFunction = new Function(this, "MyFunction", new FunctionProps {
    Runtime = Runtime.PYTHON_3_11,
    Handler = "index.handler",
    Code = Code.FromInline("def handler(event, context): return \"Hello\"")
});

importedFromCfn.GrantProfileUsage(lambdaFunction);
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
// Create or reference an existing L1 CfnApplicationInferenceProfile
cfnProfile := awscdk.Aws_bedrock.NewCfnApplicationInferenceProfile(this, jsii.String("CfnProfile"), &CfnApplicationInferenceProfileProps{
	InferenceProfileName: jsii.String("my-cfn-profile"),
	ModelSource: &InferenceProfileModelSourceProperty{
		CopyFrom: bedrock.BedrockFoundationModel_ANTHROPIC_CLAUDE_3_5_SONNET_V1_0().InvokableArn,
	},
	Description: jsii.String("Profile created via L1 construct"),
})

// Import the L1 construct as an L2 ApplicationInferenceProfile
importedFromCfn := bedrock.ApplicationInferenceProfile_FromCfnApplicationInferenceProfile(cfnProfile)

// Grant permissions to use the imported profile
lambdaFunction := lambda.NewFunction(this, jsii.String("MyFunction"), &FunctionProps{
	Runtime: lambda.Runtime_PYTHON_3_11(),
	Handler: jsii.String("index.handler"),
	Code: lambda.Code_FromInline(jsii.String("def handler(event, context): return \"Hello\"")),
})

importedFromCfn.GrantProfileUsage(lambdaFunction)

Initializer ​

ts
new Function(scope: Construct, id: string, props: FunctionProps)
python
Function(scope: Construct, id: str, props: FunctionProps)
java
new Function(Construct scope, String id, FunctionProps props)
csharp
new Function(Construct scope, string id, FunctionProps props)
go
NewFunction(Scope Construct, Id *string, Props FunctionProps)

Construct Props ​

adotInstrumentationAdotInstrumentationConfigadot_instrumentationAdotInstrumentationConfigadotInstrumentationAdotInstrumentationConfigAdotInstrumentationAdotInstrumentationConfigAdotInstrumentationAdotInstrumentationConfig= No ADOT instrumentation#
Specify the configuration of AWS Distro for OpenTelemetry (ADOT) instrumentation.
allowAllIpv6Outboundbooleanallow_all_ipv6_outboundboolallowAllIpv6OutboundBooleanAllowAllIpv6OutboundboolAllowAllIpv6Outbound*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.

allowAllOutboundbooleanallow_all_outboundboolallowAllOutboundBooleanAllowAllOutboundboolAllowAllOutbound*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.

allowPublicSubnetbooleanallow_public_subnetboolallowPublicSubnetBooleanAllowPublicSubnetboolAllowPublicSubnet*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.

applicationLogLevelstringapplication_log_levelstrapplicationLogLevelStringApplicationLogLevelstringApplicationLogLevel*string= "INFO"deprecated#
Use `applicationLogLevelV2` as a property instead.
applicationLogLevelV2ApplicationLogLevelapplication_log_level_v2ApplicationLogLevelapplicationLogLevelV2ApplicationLogLevelApplicationLogLevelV2ApplicationLogLevelApplicationLogLevelV2ApplicationLogLevel= ApplicationLogLevel.INFO#
Sets the application log level for the function.
architectureArchitecturearchitectureArchitecturearchitectureArchitectureArchitectureArchitectureArchitectureArchitecture= 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.

codeSigningConfigICodeSigningConfigRefcode_signing_configICodeSigningConfigRefcodeSigningConfigICodeSigningConfigRefCodeSigningConfigICodeSigningConfigRefCodeSigningConfigICodeSigningConfigRef= Not Sign the Code#
Code signing config associated with this function.
currentVersionOptionsVersionOptionscurrent_version_optionsVersionOptionscurrentVersionOptionsVersionOptionsCurrentVersionOptionsVersionOptionsCurrentVersionOptionsVersionOptions= default options as described in …#
Options for the `lambda.Version` resource automatically created by the `fn.currentVersion` method.
default

Default: default options as described in VersionOptions

deadLetterQueueIQueuedead_letter_queueIQueuedeadLetterQueueIQueueDeadLetterQueueIQueueDeadLetterQueueIQueue= SQS queue with 14 day retention …#
The SQS queue to use if DLQ is enabled.

If SNS topic is desired, specify deadLetterTopic property instead.

default

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

deadLetterQueueEnabledbooleandead_letter_queue_enabledbooldeadLetterQueueEnabledBooleanDeadLetterQueueEnabledboolDeadLetterQueueEnabled*bool= false unless `deadLetterQueue` i…#
Enabled DLQ.

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

default

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

deadLetterTopicITopicdead_letter_topicITopicdeadLetterTopicITopicDeadLetterTopicITopicDeadLetterTopicITopic= no SNS topic#
The SNS topic to use as a DLQ.

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.

descriptionstringdescriptionstrdescriptionStringDescriptionstringDescription*string= No description.#
A description of the function.
durableConfigDurableConfigdurable_configDurableConfigdurableConfigDurableConfigDurableConfigDurableConfigDurableConfigDurableConfig= No durable configuration#
The durable configuration for the function.

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.

environment{ [key: string]: string }environmenttyping.Mapping[str, str]environmentMap<String, String>EnvironmentIDictionary<string, string>Environment*map[string]*string= No environment variables.#
Key-value pairs that Lambda caches and makes available for your Lambda functions.

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

environmentEncryptionIKeyRefenvironment_encryptionIKeyRefenvironmentEncryptionIKeyRefEnvironmentEncryptionIKeyRefEnvironmentEncryptionIKeyRef= AWS Lambda creates and uses an A…#
The AWS KMS key that's used to encrypt your function's environment variables.
default

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

ephemeralStorageSizeSizeephemeral_storage_sizeSizeephemeralStorageSizeSizeEphemeralStorageSizeSizeEphemeralStorageSizeSize= 512 MiB#
The size of the function’s /tmp directory in MiB.
eventsIEventSource[]eventstyping.List[IEventSource]eventsList<IEventSource>EventsIEventSource[]Events*[]IEventSource= No event sources.#
Event sources for this function.

You can also add event sources using addEventSource.

filesystemFileSystemfilesystemFileSystemfilesystemFileSystemFilesystemFileSystemFilesystemFileSystem= will not mount any filesystem#
The filesystem configuration for the lambda function.
functionNamestringfunction_namestrfunctionNameStringFunctionNamestringFunctionName*string= AWS CloudFormation generates a u…#
A name for the function.
default

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.

initialPolicyPolicyStatement[]initial_policytyping.List[PolicyStatement]initialPolicyList<PolicyStatement>InitialPolicyPolicyStatement[]InitialPolicy*[]PolicyStatement= No policy statements are added t…#
Initial policy statements to add to the created Lambda Role.

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

default

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

insightsVersionLambdaInsightsVersioninsights_versionLambdaInsightsVersioninsightsVersionLambdaInsightsVersionInsightsVersionLambdaInsightsVersionInsightsVersionLambdaInsightsVersion= No Lambda Insights#
Specify the version of CloudWatch Lambda insights to use for monitoring.
ipv6AllowedForDualStackbooleanipv6_allowed_for_dual_stackboolipv6AllowedForDualStackBooleanIpv6AllowedForDualStackboolIpv6AllowedForDualStack*bool= false#
Allows outbound IPv6 traffic on VPC functions that are connected to dual-stack subnets.

Only used if 'vpc' is supplied.

layersILayerVersion[]layerstyping.List[ILayerVersion]layersList<ILayerVersion>LayersILayerVersion[]Layers*[]ILayerVersion= No layers.#
A list of layers to add to the function's execution environment.

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.

logFormatstringlog_formatstrlogFormatStringLogFormatstringLogFormat*string= "Text"deprecated#
Use `loggingFormat` as a property instead.
loggingFormatLoggingFormatlogging_formatLoggingFormatloggingFormatLoggingFormatLoggingFormatLoggingFormatLoggingFormatLoggingFormat= LoggingFormat.TEXT#
Sets the loggingFormat for the function.
logGroupILogGroupReflog_groupILogGroupReflogGroupILogGroupRefLogGroupILogGroupRefLogGroupILogGroupRef= `/aws/lambda/${this.functionName…#
The log group the function sends logs to.
notes · default

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.

Default: /aws/lambda/$&#123;this.functionName&#125; - default log group created by Lambda

logRemovalPolicyRemovalPolicylog_removal_policyRemovalPolicylogRemovalPolicyRemovalPolicyLogRemovalPolicyRemovalPolicyLogRemovalPolicyRemovalPolicy= 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.

logRetentionRetentionDayslog_retentionRetentionDayslogRetentionRetentionDaysLogRetentionRetentionDaysLogRetentionRetentionDays= 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;
logRetentionRetryOptionsLogRetentionRetryOptionslog_retention_retry_optionsLogRetentionRetryOptionslogRetentionRetryOptionsLogRetentionRetryOptionsLogRetentionRetryOptionsLogRetentionRetryOptionsLogRetentionRetryOptionsLogRetentionRetryOptions= Default AWS SDK retry options.#
When log retention is specified, a custom resource attempts to create the CloudWatch log group.
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.

logRetentionRoleIRolelog_retention_roleIRolelogRetentionRoleIRoleLogRetentionRoleIRoleLogRetentionRoleIRole= A new role is created.#
The IAM role for the Lambda function associated with the custom resource that sets the retention policy.

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.

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

Minimum: 60 seconds Maximum: 6 hours

memorySizenumbermemory_sizeint | floatmemorySizeNumberMemorySizedoubleMemorySize*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.

onFailureIDestinationon_failureIDestinationonFailureIDestinationOnFailureIDestinationOnFailureIDestination= no destination#
The destination for failed invocations.
onSuccessIDestinationon_successIDestinationonSuccessIDestinationOnSuccessIDestinationOnSuccessIDestination= no destination#
The destination for successful invocations.
paramsAndSecretsParamsAndSecretsLayerVersionparams_and_secretsParamsAndSecretsLayerVersionparamsAndSecretsParamsAndSecretsLayerVersionParamsAndSecretsParamsAndSecretsLayerVersionParamsAndSecretsParamsAndSecretsLayerVersion= No Parameters and Secrets Extens…#
Specify the configuration of Parameters and Secrets Extension.
default

Default: No Parameters and Secrets Extension

profilingbooleanprofilingboolprofilingBooleanProfilingboolProfiling*bool= No profiling.#
Enable profiling.
profilingGroupIProfilingGroupprofiling_groupIProfilingGroupprofilingGroupIProfilingGroupProfilingGroupIProfilingGroupProfilingGroupIProfilingGroup= A new profiling group will be cr…#
Profiling Group.
default

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

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

It lets Lambda detect and terminate unintended recursive loops.

reservedConcurrentExecutionsnumberreserved_concurrent_executionsint | floatreservedConcurrentExecutionsNumberReservedConcurrentExecutionsdoubleReservedConcurrentExecutions*float64= No specific limit - account limi…#
The maximum of concurrent executions you want to reserve for the function.
default

Default: No specific limit - account limit.

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

Minimum: 0 Maximum: 2

roleIRoleroleIRoleroleIRoleRoleIRoleRoleIRole= A unique role will be generated …#
Lambda execution role.
notes · default

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".

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

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.

runtimeManagementModeRuntimeManagementModeruntime_management_modeRuntimeManagementModeruntimeManagementModeRuntimeManagementModeRuntimeManagementModeRuntimeManagementModeRuntimeManagementModeRuntimeManagementMode= Auto#
Sets the runtime management configuration for a function's version.
securityGroupsISecurityGroup[]security_groupstyping.List[ISecurityGroup]securityGroupsList<ISecurityGroup>SecurityGroupsISecurityGroup[]SecurityGroups*[]ISecurityGroup= If the function is placed within…#
The list of security groups to associate with the Lambda's network interfaces.

Only used if 'vpc' is supplied.

default

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.

snapStartSnapStartConfsnap_startSnapStartConfsnapStartSnapStartConfSnapStartSnapStartConfSnapStartSnapStartConf= No snapstart#
Enable SnapStart for Lambda Function.

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.

systemLogLevelstringsystem_log_levelstrsystemLogLevelStringSystemLogLevelstringSystemLogLevel*string= "INFO"deprecated#
Use `systemLogLevelV2` as a property instead.
systemLogLevelV2SystemLogLevelsystem_log_level_v2SystemLogLevelsystemLogLevelV2SystemLogLevelSystemLogLevelV2SystemLogLevelSystemLogLevelV2SystemLogLevel= SystemLogLevel.INFO#
Sets the system log level for the function.
tenancyConfigTenancyConfigtenancy_configTenancyConfigtenancyConfigTenancyConfigTenancyConfigTenancyConfigTenancyConfigTenancyConfig= Tenant isolation is not enabled#
The tenancy configuration for the function.
timeoutDurationtimeoutDurationtimeoutDurationTimeoutDurationTimeoutDuration= 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.

tracingTracingtracingTracingtracingTracingTracingTracingTracingTracing= Tracing.Disabled#
Enable AWS X-Ray Tracing for Lambda Function.
vpcIVpcvpcIVpcvpcIVpcVpcIVpcVpcIVpc= Function is not placed within a …#
VPC network to place Lambda network interfaces.

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

default

Default: Function is not placed within a VPC.

vpcSubnetsSubnetSelectionvpc_subnetsSubnetSelectionvpcSubnetsSubnetSelectionVpcSubnetsSubnetSelectionVpcSubnetsSubnetSelection= the Vpc default strategy if not …#
Where to place the network interfaces within the VPC.
notes · default

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).

Default: the Vpc default strategy if not specified

Properties ​

architectureArchitecturearchitectureArchitecturearchitectureArchitectureArchitectureArchitectureArchitectureArchitecturerequired#
The architecture of this Lambda Function (this is an optional attribute and defaults to X86_64).
connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#
Access the Connections object.

Will fail if not a VPC-enabled Lambda Function

currentVersionVersioncurrent_versionVersioncurrentVersionVersionCurrentVersionVersionCurrentVersionVersionrequired#
Returns a `lambda.Version` which represents the current version of this Lambda function. A new version will be created every time the function's configuration changes.

You can specify options for this version using the currentVersionOptions prop when initializing the lambda.Function.

deadLetterQueueIQueuedead_letter_queueIQueuedeadLetterQueueIQueueDeadLetterQueueIQueueDeadLetterQueueIQueue#
The DLQ (as queue) associated with this Lambda Function (this is an optional attribute).
deadLetterTopicITopicdead_letter_topicITopicdeadLetterTopicITopicDeadLetterTopicITopicDeadLetterTopicITopic#
The DLQ (as topic) associated with this Lambda Function (this is an optional attribute).
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#
ARN of this function.
functionNamestringfunction_namestrfunctionNameStringFunctionNamestringFunctionName*stringrequired#
Name of this function.
functionRefFunctionReferencefunction_refFunctionReferencefunctionRefFunctionReferenceFunctionRefFunctionReferenceFunctionRefFunctionReferencerequired#
A reference to a Function resource.
grantPrincipalIPrincipalgrant_principalIPrincipalgrantPrincipalIPrincipalGrantPrincipalIPrincipalGrantPrincipalIPrincipalrequired#
The principal this Lambda Function is running as.
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.

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.

logGroupILogGrouplog_groupILogGrouplogGroupILogGroupLogGroupILogGroupLogGroupILogGrouprequired#
The LogGroup where the Lambda function's logs are made available.
notes

If either logRetention is set or this 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, 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.

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().
roleIRoleroleIRoleroleIRoleRoleIRoleRoleIRole#
Execution role associated with this function.
runtimeRuntimeruntimeRuntimeruntimeRuntimeRuntimeRuntimeRuntimeRuntimerequired#
The runtime configured for this lambda.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
tenancyConfigTenancyConfigtenancy_configTenancyConfigtenancyConfigTenancyConfigTenancyConfigTenancyConfigTenancyConfigTenancyConfig#
The tenancy configuration for this function.
timeoutDurationtimeoutDurationtimeoutDurationTimeoutDurationTimeoutDuration#
The timeout configured for this lambda.

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 function.
notes · 2 parameters

The alias will automatically be updated to point to the latest version of the function as it is being updated during a deployment.

ts
declare const fn: lambda.Function;

fn.addAlias('Live');

// Is equivalent to

new lambda.Alias(this, 'AliasLive', {
  aliasName: 'Live',
  version: fn.currentVersion,
});

Parameters

  • aliasNamealias_namealiasNamealiasNameAliasName — The name of the alias.
  • optionsoptionsoptionsoptionsOptions — Alias options.
addEnvironment(key: string, value: string, options?: EnvironmentOptions): Function // chainabledef add_environment(self, key: str, value: str, options: typing.Optional[EnvironmentOptions] = None) -> Functionpublic Function addEnvironment(String key, String value, EnvironmentOptions options)public Function AddEnvironment(string key, string value, EnvironmentOptions? options = null)func AddEnvironment(Key *string, Value *string, Options EnvironmentOptions) Function#
Adds an environment variable to this Lambda function.

If this is a ref to a Lambda function, this operation results in a no-op.

3 parameters

Parameters

  • keykeykeykeyKey — The environment variable key.
  • valuevaluevaluevalueValue — The environment variable's value.
  • optionsoptionsoptionsoptionsOptions — Environment variable options.
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.
notes

Event sources are implemented in the aws-cdk-lib/aws-lambda-event-sources module.

The following example adds an SQS Queue as an event source:

import { SqsEventSource } from 'aws-cdk-lib/aws-lambda-event-sources';
myFunction.addEventSource(new SqsEventSource(myQueue));
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.
addLayers(...layers: ILayerVersion[]): voiddef add_layers(self, layers: ILayerVersion) -> Nonepublic void addLayers(ILayerVersion layers)public void AddLayers(ILayerVersion layers)func AddLayers(Layers ILayerVersion)#
Adds one or more Lambda Layers to this Lambda function.
1 parameter

Parameters

  • layerslayerslayerslayersLayers — the layers to be added.
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.
2 parameters

Parameters

  • ididididId — The id for the permission construct.
  • permissionpermissionpermissionpermissionPermission — The permission to grant to this Lambda function.
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).

classifyVersionProperty(propertyName: string, locked: boolean): void@staticmethod def classify_version_property(property_name: str, locked: bool) -> Nonepublic static void classifyVersionProperty(String propertyName, Boolean locked)public static void ClassifyVersionProperty(string propertyName, bool locked)func ClassifyVersionProperty(PropertyName *string, Locked *bool)static#
Record whether specific properties in the `AWS::Lambda::Function` resource should also be associated to the Version resource.

See 'currentVersion' section in the module README for more details.

2 parameters

Parameters

  • propertyNameproperty_namepropertyNamepropertyNamePropertyName — The property to classify.
  • lockedlockedlockedlockedLocked — whether the property should be associated to the version or not.
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.
considerWarningOnInvokeFunctionPermissions(scope: Construct, action: string): voiddef consider_warning_on_invoke_function_permissions(self, scope: Construct, action: str) -> Nonepublic void considerWarningOnInvokeFunctionPermissions(Construct scope, String action)public void ConsiderWarningOnInvokeFunctionPermissions(Construct scope, string action)func ConsiderWarningOnInvokeFunctionPermissions(Scope Construct, Action *string)#
A warning will be added to functions under the following conditions: - permissions that include `lambda:InvokeFunction` are added to the unqualified function.
  • function.currentVersion is invoked before or after the permission is created.

This applies only to permissions on Lambda functions, not versions or aliases. This function is overridden as a noOp for QualifiedFunctionBase.

fromFunctionArn(scope: Construct, id: string, functionArn: string): IFunction@staticmethod def from_function_arn(scope: Construct, id: str, function_arn: str) -> IFunctionpublic static IFunction fromFunctionArn(Construct scope, String id, String functionArn)public static IFunction FromFunctionArn(Construct scope, string id, string functionArn)func FromFunctionArn(Scope Construct, Id *string, FunctionArn *string) IFunctionstatic#
Import a lambda function into the CDK using its ARN.

For Function.addPermissions() to work on this imported lambda, make sure that is in the same account and region as the stack you are importing it into.

fromFunctionAttributes(scope: Construct, id: string, attrs: FunctionAttributes): IFunction@staticmethod def from_function_attributes(scope: Construct, id: str, attrs: FunctionAttributes) -> IFunctionpublic static IFunction fromFunctionAttributes(Construct scope, String id, FunctionAttributes attrs)public static IFunction FromFunctionAttributes(Construct scope, string id, FunctionAttributes attrs)func FromFunctionAttributes(Scope Construct, Id *string, Attrs FunctionAttributes) IFunctionstatic#
Creates a Lambda function object which represents a function not defined within this stack.

For Function.addPermissions() to work on this imported lambda, set the sameEnvironment property to true if this imported lambda is in the same account and region as the stack you are importing it into.

3 parameters

Parameters

  • scopescopescopescopeScope — The parent construct.
  • ididididId — The name of the lambda construct.
  • attrsattrsattrsattrsAttrs — the attributes of the function to import.
fromFunctionName(scope: Construct, id: string, functionName: string): IFunction@staticmethod def from_function_name(scope: Construct, id: str, function_name: str) -> IFunctionpublic static IFunction fromFunctionName(Construct scope, String id, String functionName)public static IFunction FromFunctionName(Construct scope, string id, string functionName)func FromFunctionName(Scope Construct, Id *string, FunctionName *string) IFunctionstatic#
Import a lambda function into the CDK using its name.
grantInvoke(grantee: IGrantable): Grantdef grant_invoke(self, grantee: IGrantable) -> Grantpublic Grant grantInvoke(IGrantable grantee)public Grant GrantInvoke(IGrantable grantee)func GrantInvoke(Grantee IGrantable) Grant#
Grant the given identity permissions to invoke this Lambda.

[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#
Grant multiple principals the ability to invoke this Lambda via CompositePrincipal.

[disable-awslint:no-grants]

grantInvokeLatestVersion(grantee: IGrantable): Grantdef grant_invoke_latest_version(self, grantee: IGrantable) -> Grantpublic Grant grantInvokeLatestVersion(IGrantable grantee)public Grant GrantInvokeLatestVersion(IGrantable grantee)func GrantInvokeLatestVersion(Grantee IGrantable) Grant#
Grant the given identity permissions to invoke the $LATEST version or unqualified version of this Lambda.

[disable-awslint:no-grants]

grantInvokeUrl(grantee: IGrantable): Grantdef grant_invoke_url(self, grantee: IGrantable) -> Grantpublic Grant grantInvokeUrl(IGrantable grantee)public Grant GrantInvokeUrl(IGrantable grantee)func GrantInvokeUrl(Grantee IGrantable) Grant#
Grant the given identity permissions to invoke this Lambda Function URL.

[disable-awslint:no-grants]

grantInvokeVersion(grantee: IGrantable, version: IVersion): Grantdef grant_invoke_version(self, grantee: IGrantable, version: IVersion) -> Grantpublic Grant grantInvokeVersion(IGrantable grantee, IVersion version)public Grant GrantInvokeVersion(IGrantable grantee, IVersion version)func GrantInvokeVersion(Grantee IGrantable, Version IVersion) Grant#
Grant the given identity permissions to invoke the given version of this Lambda.

[disable-awslint:no-grants]

invalidateVersionBasedOn(x: string): voiddef invalidate_version_based_on(self, x: str) -> Nonepublic void invalidateVersionBasedOn(String x)public void InvalidateVersionBasedOn(string x)func InvalidateVersionBasedOn(X *string)#
Mix additional information into the hash of the Version object.
notes

The Lambda Function construct does its best to automatically create a new Version when anything about the Function changes (its code, its layers, any of the other properties).

However, you can sometimes source information from places that the CDK cannot look into, like the deploy-time values of SSM parameters. In those cases, the CDK would not force the creation of a new Version object when it actually should.

This method can be used to invalidate the current Version object. Pass in any string into this method, and make sure the string changes when you know a new Version needs to be created.

This method may be called more than once.

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 Function.
metricAll(metricName: string, props?: MetricOptions): Metric@staticmethod def metric_all(metric_name: str, props: typing.Optional[MetricOptions] = None) -> Metricpublic static Metric metricAll(String metricName, MetricOptions props)public static Metric MetricAll(string metricName, MetricOptions? props = null)func MetricAll(MetricName *string, Props MetricOptions) Metricstatic#
Return the given named metric for this Lambda.
metricAllConcurrentExecutions(props?: MetricOptions): Metric@staticmethod def metric_all_concurrent_executions(props: typing.Optional[MetricOptions] = None) -> Metricpublic static Metric metricAllConcurrentExecutions(MetricOptions props)public static Metric MetricAllConcurrentExecutions(MetricOptions? props = null)func MetricAllConcurrentExecutions(Props MetricOptions) Metricstatic#
Metric for the number of concurrent executions across all Lambdas.
metricAllDuration(props?: MetricOptions): Metric@staticmethod def metric_all_duration(props: typing.Optional[MetricOptions] = None) -> Metricpublic static Metric metricAllDuration(MetricOptions props)public static Metric MetricAllDuration(MetricOptions? props = null)func MetricAllDuration(Props MetricOptions) Metricstatic#
Metric for the Duration executing all Lambdas.
metricAllErrors(props?: MetricOptions): Metric@staticmethod def metric_all_errors(props: typing.Optional[MetricOptions] = None) -> Metricpublic static Metric metricAllErrors(MetricOptions props)public static Metric MetricAllErrors(MetricOptions? props = null)func MetricAllErrors(Props MetricOptions) Metricstatic#
Metric for the number of Errors executing all Lambdas.
metricAllInvocations(props?: MetricOptions): Metric@staticmethod def metric_all_invocations(props: typing.Optional[MetricOptions] = None) -> Metricpublic static Metric metricAllInvocations(MetricOptions props)public static Metric MetricAllInvocations(MetricOptions? props = null)func MetricAllInvocations(Props MetricOptions) Metricstatic#
Metric for the number of invocations of all Lambdas.
metricAllThrottles(props?: MetricOptions): Metric@staticmethod def metric_all_throttles(props: typing.Optional[MetricOptions] = None) -> Metricpublic static Metric metricAllThrottles(MetricOptions props)public static Metric MetricAllThrottles(MetricOptions? props = null)func MetricAllThrottles(Props MetricOptions) Metricstatic#
Metric for the number of throttled invocations of all Lambdas.
metricAllUnreservedConcurrentExecutions(props?: MetricOptions): Metric@staticmethod def metric_all_unreserved_concurrent_executions(props: typing.Optional[MetricOptions] = None) -> Metricpublic static Metric metricAllUnreservedConcurrentExecutions(MetricOptions props)public static Metric MetricAllUnreservedConcurrentExecutions(MetricOptions? props = null)func MetricAllUnreservedConcurrentExecutions(Props MetricOptions) Metricstatic#
Metric for the number of unreserved concurrent executions across all Lambdas.
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#
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#
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#
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.