18

Làm thế nào để tôi nhận được biến môi trường từ beanstalk đàn hồi vào ứng dụng mvc lõi asp.net? Tôi đã thêm một thư mục .ebextensions với tệp app.config trong đó với các thông tin sau:AWS biến môi trường Beanst Elastic trong ASP.NET Core 1.0

option_settings: 
- option_name: HelloWorld 
    value: placeholder 

- option_name: ASPNETCORE_ENVIRONMENT 
    value: placeholder 

Thư mục .ebextensions được bao gồm trong gói xuất bản.

On triển khai, cả hai biến có thể nhìn thấy trong AWS elasticbeanstalk console tại Configuration> Cấu hình phần mềm> Environment Variables

Tuy nhiên, khi tôi cố gắng đọc các biến trong ứng dụng, không ai trong số các tùy chọn bên dưới đang làm việc:

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

Bất kỳ ý tưởng nào về những gì tôi có thể bị thiếu? Cảm ơn.

+0

Dường như cùng một vấn đề khi triển khai ứng dụng .NET Standard sử dụng 'aws-windows-deployment-manifest.json': https://serverfault.com/questions/892493/windows-custom-elastic-beanstalk-deployment -missing-environment-variables – andrewf

Trả lời

13

Có cùng sự cố và chỉ nhận được trả lời từ AWS về sự cố này. Rõ ràng các biến môi trường không được tiêm đúng vào các ứng dụng ASP.NET Core trong beanstalk đàn hồi.

Theo như tôi biết, họ đang nỗ lực khắc phục sự cố.

Giải pháp thay thế là phân tích cú pháp C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration vào trình tạo cấu hình. Tệp này là một phần của môi trường beanstalk đàn hồi của bạn và sẽ có thể truy cập được khi triển khai dự án của bạn.

Đầu tiên thêm các tập tin:

var builder = new ConfigurationBuilder() 
    .SetBasePath("C:\\Program Files\\Amazon\\ElasticBeanstalk\\config") 
    .AddJsonFile("containerconfiguration", optional: true, reloadOnChange: true); 

Sau đó truy cập vào các giá trị:

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 
    } 
} 

Courtesy of G.P. từ Dịch vụ trang web của Amazon

+0

Tính đến hôm nay lỗi này vẫn còn hiện diện. Sử dụng cách này, bạn có thể thực hiện 'ConfigurationProvider' của riêng bạn và làm việc xung quanh vấn đề. – Gabriel

+0

Một điều cần lưu ý là các phương thức tiện ích trong Amazon.Extensions.NETCore.Setup bỏ qua Cấu hình và cố gắng đọc trực tiếp từ Môi trường. Bạn sẽ phải tự thêm AWSCredentials, RegionEndpoint và bất kỳ dịch vụ nào mà bạn đang sử dụng làm đơn. – JeffreyABecker

+8

Thực tế là điều này là cần thiết là lố bịch, và nó sẽ xấu hổ AWS (người mà tôi thường thích và tôn trọng) rằng nó vẫn không bị đóng băng, 12 tháng sau khi phát hành ASP.NET Core 1.0, mặc dù Amazon [yêu cầu hỗ trợ ASP.NET Core trên Cây đậu đàn hồi và cung cấp hướng dẫn về cách triển khai nó ở đó] (http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/dotnet-core-tutorial.html). Đây là chức năng * cơ bản *, có thể sửa chữa trong một vài ngày bởi một thực tập sinh, và nó cho thấy chất lượng dịch vụ khá kinh khủng cho nó chỉ để lại bị hỏng trong một năm. Tuy nhiên, ít nhất câu trả lời này hoạt động; +1. –

5

Tôi đã thực hiện câu trả lời khác để tạo giải pháp thuận tiện để tải các thuộc tính môi trường từ Cây đậu đàn hồi trực tiếp vào cấu hình ứng dụng ASP.NET Core của bạn.

Đối với ASP.NET Lõi 2.0 - chỉnh sửa Program.cs bạn

Lưu ý rằng WebHost build này được lấy từ mã nguồn của 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]); 
     } 
    } 
} 

Đối 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; 
    } 
1

Trên solu tion không giúp tôi tải tệp cấu hình dựa trên cài đặt môi trường. Vì vậy, đây là giải pháp của tôi 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; 
    } 
-1

Bạn có thể tạo triển khai Microsoft.Extensions.Configuration.

Cũng có sẵn tại 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; 
     } 
    } 
} 

Sau đó sử dụng với ConfigurationBuilder của bạn:

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

tôi chỉ thực hiện một giải pháp hơi khác mà tiêm nhiễm các biến môi trường cây đậu vào chương trình để bạn có thể truy cập chúng bằng 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); 
    } 
} 

Chỉ cần gọi SetEbConfig(); trước khi tạo webhost của bạn. Với giải pháp này, AWS SDK cũng đọc chính xác các cài đặt của nó như AWS_ACCESS_KEY_ID.

+0

Rõ ràng vấn đề Cây đậu đàn hồi chưa được khắc phục. Giải pháp của bạn cực kỳ hữu ích để mã của tôi được triển khai và hoạt động nhanh chóng! – victorvartan

Các vấn đề liên quan