Skip to content
v2.273.0

Version L2 construct ​

Tag the current state of a Function with a Version number.

Avoid using this resource directly. If you need a Version object, use function.currentVersion instead. That will add a Version object to your template, and make sure the Version is invalidated whenever the Function object changes. If you use the Version resource directly, you are responsible for making sure it is invalidated (by changing its logical ID) whenever necessary.

Version resources can then be used in Alias resources to refer to a particular deployment of a Lambda.

If you want to ensure that you're associating the right version with the right deployment, specify the codeSha256 property while creating the `Version.

Example ​

ts
const lambdaCode = lambda.Code.fromCfnParameters();
const func = new lambda.Function(this, 'Lambda', {
  code: lambdaCode,
  handler: 'index.handler',
  runtime: lambda.Runtime.NODEJS_LATEST,
});
// used to make sure each CDK synthesis produces a different Version
const version = func.currentVersion;
const alias = new lambda.Alias(this, 'LambdaAlias', {
  aliasName: 'Prod',
  version,
});

new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', {
  alias,
  deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE,
});
python
lambda_code = lambda_.Code.from_cfn_parameters()
func = lambda_.Function(self, "Lambda",
    code=lambda_code,
    handler="index.handler",
    runtime=lambda_.Runtime.NODEJS_LATEST
)
# used to make sure each CDK synthesis produces a different Version
version = func.current_version
alias = lambda_.Alias(self, "LambdaAlias",
    alias_name="Prod",
    version=version
)

codedeploy.LambdaDeploymentGroup(self, "DeploymentGroup",
    alias=alias,
    deployment_config=codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE
)
java
CfnParametersCode lambdaCode = Code.fromCfnParameters();
Function func = Function.Builder.create(this, "Lambda")
        .code(lambdaCode)
        .handler("index.handler")
        .runtime(Runtime.NODEJS_LATEST)
        .build();
// used to make sure each CDK synthesis produces a different Version
Version version = func.getCurrentVersion();
Alias alias = Alias.Builder.create(this, "LambdaAlias")
        .aliasName("Prod")
        .version(version)
        .build();

LambdaDeploymentGroup.Builder.create(this, "DeploymentGroup")
        .alias(alias)
        .deploymentConfig(LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE)
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
var lambdaCode = Code.FromCfnParameters();
var func = new Function(this, "Lambda", new FunctionProps {
    Code = lambdaCode,
    Handler = "index.handler",
    Runtime = Runtime.NODEJS_LATEST
});
// used to make sure each CDK synthesis produces a different Version
var version = func.CurrentVersion;
var alias = new Alias(this, "LambdaAlias", new AliasProps {
    AliasName = "Prod",
    Version = version
});

new LambdaDeploymentGroup(this, "DeploymentGroup", new LambdaDeploymentGroupProps {
    Alias = alias,
    DeploymentConfig = LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
lambdaCode := lambda.Code_FromCfnParameters()
func := lambda.NewFunction(this, jsii.String("Lambda"), &FunctionProps{
	Code: lambdaCode,
	Handler: jsii.String("index.handler"),
	Runtime: lambda.Runtime_NODEJS_LATEST(),
})
// used to make sure each CDK synthesis produces a different Version
version := func.currentVersion
alias := lambda.NewAlias(this, jsii.String("LambdaAlias"), &AliasProps{
	AliasName: jsii.String("Prod"),
	Version: Version,
})

codedeploy.NewLambdaDeploymentGroup(this, jsii.String("DeploymentGroup"), &LambdaDeploymentGroupProps{
	Alias: Alias,
	DeploymentConfig: codedeploy.LambdaDeploymentConfig_LINEAR_10PERCENT_EVERY_1MINUTE(),
})

Initializer ​

ts
new Version(scope: Construct, id: string, props: VersionProps)
python
Version(scope: Construct, id: str, props: VersionProps)
java
new Version(Construct scope, String id, VersionProps props)
csharp
new Version(Construct scope, string id, VersionProps props)
go
NewVersion(Scope Construct, Id *string, Props VersionProps)

Construct Props ​

codeSha256stringcode_sha256strcodeSha256StringCodeSha256stringCodeSha256*string= No validation is performed#
SHA256 of the version of the Lambda source code.

Specify to validate that you're deploying the right version.

descriptionstringdescriptionstrdescriptionStringDescriptionstringDescription*string= Description of the Lambda#
Description of the version.
lambdaIFunctionlambdaIFunctionlambdaIFunctionLambdaIFunctionLambdaIFunctionrequired#
Function to get the value of.
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

maxExecutionEnvironmentsnumbermax_execution_environmentsint | floatmaxExecutionEnvironmentsNumberMaxExecutionEnvironmentsdoubleMaxExecutionEnvironments*float64= No maximum specified#
The maximum number of execution environments allowed for this version when published into a capacity provider.

This setting limits the total number of execution environments that can be created to handle concurrent invocations of this specific version.

minExecutionEnvironmentsnumbermin_execution_environmentsint | floatminExecutionEnvironmentsNumberMinExecutionEnvironmentsdoubleMinExecutionEnvironments*float64= 3 execution environments are set…#
The minimum number of execution environments to maintain for this version when published into a capacity provider.

This setting ensures that at least this many execution environments are always available to handle function invocations for this specific version, reducing cold start latency.

default

Default: 3 execution environments are set to be the minimum

onFailureIDestinationon_failureIDestinationonFailureIDestinationOnFailureIDestinationOnFailureIDestination= no destination#
The destination for failed invocations.
onSuccessIDestinationon_successIDestinationonSuccessIDestinationOnSuccessIDestinationOnSuccessIDestination= no destination#
The destination for successful invocations.
provisionedConcurrentExecutionsnumberprovisioned_concurrent_executionsint | floatprovisionedConcurrentExecutionsNumberProvisionedConcurrentExecutionsdoubleProvisionedConcurrentExecutions*float64= No provisioned concurrency#
Specifies a provisioned concurrency configuration for a function's version.
removalPolicyRemovalPolicyremoval_policyRemovalPolicyremovalPolicyRemovalPolicyRemovalPolicyRemovalPolicyRemovalPolicyRemovalPolicy= RemovalPolicy.DESTROY#
Whether to retain old versions of this function when a new version is created.
retryAttemptsnumberretry_attemptsint | floatretryAttemptsNumberRetryAttemptsdoubleRetryAttempts*float64= 2#
The maximum number of times to retry when the function returns an error.

Minimum: 0 Maximum: 2

Properties ​

architectureArchitecturearchitectureArchitecturearchitectureArchitectureArchitectureArchitectureArchitectureArchitecturerequired#
The architecture of this Lambda Function.
connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#
Access the Connections object.

Will fail if not a VPC-enabled Lambda 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 fo the function.
functionNamestringfunction_namestrfunctionNameStringFunctionNamestringFunctionName*stringrequired#
The name of the 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.

lambdaIFunctionlambdaIFunctionlambdaIFunctionLambdaIFunctionLambdaIFunctionrequired#
The underlying `IFunction`.
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().
roleIRoleroleIRoleroleIRoleRoleIRoleRoleIRole#
The IAM role associated with this function.

Undefined if the function was imported without a role.

stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.
tenancyConfigTenancyConfigtenancy_configTenancyConfigtenancyConfigTenancyConfigTenancyConfigTenancyConfigTenancyConfigTenancyConfig#
The tenancy configuration for this function.
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) Aliasdeprecated#
Calling `addAlias` on a `Version` object will cause the Alias to be replaced on every function update. Call `function.addAlias()` or `new Alias()` instead.
2 parameters

Parameters

  • aliasNamealias_namealiasNamealiasNameAliasName — The name of the alias (e.g. "live").
  • optionsoptionsoptionsoptionsOptions — Alias 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.
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).

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.

fromVersionArn(scope: Construct, id: string, versionArn: string): IVersion@staticmethod def from_version_arn(scope: Construct, id: str, version_arn: str) -> IVersionpublic static IVersion fromVersionArn(Construct scope, String id, String versionArn)public static IVersion FromVersionArn(Construct scope, string id, string versionArn)func FromVersionArn(Scope Construct, Id *string, VersionArn *string) IVersionstatic#
Construct a Version object from a Version ARN.
3 parameters

Parameters

  • scopescopescopescopeScope — The cdk scope creating this resource.
  • ididididId — The cdk id of this resource.
  • versionArnversion_arnversionArnversionArnVersionArn — The version ARN to create this version from.
fromVersionAttributes(scope: Construct, id: string, attrs: VersionAttributes): IVersion@staticmethod def from_version_attributes(scope: Construct, id: str, attrs: VersionAttributes) -> IVersionpublic static IVersion fromVersionAttributes(Construct scope, String id, VersionAttributes attrs)public static IVersion FromVersionAttributes(Construct scope, string id, VersionAttributes attrs)func FromVersionAttributes(Scope Construct, Id *string, Attrs VersionAttributes) IVersionstatic#
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]

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