AWS Systems Manager (SSM) Parameter Store In .NET 3.1 Web API

Introduction

This article will teach you how to access parameters from the AWS Systems Manager Parameter Store (SSM) in .NET Core 3.1 Web API. Parameter Store, a capability of AWS Systems Manager, provides secure, hierarchical storage for configuration data and secrets management. You can store data such as passwords, database strings, Amazon Machine Image (AMI) IDs, and license codes as parameter values. You can store values as plain text or encrypted data based on values stored in SSM Keys.

Topics Covered

This article demonstrates how to build the following,

  1. Create parameters in Parameter Store (SSM) using AWS Wizard/Console.
  2. Create a sample ASP.NET Core Web API
  3. Testing
  4. Clean up resources.

Pre-requisites

  1. Download and install Visual Studio 2022.
  2. Download and install AWS Toolkit for Visual Studio 2022.
  3. An Active AWS Account. (See AWS Account Page.)
  4. User with sufficient access to create AWS resources for this article. (See IAM role/Server Permission in AWS IAM Roles Documentation.)
  5. The user should have programmatic access keys. (See IAM user and Access in the AWS IAM documentation.)
  6. Download and install the Amazon command line interface (AWS CLI). Configure AWS CLI.

Tools

  1. AWS Console
  2. Visual Studio 2022

Task 1. Create parameters in the Parameter store using the Console

In this task, you will see how to create sample parameters using Console.

Step 1

Follow this link to create the parameters using Console.

Step 2

The following parameters are created for this article.

AWS Systems Manager (SSM) Parameter store in .NET 3.1 Web API

Task 2. Create a sample ASP.NET Core Web API

In this task, you will see how to create a new sample .NET 3.1 ASP.NET Core Web API using Visual Studio 2022.

Step 1

Open Visual Studio 2022, and click Create a new project.

Step 2

Search ASP.NET in the search bar, select ASP.NET Core Web API project template, and click Next.

AWS Systems Manager (SSM) Parameter store in .NET 3.1 Web API

Step 3

Enter the project name as AWSParametersStoreNETAPIDemoClick Next.

AWS Systems Manager (SSM) Parameter store in .NET 3.1 Web API

Step 4

Select .NET 3.1 as Framework. Click Create.

AWS Systems Manager (SSM) Parameter store in .NET 3.1 Web API

Step 5

Expand the Controller folder in the solution explorer, right-click WeatherForecastController.cs file, and click Delete. Right-click WeatherForecast.cs file and click Delete.

Step 6

Right-click the Controllers folder, click Add and then click Controller.

Step 7

Select API -> API Controller with read/write actions. Click Add.

AWS Systems Manager (SSM) Parameter store in .NET 3.1 Web API

Step 8

Leave the default name and click Add.

AWS Systems Manager (SSM) Parameter store in .NET 3.1 Web API

Step 9

Add Amazon.Extensions.Configuration.SystemsManager NuGet package.

AWS Systems Manager (SSM) Parameter store in .NET 3.1 Web API

Step 10

Create a static class with the name "ConfigurationExtensions".

Consider the namespaces.

using Amazon;
using Amazon.Extensions.NETCore.Setup;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;

Open ConfigurationExtensions.cs file and add the following code snippet as shown below. As you already created a custom class and added an extension method in IWebHostBuilder. We can call it directly in program.cs.

using Amazon;
using Amazon.Extensions.NETCore.Setup;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;

namespace AWSParametersStoreNETAPIDemo
{
    public static class ConfigurationExtensions
    {
        public static IConfiguration AppSetting { get; }
        static ConfigurationExtensions()
        {
            AppSetting = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .Build();
        }

        public static IWebHostBuilder UseDefaultSettings(this IWebHostBuilder builder)
        {
            var environmentName = "dev"; // AppSetting["ASPNETCORE_ENVIRONMENT"];
            builder.UseEnvironment(environmentName).ConfigureAppConfiguration((a, b) => a.ConfigureAppConfiguration(b));
            return builder;
        }
        public static IConfigurationBuilder UseDefaultSettingsConfigBuilder(this IConfigurationBuilder builder)
        {
            var environmentName = Environment.GetEnvironmentVariable("Development");
            builder.AddSystemsManager(source =>
            {
                source.AwsOptions = new AWSOptions()
                {
                    Region = RegionEndpoint.USEast1
                };
                source.Optional = true;
                source.Path = "wms_dev";
            });
            return builder;
        }
        
        private static void ConfigureAppConfiguration(this WebHostBuilderContext hostingContext, IConfigurationBuilder builder)
        {
            if (!hostingContext.HostingEnvironment.IsDevelopment())
            {
                builder.AddSystemsManager(configureSource =>
                {
                    var env = hostingContext.HostingEnvironment;
                    configureSource.Optional = true;
                    // Parameter Store prefix to pull configuration data from.
                    configureSource.Path = $"/{env.EnvironmentName}/{"wms"}/";

                    // Reload configuration data every 15 minutes.
                    configureSource.ReloadAfter = TimeSpan.FromMinutes(15);
                });
            }
        }
    }
}

Step 11

Open Program.cs file and add the following code snippet as shown below.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace AWSParametersStoreNETAPIDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseDefaultSettings()
                    .UseStartup<Startup>();
                });
    }
}

NOTE

The parameter name ("/dev/myapp") and RegionEndPoint should be coming from Environment variables (Region = RegionEndpoint.GetBySystemName("us-west-2")), or it should be dynamic instead of hard-code values in a production environment.

Step 12

Open ValuesController.cs file and replace the code with the following as shown below.

AWS Systems Manager (SSM) Parameter store in .NET 3.1 Web API

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
namespace AWSParametersStoreNETAPIDemo.Controllers {
    public class ValuesController: ControllerBase {
        private readonly IConfiguration _configuration;
        public ValuesController(IConfiguration configuration) {
            _configuration = configuration;
        }
        public IEnumerable < string > Get() {
            // Grab the value from SSM parmeters and use it through out the project using IConfiguration
            var connectionString = _configuration.GetValue < string > ("ConnectionString");
            var BucketName = _configuration.GetValue < string > ("BucketName");
            var EC2Name = _configuration.GetValue < string > ("EC2Name");
            return new string[] {
                connectionString,
                BucketName,
                EC2Name
            };
        }
    }
}

Task 3. Testing

In this task, you will see how to test the API to retrieve the values from the Parameter store.

Hit F5 to run the API locally, and Swagger will be displayed. Expand /api/values and click Try it out. Click Execute to get the response as shown below.

AWS Systems Manager (SSM) Parameter store in .NET 3.1 Web API

AWS Systems Manager (SSM) Parameter store in .NET 3.1 Web API

Task 4. Clean up resources

Delete all the resources to ensure you're not charged for any services you aren't using.

Summary

This article describes how to access all the parameters from AWS Systems Manager (SSM) Parameter store in .NET 3.1 Web API.