敏感和运行时环境特定数据可以从环境变量中读取,AWS Lambda 支持它。
您可以通过配置文件和变量 (example) 轻松实现 serverless framework。
归根结底就是简单的命令:
$ serverless deploy --stage Prod //使用指定的配置文件设置环境变量
$ serverless deploy --stage Dev
它的作用是在部署时根据 cli 选项设置环境变量。因此,在您的代码中,您从环境变量中读取 ConnectionString。
您也可以在没有无服务器框架的情况下实现这一目标。
为此,您必须在部署时自己定义环境变量,或者在 AWS 控制台中的 Lambda 函数上硬编码(您知道它是 Prod 或 Dev 或...)。
然后你必须像Environment.GetEnvironmentVariable("ConnectionString")一样直接在你的应用程序中阅读它
而不是直接阅读我选择做的事情是使用 Microsoft Extensions 之类的方法来引导我的功能。
IConfigurationRoot configuration = GetConfiguration();
// Read values from appsettings{Env}.json file.
var connString = configuration.GetSection("ConnectionStringField"))
private static IConfigurationRoot GetConfiguration()
{
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
Console.WriteLine("EnvironmentName: " + environmentName);
return new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory() + "/AppSettings")
.AddJsonFile($"appsettings.json", optional: true)
.AddJsonFile($"appsettings.{environmentName}.json", optional: true)
.Build();
}
所以我在同一个项目中为每个阶段(产品、开发...)保留单独的文件。在运行时从相应的 json 文件中读取敏感数据。
您可以更多地了解如何在 .net 核心上进行更好的 DependecyInjection 和配置。 Example1,Example2