In this blog, we will learn how to add environment variables to the Lambda function using CDK. First, we have learned how to create the Lambda function using CDK. Adding environment variables using CDK is easy.

Environment variables in Lambda

Environment variables in Lambda are similar to those in other programming languages like Node or Python. For example, we can use these variables for Database connection URLs or passwords. You can learn more about how environment variables work in Lambda in AWS Docs.

Adding environment variables

We can add these to the lambda function using CDK in the following manner.

import { Stack, StackProps, Duration } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from 'aws-cdk-lib/aws-lambda';

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

    new lambda.Function(this, "LambdaFunctionFromCDK", {
      runtime: lambda.Runtime.NODEJS_16_X,
      handler: "index.handler",
      code: lambda.AssetCode.fromAsset("../lambda-code"),
      memorySize: 512,
      timeout: Duration.seconds(10),
      environment: {
        ENV: "dev",
        DB_URL: "https:dev.example.com",
      }
    });
  }
}

Lambda construct takes environment parameter that accepts key-value pairs. When we deploy our stack, these key-value pairs will be added as environment variables to the lambda function.

Let us deploy our stack and validate. When we check our lambda function on the AWS console, we see that these variables have been added.

Environment variables for Lambda function added using CDK
Environment variables for Lambda function added using CDK

Adding values using process.env

We are not limited to adding constant values to these environment variables. We can use language-specific features to add any values to these environment variables. As we are using Typescript(javascript), we can use process.env to set these values.

For this, I have installed `dotenv` package in my CDK project.

npm install dotenv -D

Then added a simple `.env` file.

DEV_DB_PASSWORD=12343
PROD_DB_PASSWORD=12342

Now we are ready to pass lambda environment variable values using process.env. But when we try that, we will see an error like the one below.

Error when using process.env
Error when using process.env

Typescript does not know that we have already set the value for `DEV_DB_PASSWORD.` Hence it is comparing it as we can not pass an empty value for the environment variable. But we know this variable is present, and we can let Typescript know about it by adding ‘!’ at the end of our variable name, as shown below.

import { Stack, StackProps, Duration } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from 'aws-cdk-lib/aws-lambda';

import { config } from 'dotenv';
config();

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

    new lambda.Function(this, "LambdaFunctionFromCDK", {
      runtime: lambda.Runtime.NODEJS_16_X,
      handler: "index.handler",
      code: lambda.AssetCode.fromAsset("../lambda-code"),
      memorySize: 512,
      timeout: Duration.seconds(10),
      environment: {
        ENV: "dev",
        DB_URL: "https:dev.example.com",
        DB_PASSWORD: process.env.DEV_DB_PASSWORD!,
      }
    });
  }
}

We can deploy this code and check on the AWS console if DB_PASSWORD has the correct value or not.

Environment variable set up using process.env
Environment variable set up using process.env

Hey, it worked. This will be useful when you have a large project with different environments.

Conclusion

I hope you have found it easy to add environment variables to Lambda using CDK. Let me know if you have any questions about it. See you in the next blog.

Share with your friends

Similar Posts

Leave a Reply

Your email address will not be published.