Using Environment Variables with .NET Lambda Functions

Using environment variables in your .NET Lambda functions is a great way to store some simple configuration info. They are easy to create, update and use. In this post, I’ll show you how to use environment variables in your .NET Lambda functions.

1. Get the tools

See this post for how to get all the tools you need.

2. Create the Lambda function

From the command line, create a new Lambda function using the -

dotnet new lambda.EmptyTopLevelFunction -n LambdaEnvVariables

3. Update the function

Change to the LambdaEnvVariables/src/LambdaEnvVariables directory.

Update the handler code to the following -

var handler = (ILambdaContext context) =>
{
    string myVariable = Environment.GetEnvironmentVariable("MyVariable");
    return $"Hello World {myVariable}";
};

I removed the string parameter to the function and added a line to get the environment variable.

4. Deploy the function

Deploy the function using the following command -

dotnet lambda deploy-function LambdaEnvVariables

You will be asked to select an IAM role, or create a new one, at the bottom of the list will be *** Create new IAM Role ***, type in the associated number.

You will be asked for a role name, enter LambdaEnvVariablesRole.

After this you will be prompted to select the IAM Policy to attach to the role, choose AWSLambdaBasicExecutionRole, it is number 6 on my list.

After a few seconds, the function will be deployed.

5. Set the environment variable for the Lambda function

From the command line run -

aws lambda update-function-configuration --function-name LambdaEnvVariables --environment "Variables={MyVariable=xyz}"

You can set multiple variables by separating them with a comma, e.g. --environment "Variables={MyVariable=xyz,Hello=world}". You can clear the environment variables by sending an empty list - --environment "Variables={}"

6. Invoke the function

To invoke the Lambda function, run -

dotnet lambda invoke-function LambdaEnvVariables

You should see output like -

Amazon Lambda Tools for .NET Core applications (5.4.5)
Project Home: https://github.com/aws/aws-extensions-for-dotnet-cli, https://github.com/aws/aws-lambda-dotnet

Payload:
"Hello World xyz"

Log Tail:
START RequestId: 53d0db6b-b1c9-4e75-8559-59b8f121e170 Version: $LATEST
END RequestId: 53d0db6b-b1c9-4e75-8559-59b8f121e170
REPORT RequestId: 53d0db6b-b1c9-4e75-8559-59b8f121e170  Duration: 175.02 ms     Billed Duration: 176 ms Memory Size: 256 MB     Max Memory Used: 55 MB  Init Duration: 181.52 ms
comments powered by Disqus

Related