ASP.NET Core 1.0中的AWS Elastic Beanstalk环境变量

时间:2016-10-19 09:42:46

标签: asp.net-mvc asp.net-core environment-variables elastic-beanstalk asp.net-core-1.0

如何将弹性beanstalk中的环境变量导入asp.net核心mvc应用程序?我在其中添加了一个带有app.config文件的.ebextensions文件夹,其中包含以下内容:

option_settings:
- option_name: HelloWorld
  value: placeholder

- option_name: ASPNETCORE_ENVIRONMENT
  value: placeholder

.ebextensions文件夹包含在发布包中。

在部署时,两个变量在配置>的aws elasticbeanstalk控制台中可见。软件配置>环境变量

但是,当我尝试读取应用程序中的变量时,以下选项均无效:

Environment.GetEnvironmentVariable("HelloWorld") // In controller
Configuration["HelloWorld"] // In startup.cs

关于我可能遗失的任何想法?感谢。

9 个答案:

答案 0 :(得分:23)

我刚刚实现了一个稍微其他的解决方案,它将beanstalk环境变量注入到程序中,以便您可以通过Environment.GetEnvironmentVariable()访问它们:

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();即可。通过此解决方案,AWS SDK也可以正确读取AWS_ACCESS_KEY_ID等设置。

答案 1 :(得分:19)

遇到同样的问题,刚收到AWS支持人员对此问题的回复。显然,环境变量没有在弹性beanstalk中正确地注入ASP.NET Core应用程序。

据我所知,他们正在努力解决问题。

解决方法是将C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration解析为配置构建器。此文件是弹性beanstalk环境的一部分,在部署项目时应该可以访问。

首先添加文件:

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。来自 亚马逊网络服务

答案 2 :(得分:7)

我实现了另一个答案,以创建一个方便的解决方法,将环境属性从Elastic Beanstalk直接加载到ASP.NET Core应用程序配置中。

对于ASP.NET Core 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 Core 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;
    }

答案 3 :(得分:3)

AWS在2020年6月29日发布的Elastic Beanstalk Windows Server平台更新中解决了此问题:

以前,Elastic Beanstalk不支持将环境变量传递给使用部署清单[1]的.NET Core应用程序和多应用程序IIS部署。 2020年6月29日更新的Elastic Beanstalk Windows Server平台[2]现在可以解决此问题。有关详细信息,请参阅在Elastic Beanstalk控制台[3]中配置.NET环境。

[1] https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/dotnet-manifest.html

[2] https://docs.aws.amazon.com/elasticbeanstalk/latest/relnotes/release-2020-06-29-windows.html

[3] https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_NET.container.console.html#dotnet-console

答案 4 :(得分:2)

以上解决方案并没有帮助我根据环境设置加载配置文件。所以这是我的解决方案AWS ElasticBeansTalk“hack”

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{GetEnvVariableAWSBeansTalkHack(env)}.json", optional: true)
            .AddEnvironmentVariables();

        Configuration = builder.Build();
    }

    private static string GetEnvVariableAWSBeansTalkHack(IHostingEnvironment env)
    {
        var config = new ConfigurationBuilder()
           .AddJsonFile(@"C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration", optional: true, reloadOnChange: true).Build();

        Dictionary<string, string> dict = new Dictionary<string, string>();
        foreach (IConfigurationSection pair in config.GetSection("iis:env").GetChildren())
        {
            string[] keypair = pair.Value.Split(new[] { '=' }, 2);
            dict.Add(keypair[0], keypair[1]);
        }

        return dict.ContainsKey("ASPNETCORE_ENVIRONMENT") 
                ? dict["ASPNETCORE_ENVIRONMENT"] 
                : env.EnvironmentName;
    }

答案 5 :(得分:2)

您无需解析containerconfiguration,而是可以利用ebextensions options将变量设置为部署过程的一部分:

commands:
  set_environment: 
    command: setx ASPNETCORE_ENVIRONMENT "Development" /M

这将在应用程序部署中设置全局环境变量。这个变量用例由Microsoft官方支持和documented

部署应用后,您可以验证在EC2实例中是否正确设置了设置:

environment variable

答案 6 :(得分:1)

.NET Core 2 + posrgresql RDS

继上面@ sebastian的答案之后,我发现设置在文件的不同部分,即。 plugins:rds:env

此外,无需拆分=,因此我的解析代码是:

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("plugins:rds:env")
                                        .GetChildren()
                                        .ToDictionary(child => child.Key, child => child.Value);

            foreach (var keyVal in ebEnv)
            {
                Environment.SetEnvironmentVariable(keyVal.Key, keyVal.Value);
            }
        }

相关(和编辑;-))JSON如下:

{
    "plugins": {
        "rds": {
            "Description": "RDS Environment variables",
            "env": {
                "RDS_PORT": "....",
                "RDS_HOSTNAME": "....",
                "RDS_USERNAME": "....",
                "RDS_DB_NAME": "....",
                "RDS_PASSWORD": "...."
            }
        }
    }
}

(这个回复是独立的,因为我没有回复评论......)

答案 7 :(得分:0)

您可以创建Microsoft.Extensions.Configuration

的实现

也可在https://gist.github.com/skarllot/11e94ed8901a9ddabdf05c0e5c08dbc5处找到。

using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Linq;

namespace Microsoft.Extensions.Configuration.AWS
{
    public class AmazonEBConfigurationProvider : ConfigurationProvider
    {
        private const string ConfigurationFilename = @"C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration";

        public override void Load()
        {
            if (!File.Exists(ConfigurationFilename))
                return;

            string configJson;
            try
            {
                configJson = File.ReadAllText(ConfigurationFilename);
            }
            catch
            {
                return;
            }

            var config = JObject.Parse(configJson);
            var env = (JArray)config["iis"]["env"];

            if (env.Count == 0)
                return;

            foreach (var item in env.Select(i => (string)i))
            {
                int eqIndex = item.IndexOf('=');
                Data[item.Substring(0, eqIndex)] = item.Substring(eqIndex + 1);
            }
        }
    }

    public class AmazonEBConfigurationSource : IConfigurationSource
    {
        public IConfigurationProvider Build(IConfigurationBuilder builder)
        {
            return new AmazonEBConfigurationProvider();
        }
    }

    public static class AmazonEBExtensions
    {
        public static IConfigurationBuilder AddAmazonElasticBeanstalk(this IConfigurationBuilder configurationBuilder)
        {
            configurationBuilder.Add(new AmazonEBConfigurationSource());
            return configurationBuilder;
        }
    }
}

然后使用ConfigurationBuilder

var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", true, true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
    .AddAmazonElasticBeanstalk()    // <-- Merge with other sources
    .AddEnvironmentVariables();

答案 8 :(得分:0)

这绝对可以在.ebextensions文件夹中完成。只需在.ebextensions文件夹中创建一个新文件(我使用的名称为“ options.config”),将其标记为“如果较新则复制”或“始终复制”,并确保将option_settings标头与aws:elasticbeanstalk:application:environment命名空间:

option_settings:
  aws:elasticbeanstalk:application:environment:
    MyEnvVar: SomeValue

编辑:我忘了包括文档链接! https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-softwaresettings.html