Lambda(C#)の環境変数にアクセスする

今回はLambdaの環境変数C#からアクセスしてみます。 接続するDBを環境毎に切り替える場合などに役立ちます。

AWS Lambda の新機能 – 環境変数とサーバーレスアプリケーションモデル (SAM) | Amazon Web Services ブログ (結構最近追加された機能だったのですね。)

Lambdaの実装

まずはLambdaの実装です。
といってもこれまでのC#プログラミングと同じで、以下のようにEnvironment.GetEnvironmentVariableメソッドでアクセスできます。

// 環境変数"Path"にアクセスする場合
var pathValue = Environment.GetEnvironmentVariable("Path");

今回は"ENV_NAME"という名前で設定された環境変数にコンストラクタからアクセスしています。

using System;
using System.Collections.Generic;
using System.Net;
using Amazon.Lambda.Core;
using Amazon.Lambda.APIGatewayEvents;

[assembly: LambdaSerializerAttribute(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace AWSServerless
{
    public class Functions
    {
        private readonly string envName;
        
        public Functions()
        {
            envName = Environment.GetEnvironmentVariable("ENV_NAME");
        }
        
        public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = $"This environment is {envName}",
                Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } }
            };

            return response;
        }
    }
}

Serverlessでデプロイ

AWSコンソールからでも設定可能ですが、前回同様Serverlessでデプロイしてみます。

ohke.hateblo.jp

serverless.templateのResources.Get.Properties.Environment.Variablesで、環境変数"ENV_NAME"に"test"という値で定義しています。

{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Transform" : "AWS::Serverless-2016-10-31",
  "Description" : "An AWS Serverless Application.",
  "Resources" : {
    "Get" : {
      "Type" : "AWS::Serverless::Function",
      "Properties": {
        "Handler": "AWSServerless::AWSServerless.Functions::Get",
        "Runtime": "dotnetcore1.0",
        "CodeUri": "",
        "MemorySize": 256,
        "Timeout": 30,
        "Role": null,
        "Policies": [ "AWSLambdaBasicExecutionRole" ],
        "Events": {
          "PutResource": {
            "Type": "Api",
            "Properties": {
              "Path": "/",
              "Method": "GET"
            }
          }
        },
        "Environment": {
          "Variables": {
            "ENV_NAME": "test"
          }
        }
      }
    }
  },
  "Outputs" : {
  }
}

これでAWS ExplorerからPublishして、AWSコンソールからデプロイしたLambdaを見ると環境変数が設定されていることを確認できます。 (Serverlessを使わない場合はこの画面から設定します。)

f:id:ohke:20170127223433j:plain

リリースしたURLにアクセスしてみると、"test"を取得できていることも確認できます。

f:id:ohke:20170127223539j:plain