我如何得到环境变量从弹性豆到一个asp.net核心mvc应用程序?我已经添加了一个. eb扩展文件夹,其中包含app.config文件,如下所示:
option_settings:
- option_name: HelloWorld
value: placeholder
- option_name: ASPNETCORE_ENVIRONMENT
value: placeholder
. eb扩展文件夹包含在发布包中。
在部署时,这两个变量在配置的aws elasticbeanstatk控制台中都可见
但是,当我尝试读取应用程序中的变量时,以下选项均不起作用:
Environment.GetEnvironmentVariable("HelloWorld") // In controller
Configuration["HelloWorld"] // In startup.cs
知道我会错过什么吗?谢谢。
我刚刚实现了一个稍微不同的解决方案,它将beanstek环境变量注入到程序中,以便您可以通过环境访问它们。Get环境变量()
:
private static void SetEbConfig()
{
var tempConfigBuilder = new ConfigurationBuilder();
tempConfigBuilder.AddJsonFile(
@"C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration",
optional: true,
reloadOnChange: true
);
var configuration = tempConfigBuilder.Build();
var ebEnv =
configuration.GetSection("iis:env")
.GetChildren()
.Select(pair => pair.Value.Split(new[] { '=' }, 2))
.ToDictionary(keypair => keypair[0], keypair => keypair[1]);
foreach (var keyVal in ebEnv)
{
Environment.SetEnvironmentVariable(keyVal.Key, keyVal.Value);
}
}
只需在构建虚拟主机之前调用SetEbConfig();
。使用此解决方案,AWSSDK也可以正确读取AWS_ACCESS_KEY_ID等设置。
有同样的问题,刚刚收到AWS支持关于这个问题的回复。显然环境变量没有正确注入到弹性豆茎中的ASP.NET核心应用程序中。
据我所知,他们正在努力解决这个问题。
解决方法是将C:\Program Files\Amazon\ElasticBeanstik\config\容器配置
解析到配置生成器中。此文件是您的弹性beanstik环境的一部分,应该在部署项目时可以访问。
首先添加文件:
var builder = new ConfigurationBuilder()
.SetBasePath("C:\\Program Files\\Amazon\\ElasticBeanstalk\\config")
.AddJsonFile("containerconfiguration", optional: true, reloadOnChange: true);
然后访问值:
var env = Configuration.GetSection("iis:env").GetChildren();
foreach (var envKeyValue in env)
{
var splitKeyValue = envKeyValue.Value.Split('=');
var envKey = splitKeyValue[0];
var envValue = splitKeyValue[1];
if (envKey == "HelloWorld")
{
// use envValue here
}
}
由G. P.提供。来自亚马逊网络服务
我实现了另一个答案,以创建一个方便的解决方法,将Elastic Beanstik中的环境属性直接加载到您的ASP.NETCore应用程序配置中。
对于ASP.NETCore 2.0-编辑您的Program. cs
请注意,此WebHost构建取自WebHostBuilder. CreateDefaultBuilder()的源代码
https://github.com/aspnet/MetaPackages/blob/dev/src/Microsoft.AspNetCore/WebHost.cs
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace NightSpotAdm
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args)
{
// TEMP CONFIG BUILDER TO GET THE VALUES IN THE ELASTIC BEANSTALK CONFIG
IConfigurationBuilder tempConfigBuilder = new ConfigurationBuilder();
tempConfigBuilder.AddJsonFile(
@"C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration",
optional: true,
reloadOnChange: true
);
IConfigurationRoot tempConfig = tempConfigBuilder.Build();
Dictionary<string, string> ebConfig = ElasticBeanstalk.GetConfig(tempConfig);
// START WEB HOST BUILDER
IWebHostBuilder builder = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory());
// CHECK IF EBCONFIG HAS ENVIRONMENT KEY IN IT
// IF SO THEN CHANGE THE BUILDERS ENVIRONMENT
const string envKey = "ASPNETCORE_ENVIRONMENT";
if (ebConfig.ContainsKey(envKey))
{
string ebEnvironment = ebConfig[envKey];
builder.UseEnvironment(ebEnvironment);
}
// CONTINUE WITH WEB HOST BUILDER AS NORMAL
builder.ConfigureAppConfiguration((hostingContext, config) =>
{
IHostingEnvironment env = hostingContext.HostingEnvironment;
// ADD THE ELASTIC BEANSTALK CONFIG DICTIONARY
config.AddJsonFile(
"appsettings.json",
optional: true,
reloadOnChange: true
)
.AddJsonFile(
$"appsettings.{env.EnvironmentName}.json",
optional: true,
reloadOnChange: true
)
.AddInMemoryCollection(ebConfig);
if (env.IsDevelopment())
{
Assembly appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseIISIntegration()
.UseDefaultServiceProvider(
(context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); })
.ConfigureServices(
services =>
{
services.AddTransient<IConfigureOptions<KestrelServerOptions>, KestrelServerOptionsSetup>();
});
return builder.UseStartup<Startup>().Build();
}
}
public static class ElasticBeanstalk
{
public static Dictionary<string, string> GetConfig(IConfiguration configuration)
{
return
configuration.GetSection("iis:env")
.GetChildren()
.Select(pair => pair.Value.Split(new[] { '=' }, 2))
.ToDictionary(keypair => keypair[0], keypair => keypair[1]);
}
}
}
ASP.NET核心1.0
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddJsonFile(@"C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
var config = builder.Build();
builder.AddInMemoryCollection(GetEbConfig(config));
Configuration = builder.Build();
}
private static Dictionary<string, string> GetEbConfig(IConfiguration configuration)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (IConfigurationSection pair in configuration.GetSection("iis:env").GetChildren())
{
string[] keypair = pair.Value.Split(new [] {'='}, 2);
dict.Add(keypair[0], keypair[1]);
}
return dict;
}