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
.envfile for production?