27

When running a .net core 2.1 AWS Lambda function, it is simple to fetch an environment variable from the AWS Lambda Console in c# using:

var envVariable = Environment.GetEnvironmentVariable("myVariableName");

However, when running ASP.NET core 2.1 as a Serverless Application on AWS Lambda, this does not work (the above returns null).

I can set a local env variable in the launchSettings.json file, but I want to use the Env variable from the AWS Lambda console.

How can I access the AWS Lambda Env variable in ASP.NET Core 2.1?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Pete Lunenfeld
  • 1,557
  • 3
  • 19
  • 32

2 Answers2

38

How can I access the AWS Lambda Env variable in ASP.NET Core 2.1

You access it the same way you would as before.

var envVariable = Environment.GetEnvironmentVariable("myVariableName");

Ensure that the environment variable is set for the respective resource so that it is available when called.

Each resource would have an entry in the serverless.template file, which is the AWS CloudFormation template used to deploy functions.

Environment variable entries are found under the Resources:{ResourceName}:Properties:Environment:Variables JSON path in the file.

Example declaration

{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Transform" : "AWS::Serverless-2016-10-31",
  "Description" : "An AWS Serverless Application that uses the ASP.NET Core framework running in Amazon Lambda.",
  "Parameters" : {
  },
  "Conditions" : {
  },
  "Resources" : {
    "Get" : {
      "Type" : "AWS::Serverless::Function",
      "Properties": {
        "Handler": "TimeZoneService::TimeZoneService.LambdaEntryPoint::FunctionHandlerAsync",
        "Runtime": "dotnetcore1.0",
        "CodeUri": "",
        "MemorySize": 256,
        "Timeout": 60,
        "Role": null,
        "Policies": [ "AWSLambdaFullAccess" ],
        "Environment" : {
          "Variables" : {
            "myVariableName" : "my environment variable value"
          }
        },
        "Events": {
          "PutResource": {
            "Type": "Api",
            "Properties": {
              "Path": "/{proxy+}",
              "Method": "ANY"
            }
          }
        }
      }
    }
  },
  "Outputs" : {
  }
}

Reference Build and Test a Serverless Application with AWS Lambda

Reference Creating a Serverless Application with ASP.NET Core, AWS Lambda and AWS API Gateway

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • 2
    Don't forget that you can treat environment variables as a configuration source, and never use this syntax at all. – VeteranCoder Jan 11 '19 at 15:05
0

Try this:

public interface IEnviromentVariables {
    string getEnVariable(string variable);
}

public class EnviromentClass : IEnviromentVariables {
    public string getEnVariable(string variable) {
        return System.Environment.GetEnvironmentVariable(variable);
    }
}