C# – .NET Core AWS RDS CONNECTION

.net coreamazon-rdsamazon-web-servicesasp.net-core-webapic

I am creating a .NET Core Web API on Amazons AWS, Elastic Beanstalk.
I am trying to add a database, but their guide to add a database does not work for .Net Core
http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_NET.rds.html

It says to get the relevant information using "ConfigurationManager.AppSettings;", but this is not possible in .NET Core.

Can anybody give some inforamtion about how to get the database informations?
(
"RDS_DB_NAME"
"RDS_USERNAME"
"RDS_PASSWORD"
"RDS_HOSTNAME"
)

UPDATE
I tried to read on https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration
But I have not resolved the problem. I still cannot seem to get the values from AWS.

It just returns whatever I set in my own appsettings.json
Here is my code:
MyOptions.cs

public class MyOptions
{
    public MyOptions()
    {
        // Set default value.
    }
    public string RDS_HOSTNAME { get; set; }
    public string RDS_PORT { get; set; }
    public string RDS_DB_NAME { get; set; }
    public string RDS_USERNAME { get; set; }
    public string RDS_PASSWORD { get; set; }
}

StartUp.cs

public void ConfigureServices(IServiceCollection services)
{
    // Register the IConfiguration instance which MyOptions binds against.
    services.Configure<MyOptions>(Configuration);
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddMvc();
}

HomeController.cs

namespace WebApplication2.Controllers
{
    [Route("")]
    public class HomeController : Controller
    {
        private readonly MyOptions _options;

        public HomeController(IOptions<MyOptions> optionsAccessor)
        {
            _options = optionsAccessor.Value;
        }

        [HttpGet]
        public IActionResult Index()
        {
            var RDS_DB_NAME = _options.RDS_DB_NAME;
            var RDS_HOSTNAME = _options.RDS_HOSTNAME;
            var RDS_PASSWORD = _options.RDS_PASSWORD;
            var RDS_PORT = _options.RDS_PORT;
            var RDS_USERNAME = _options.RDS_USERNAME;
            return Content($"RDS_DB_NAME = {RDS_DB_NAME}, RDS_HOSTNAME = {RDS_HOSTNAME}, RDS_PASSWORD = { RDS_PASSWORD}, RDS_PORT = {RDS_PORT}, RDS_USERNAME = { RDS_USERNAME}");
        }
    }
}

Best Answer

I ran into this exact problem and it was MUCH more complicated than I anticipated.

Step 1 - I modified this answer from another Stack Overflow question. My code in Startup.cs looked like this:

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, reloadOnChange: true)
        .AddJsonFile(@"C:\Program Files\Amazon\ElasticBeanstalk\config\containerconfiguration", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();

    // This adds EB environment variables.
    builder.AddInMemoryCollection(GetAwsDbConfig(builder.Build()));

    Configuration = builder.Build();
}

private Dictionary<string, string> GetAwsDbConfig(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;
    }

private string GetRdsConnectionString()
{
    string hostname = Configuration.GetValue<string>("RDS_HOSTNAME");
    string port = Configuration.GetValue<string>("RDS_PORT");
    string dbname = Configuration.GetValue<string>("RDS_DB_NAME");
    string username = Configuration.GetValue<string>("RDS_USERNAME");
    string password = Configuration.GetValue<string>("RDS_PASSWORD");

    return $"Data Source={hostname},{port};Initial Catalog={dbname};User ID={username};Password={password};";
}

Step 2 - You will need to go to the RDS Service in the AWS Console. Select the Instance that you want to connect to -> Instance Actions -> See Details. You will be able to find RDS_HOSTNAME (endpoint) and RDS_PORT (port).

RDS_DB_NAME is the Database name that your code is meant to work with.

RDS_USERNAME and RDS_PASSWORD are the master usernames and passwords you used when creating the database in Elastic Beanstalk. If you go to Elastic Beanstalk -> Configuration -> Data Tier -> (Click on the Gear) you see your Master username and have the option to change your Password if you have forgotten it.

Step 3 - Now that you have all the data, you will have to enter these options as Environmental Properties in Elastic Beanstalk. Go to Elastic Beanstalk -> Software Configuration -> (Click on the Gear). At the bottom of this page are the Environment Properties. Here is where you will want to enter the names in your code from step one and the values from RDS in step two.

For more information on this from AWS documentation check here and here.