Access Lambda environment variables from .env file - c#

I am running .net core 3.1 AWS Lambda function but I am unable to access the environment variable from the AWS Lambda Console in c# using:
var envVariable = Environment.GetEnvironmentVariable("myVariableName");
The environment variables are stored in a .env file in the root of my lambda function. Does the .env file need to be copied into the build folder for it to be accessible in the lambda function?. How can I access the AWS Lambda environment variable from the .env file?
Application Structure
cloudformation-template.json refers to .env file.
update: 5/31/2020:
I removed the .env file and added the variables in the cloudformation-template.json directly as individual variables. When I try to push the same to aws using amplify publish command, I get a
Resource is not in the state stackUpdateComplete
An error occured during the push operation: Resource is not in the state stackUpdateComplete error

I am able to solve this issue by adding environment variables directly to the cloudformation-template.json and running the amplify publish command to push to aws.
"Environment": {
"Variables": {
"VUE_APP_STRIPE_PUBLISHABLE_KEY": "<someRandomString>",
"VUE_APP_STRIPE_SECRET_KEY": "<someRandomString>"
}
},

Related

Visual Studio 2022 System.Environment.GetEnvironmentVariable not working

I know this is still in preview, but I just want to make sure I am not doing anything wrong as I have done things like this in the past. I have my Environment variables set in properties:
And I am trying to set up my tests:
[TestInitialize]
public void Initialize()
{
var test = Environment.GetEnvironmentVariables();
// test enumerates all the Env variables, don't see it there
var connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING");
if (string.IsNullOrWhiteSpace(connectionString)) // so this is obviously null
throw new ArgumentNullException("CONNECTION_STRING");
_ConnectionString = connectionString;
}
As you can see by my comments, the environment variables are not found/loaded.
What am I missing? Thank you.
I'm assuming that you are using Visual Studio 2022 because you are using .NET 6 and the minimal host (i.e., no Startup.cs)?
The general preference is not to store information in the Environment Variables given that this information is often uploaded to GitHub and can be trawled and used against you.
For a local development secret, the preference is to store these using the secrets.json file. There is information on how to do this at Safe Storage of Secrets, as well as details on accessing Configuration files at Accessing Configuration File Information.
For the TL;DR: Crowd the steps below might help (this is what I did in my Blazor app with .NET 6):
In Visual Studio 2022, right click on the project in question and select 'Manage User Secrets'. This will create a local secrets.json file and open it. It will also add a GUID in your project tile for UserSecretsId.
Create your secrets as JSON key value pairs in this file as you would for environment variables.
Go to 'Connected Services' in your project and configure the Secrets.json service.
Add the 'User Secrets' to your configuration file; this will depend on exactly where this is happening.
Inject the IConfiguration into your controller and save this to a field.
Call the data you want using:
{yourConfigurationFieldName}.GetValue<string>({yourJsonKey})
In Visual Studio 2022, you can access environment variables in development by modifying the following section of launchSettings.json file.
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"VaultUri": "https://xxx.vault.azure.net/",
"AZURE_USERNAME": "xxx#user.com"
}
where VaultUri is the name of your environment variable.

How can I get access to my docker containers environment variables in .Net Core?

I am trying to get access to some docker environment variables in my C# code running on .Net Core.
In my dockerfile generated by VS, I added environment variables like this:
ENV EnvKey = "value"
After building this image and starting the instance with the built-in Docker startup option in VS, I inspect my docker image with docker inspect MyInstance.
The resulting output lists my previously defined environment variable in "Config" -> "Env" -> "EnvKey", so I'm sure it is there.
For some testing, I try to access them with the following code:
var keys = Environment.GetEnvironmentVariables();
However, this does not retrieve the environment variable that is contained in the container.
What else do I need to configure to get this working?
The problem was very simple actually - In my case, this wasn't visible from the question.
But my real environment variable key had some "." in it. I replaced those with "_" and now it works perfectly.
If you are running an ASP.NET application, then updating the Dockerfile to ENV ASPNETCORE_EnvKey = "value" should do the trick for you.
If you are running some other .NET core app on your machine, then look at the docs here. It would seem you can't do this on the machine level, but in your RUN command, you would have to pass the 'environment variables' to the process through the dotnet command you are invoking there.

Lambda An error occurred while attempting to execute your code

I am using AWS Lambda toolkit for C#. When I am publishing AWS Lambda directly it is working fine on AWS. But when I am trying to make a zip file by using publish and then making the zip of all DLL under bin\Release\netcoreapp1.0. and trying to run.
Then it is giving an error:
{
"errorType": "LambdaException",
"errorMessage": "An error occurred while attempting to execute your code."
}
In configuration Handler name is correct.
What can be the issue?
Have you tried packing the zip using the dotnet cli command?
Try this in your project folder: dotnet lambda package -o .\lambda.zip
It should create a lambda.zip file which you can try to upload.

Bulk AWS Lambda Upload from Visual Studio

Using the AWS tool plugin for Visual Studio, how do you do a bulk upload of Lambda functions to AWS?
I have a project that contains two functions that define separate lambda functions. The context menu for AWS Lambda seems to only allow for publishing one function at a time. As you can imagine, that is a bit of a maintainability nightmare.
The json config file that it generates does not have any answers either as it seems to be pretty flat and only allows a single function at a time:
"region" : "us-west-2",
"configuration" : "Release",
"framework" : "netcoreapp1.0",
"function-runtime" : "dotnetcore1.0",
"function-memory-size" : 256,
"function-timeout" : 5,
"function-handler" : "LambdaSamples::LambdaSamples.SampleFunction::HelloWorld",
"function-name" : "HelloWorld",
"function-role" : "lambda_basic_execution",
"environment-variables" : ""
The Visual Studio project called "AWS Lambda Project" is designed for single Lambda functions.
So if your solution has multiple projects, and you want to deploy them all at once, you're best off doing it by script/command line.
The Readme.md file generated by the new project wizard has instructions on deploying by command line using dotnet lambda deploy-function.
I generally create an options file for each type of release that I want, like this (the new file is aws-options-live.json and has a specific name / env variables pertaining to my live environment):
And then use the following in a batch file in a Deploy folder off of the main solution folder:
echo off
cd ..\ApiGatewayLambda
dotnet lambda deploy-function -cfg aws-options-live.json
set /p asd="Hit enter to continue"
You can then get as clever as you want to with linking multiple uploads together / error checking etc.
You can still right click on the project and choose Public to AWS Lambda - it will use the aws-lambda-tools-defaults.json file to publish the function.

Use environment appsettings.{Environment}.json vs hardcoding in file name or db connection details in CreateHostBuilder method?

Using ef core it's possible to get everything working and run the dotnet ef migrations command line tool but Program.cs required the method
public static IHostBuilder CreateHostBuilder(string[] args)
The only thing that isn't ideal is storing database settings in a development json file then having to hardcode the development json file name in that method or hardcoding the db connection details into that method. When checking
context.HostingEnvironment.IsDevelopment() //always returns false
it is never correct or doesn't get set properly so we can't use context.HostingEnvironment.EnvironmentName as a variable either. Is there a way in the CreateHostBuilder method to load the proper app settings json file and configure/setup the environment for running the ef migrations command line tools vs hardcoding?
Yes, you have a few options to setup the Hosting Environment.
You can set a value of the DOTNET_ENVIRONMENT environment variable. This applies to all types of apps. Or you can setup ASPNETCORE_ENVIRONMENT environment variable, as this overrides the DOTNET_ENVIRONMENT when .ConfigureWebHostDefaults is called.
Another options is to set the ASPNETCORE_ENVIRONMENT value in the launchSetting.json of your project.
While you can give any value to those environment variables, the framework provides the following values: "Development", "Staging", and "Production".
You can find more information about this in the Use Multiple Environments in ASP.NET Core docs.

Categories