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

Gir*_*ish 35 asp.net-mvc environment-variables amazon-elastic-beanstalk asp.net-core 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
Run Code Online (Sandbox Code Playgroud)

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

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

但是,当我尝试读取应用程序中的变量时,以下选项都不起作用:

Environment.GetEnvironmentVariable("HelloWorld") // In controller
Configuration["HelloWorld"] // In startup.cs
Run Code Online (Sandbox Code Playgroud)

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

Seb*_*ian 34

我刚刚实现了一个稍微的其他解决方案,它将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);
    }
}
Run Code Online (Sandbox Code Playgroud)

SetEbConfig();在构建您的webhost之前,只需致电.通过此解决方案,AWS SDK也可以正确读取AWS_ACCESS_KEY_ID等设置.

  • 显然Elastic Beanstalk问题尚未解决.您的解决方案非常有助于我的代码部署并快速运行! (4认同)
  • 非常感谢,这是最通用和优雅的解决方案! (2认同)
  • 在浪费了大量时间寻找修复后,我找到了解决方案,我很高兴找到它.将自定义变量(如ASPNETCORE_ENVIRONMENT)插入到实例的环境属性中非常有用.非常感谢. (2认同)
  • 2019年7月中旬...这仍然是必需的。在program.cs中,调用SetEbConfig(); 在Main()中,在CreateWebHostBuilder(args).Build()。Run();之前)。 (2认同)

小智 23

有同样的问题,刚收到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);
Run Code Online (Sandbox Code Playgroud)

然后访问值:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

由Amazon Web Services 提供 GP

  • 事实上这是必要的,这是荒谬的,尽管亚马逊声称支持ASP.NET Core,但它应该让AWS(我通常喜欢并尊重他们)在ASP.NET Core 1.0发布12个月之后仍然没有固定. Elastic Beanstalk并提供有关如何在其中部署它的教程](http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/dotnet-core-tutorial.html).这是*基本*功能,可能在几天内由实习生修复,并且它显示了相当令人震惊的服务质量,它只能被打破一年.至少,这个答案至少有效; +1. (23认同)
  • 现在已经是 2019 年 8 月下旬了,这个问题仍然存在。我想这是一个永久性的“修复”,AWS 不关心解决这个问题。 (3认同)

Arc*_*ade 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]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对于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;
    }
Run Code Online (Sandbox Code Playgroud)


Jus*_*son 5

containerconfiguration您可以利用ebextensions 选项将变量设置为部署过程的一部分,而不必解析:

commands:
  set_environment: 
    command: setx ASPNETCORE_ENVIRONMENT "Development" /M
Run Code Online (Sandbox Code Playgroud)

这将设置一个全局环境变量作为应用程序部署的一部分。Microsoft正式支持并记录了此可变用例。

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

环境变量