diff --git a/packages/@aws-cdk/aws-lambda/lib/function.ts b/packages/@aws-cdk/aws-lambda/lib/function.ts index 9c296ea30a7b1..87ad0335cf238 100644 --- a/packages/@aws-cdk/aws-lambda/lib/function.ts +++ b/packages/@aws-cdk/aws-lambda/lib/function.ts @@ -486,6 +486,25 @@ export class Function extends FunctionBase { }); } + /** + * Add a new version for this Lambda, always with a different name. + * + * This is similar to the {@link addVersion} method, + * but useful when deploying this Lambda through CodePipeline with blue/green deployments. + * When using {@link addVersion}, + * your Alias will not be updated until you change the name passed to {@link addVersion} in your CDK code. + * When deploying through a Pipeline, + * that might lead to a situation where a change to your Lambda application code will never be activated, + * even though it traveled through the entire Pipeline, + * because the Alias is still pointing to an old Version. + * This method creates a new, unique Version every time the CDK code is executed, + * and so prevents that from happening. + */ + public newVersion(): Version { + const now = new Date(); + return this.addVersion(now.toISOString()); + } + private renderEnvironment() { if (!this.environment || Object.keys(this.environment).length === 0) { return undefined; diff --git a/packages/@aws-cdk/aws-lambda/test/test.alias.ts b/packages/@aws-cdk/aws-lambda/test/test.alias.ts index a41a075dfaf3a..1deb7d3ac00a8 100644 --- a/packages/@aws-cdk/aws-lambda/test/test.alias.ts +++ b/packages/@aws-cdk/aws-lambda/test/test.alias.ts @@ -1,6 +1,5 @@ +import { beASupersetOfTemplate, expect, haveResource, haveResourceLike } from '@aws-cdk/assert'; import cloudwatch = require('@aws-cdk/aws-cloudwatch'); - -import { beASupersetOfTemplate, expect, haveResource } from '@aws-cdk/assert'; import { Stack } from '@aws-cdk/cdk'; import { Test } from 'nodeunit'; import lambda = require('../lib'); @@ -41,6 +40,33 @@ export = { test.done(); }, + 'can use newVersion to create a new Version'(test: Test) { + const stack = new Stack(); + const fn = new lambda.Function(stack, 'MyLambda', { + code: new lambda.InlineCode('hello()'), + handler: 'index.hello', + runtime: lambda.Runtime.NodeJS610, + }); + + const version = fn.newVersion(); + + new lambda.Alias(stack, 'Alias', { + aliasName: 'prod', + version, + }); + + expect(stack).to(haveResourceLike('AWS::Lambda::Version', { + FunctionName: { Ref: "MyLambdaCCE802FB" }, + })); + + expect(stack).to(haveResourceLike('AWS::Lambda::Alias', { + FunctionName: { Ref: "MyLambdaCCE802FB" }, + Name: "prod" + })); + + test.done(); + }, + 'can add additional versions to alias'(test: Test) { const stack = new Stack();