AWS Elastic Beanstalk environment variables in ASP.NET Core 1.0

后端 未结 9 2004
误落风尘
误落风尘 2020-12-01 02:59

How do I get environment variables from elastic beanstalk into an asp.net core mvc application? I have added a .ebextensions folder with app.config file in it with the follo

相关标签:
9条回答
  • 2020-12-01 03:28

    I implemented the other answer to create a convenient workaround to load the environment properties from Elastic Beanstalk directly into your ASP.NET Core app configuration.

    For ASP.NET Core 2.0 - edit your Program.cs

    Note that this WebHost build was taken from the source code of 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]);
            }
        }
    }
    

    For 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;
        }
    
    0 讨论(0)
  • 2020-12-01 03:32

    AWS addressed this issue in the Elastic Beanstalk Windows Server platform update on June 29, 2020:

    Previously, Elastic Beanstalk didn't support passing environment variables to .NET Core applications and multiple-application IIS deployments that use a deployment manifest [1]. The Elastic Beanstalk Windows Server platform update on June 29, 2020 [2] now fixes this gap. For details, see Configuring your .NET environment in the Elastic Beanstalk console [3].

    [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

    0 讨论(0)
  • 2020-12-01 03:34

    This can definitely be done in an .ebextensions folder. Simply create a new file in your .ebextensions folder (I used a name of "options.config"), mark it as "copy if newer" or "copy always" and make sure you use the option_settings header with a aws:elasticbeanstalk:application:environment namespace:

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

    EDIT: I forgot to include a link to the docs! https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-softwaresettings.html

    0 讨论(0)
提交回复
热议问题