Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set & fetch Environment variable in AWS Lambda Project in C#

I have created AWS Lambda Project in C# (NOT Serverless Application)

enter image description here

I have defined a Environment variable in aws-lambda-tools-defaults.json as below

"environment-variables": {
 "my-api": "http://myapihost.com/api/attendance-backfill"
 }

In Function.cs, fetching the value as below

   var apiUrl = Environment.GetEnvironmentVariable("my-api").ToString();

but it always coming as null.

How do I set & fetch Environment variable?

Thanks!

As per comment.

launch-settings.json

Function.cs

like image 248
Kgn-web Avatar asked Feb 23 '19 16:02

Kgn-web


2 Answers

It's pretty close but after some digging around I found out how to actually set these for local runs using the Mock Lambda Test Tool. It is, in-fact, inside the launchSettings.json file. You want to drop the settings inside the Mock Lambda Test Tool section of the profiles node, not outside it.

{
 "profiles": {
  "Mock Lambda Test Tool": {
   "commandName": "Executable",
   "commandLineArgs": "--port 5050",
   "workingDirectory": ".\\bin\\Debug\\netcoreapp2.1",
   "executablePath": "C:\\Users\\%USERNAME%\\.dotnet\\tools\\dotnet-lambda-test-tool-2.1.exe",
   "environmentVariables": {
     "environment": "test"
   }
  }
 }
}
like image 167
Kneemin Avatar answered Oct 25 '22 22:10

Kneemin


  1. Setting Environment variables docs used

There are two places where you’ll need to set environment variables: development-time and deployment-time. To do this, open the launchSettings.json file from under the Properties folder in the Solution Explorer. Then add the following JSON property:

    "environmentVariables": {
      "my-api": "something"
    }

To set environment variables at deployment-time, you can add these to the aws-lambda-tools-defaults.json file. (Just remember to escape the double quote marks.)

    environment-variables, its format is: "<key1>=<value1>;<key2>=<value2>;".

In your case you should have

    "environment-variables" : "\"my-api\"=\"http://myapihost.com/api/attendance-backfill\";"
  1. Consuming/fetching the environment variables

    Consuming the environment variables as part of the Lambda function’s logic is done intuitively in the C# code, by using the System library aws blog:

    System.Environment.GetEnvironmentVariable(<key>);
    

    In your case you can use the following;

    var apiUrl = System.Environment.GetEnvironmentVariable("my-api");
    

In this document it is suggested that your approach for fetching environment variable is correct.

    var variableValue = Environment.GetEnvironmentVariable("nameOfVariable"); 
like image 40
marcincuber Avatar answered Oct 25 '22 20:10

marcincuber