DEV Community

Harshit Sahu
Harshit Sahu

Posted on

AWS CDK : Create new Lambda Versions with Alias pointing to $LATEST

Greetings,

Today, I would like to discuss my experience in writing AWS CDK code for Lambda versioning, with an alias pointing to either the latest version or a custom version of choice.

One of my clients requested a Lambda implementation that would generate a new version with each deployment. At first, it seemed like a straightforward task: simply import the Lambda version and create it as follows:

import { Alias, Version } from "aws-cdk-lib/aws-lambda";

new Version(this, `version-identifier-id`, {
  lambda,
  description: "v1",
  removalPolicy: RemovalPolicy.RETAIN,
});
Enter fullscreen mode Exit fullscreen mode

However, this approach overrides the previous Lambda version, which is undesirable in case we need to roll back to an earlier version. Despite extensive research, I couldn't find a solution online. I experimented with different combinations of the removalPolicy attribute, but to no avail.

After several trials and errors, I discovered that the cdk diff command reports a change, implying that there must be some alteration. This command only worked when I modified the version-identifier-id in the stack. I updated the code as follows:

import { Alias, Version } from "aws-cdk-lib/aws-lambda";

new Version(this, `${Math.random()}`, {
  lambda,
  description: "v1",
  removalPolicy: RemovalPolicy.RETAIN,
});
Enter fullscreen mode Exit fullscreen mode

This solution worked perfectly. Now, each time a deployment is executed via the cdk deploy command, a new Lambda version is generated. While this approach functions well, there is an inherent issue: creating a new version even when there are no changes in the Lambda code.

Addressing this challenge will be the focus of the next blog post. Stay tuned for more insights into AWS CDK and Lambda versioning.

Top comments (0)