3
votes

I use AWS CDK to manage Lambda.

I created two alias for the Lambda function, development and production.

But I don't know how to associate a version with each alias.

export class CdkLambdaStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);

        const fnDemo = new NodejsFunction(this, 'demo', {
            entry: 'lib/lambda-handler/index.ts',
            currentVersionOptions: {
                removalPolicy: RemovalPolicy.RETAIN,
                retryAttempts: 1
            }
        });

        // In this case, production would be the most recent version
        // I want to specify the previous stable version
        fnDemo.currentVersion.addAlias('production');


        new lambda.Alias(this, 'demo-development-alias', {
            aliasName: 'development',
            version: fnDemo.latestVersion
        });

    }
}

I've looked at the AWS CDK documentation, but I can't find a way to get a previous version It was. Do you have any other good ideas?

https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda.Version.html

1
When you create a new lamda function using cdk, there's only one version, therefore, you can set alias to this version only - Amit Baranes
Thanks for the reply. I understand. So you're saying that CDK doesn't keep track of past versions. - zaru

1 Answers

3
votes

resolved

import cdk = require('@aws-cdk/core');

import * as lambda from '@aws-cdk/aws-lambda';
import {NodejsFunction} from '@aws-cdk/aws-lambda-nodejs';
import {RemovalPolicy} from "@aws-cdk/core";

export class CdkLambdaStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);

        const fnDemo = new NodejsFunction(this, 'demo', {
            entry: 'lib/lambda-handler/index.ts',
            currentVersionOptions: {
                removalPolicy: RemovalPolicy.RETAIN,
            }
        });

        const prodVersion = lambda.Version.fromVersionArn(this, 'prodVersion', `${fnDemo.functionArn}:1`);
        prodVersion.addAlias('production');
        
        const stgVersion = lambda.Version.fromVersionArn(this, 'stgVersion', `${fnDemo.functionArn}:2`);
        stgVersion.addAlias('staging');
        
        const currentVersion = fnDemo.currentVersion;
        const development = new lambda.Alias(this, 'demo-development', {
            aliasName: 'development',
            version: currentVersion
        });
    }
}