3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWS CDKでLambdaに環境変数を設定する

3
Posted at

AWS CDKでデプロイするLambdaに環境変数を設定する方法をまとめます。

環境変数を設定するメリット

環境変数を設定することで、開発や本番といった環境ごとにロジックを変えなくても動作を変えることができます。例えば、開発と本番のDBを切り替えたいときなどに使えます。

CDKでの環境変数の設定方法

AWS CDKではLamdbaのデプロイ設定で、環境変数を設定できます。

lib/sample_stack.ts
import * as cdk from "aws-cdk-lib/core";
import { Construct } from "constructs";
import * as lambda from "aws-cdk-lib/aws-lambda";

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

    new lambda.Function(this, "SampleFunction", {
      runtime: lambda.Runtime.NODEJS_24_X,
      handler: "index.handler",
      code: lambda.Code.fromAsset("lambda"),
      timeout: cdk.Duration.seconds(10),
      // ここに環境変数をkey - value形式で設定
      environment: {
        ENV_VALUE: "from_env",
      },
    });
  }
}

Lambda関数内での環境変数の利用方法

Lambda関数内では通常の方法で環境変数を参照できます。

lambda/index.ts
import { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from "aws-lambda";

export const handler = async (
  event: APIGatewayProxyEventV2,
): Promise<APIGatewayProxyResultV2> => {
  // 通常の方法で環境変数を利用できる
  console.log("ENV_VALUE", process.env.ENV_VALUE);

  // 中略
};

利用時の注意

CI/CDを利用している場合は、CDKで設定する際もprocess.envから読み取るなどすることで設定値を一元管理できます。

APIキーやパスワードなどはSecrets Managerなど利用したほうが安全です。CI/CD側で機密情報として見れなくしていても、環境変数に設定するとLambdaの設定タブ > 環境変数から生の値が見れてしまうためです。

image.png

まとめ

CDKでデプロイするLmabdaで環境変数を利用するには、CDKのenvironmentに設定すればLambdaでは通常の方法で利用できます。APIキーなど機密性が高いものはSecrets Managerなどを使ったほうが安全です。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?