I got an ASP.NET Core Web API project. For credentials, I created an .env file which is an embedded resource and has Copy always set (I've also tried Do not copy).
As that file contains sensitive data, it's gitignored:
# .env
ENV_VAR_1_NAME=ENV_VAR_1_VALUE
ENV_VAR_2_NAME=ENV_VAR_2_VALUE
# ...
Here is the code that loads the .env file content:
// EnvLoader.cs
public static class EnvLoader
{
public static void Load(string filePath)
{
if (!File.Exists(filePath)) throw new FileNotFoundException();
var rows = File.ReadAllLines(filePath);
foreach (string row in rows)
{
if (string.IsNullOrWhiteSpace(row) || row.StartsWith("#"))
return;
var parts = row.Split('=', 2);
if (parts.Length != 2)
return;
var name = parts[0].Trim();
var value = parts[1].Trim();
Environment.SetEnvironmentVariable(name, value);
}
}
}
And here is how I use it:
// Program.cs
// ...
#if DEBUG
EnvLoader.Load(".env");
#endif
// ...
To represent that sensitive data on server I set env vars manually. Now I set up GitLab Runner, and of course it do not find my .env file during build phase with error:
CSC : error CS1566: Error reading resource 'MyProject.API..env' --
'Could not find file
'/home/gitlab-runner/builds/.../MyProject.API/.env'.'
[/home/gitlab-runner/builds/.../MyProject.API/MyProject.API.csproj]
I have no idea how to set my project to omit .env file absence. Also I'm not sure wheither my approach is correct or not, but it worked fine until CI/CD. So I wonder how it's usually done
.env fileYou could update the implementation to perfect this, but the easiest solution is to just have an empty .env file in production.
It's a good idea to make development have the same logic as production. Skipping the file in production could introduce bugs, which would not occur in development and are only found after going live.
As you already filter lines with comments, don't make the file entirely empty, but leave a message to potential readers if they stumble upon this file.
.env
# .env is intentionally left blank in production