07 best practices when using AWS SSM Parameter Store
Tags: security, serverless, aws, ssm
Published: 2019-11-21 03:28:41

This post appears first on [our blog](https://innomizetech.com/blog/07-best-practices-when-using-aws-ssm-parameter-store).

<!-- wp:image {"align":"center","id":556,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large"><img src="https://blog.innomizetech.com/wp-content/uploads/2019/11/iStock_33780344_VSMALL.jpg" alt="Cloud Encryption" class="wp-image-556"/><figcaption><a href="https://blog.hubstor.net/cloud-storage-and-data-encryption-how-businesses-can-protect-information-in-the-cloud">Cloud Encryption</a></figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p><strong>Security</strong> is one of 5 pillars of the Well-Architected framework, it can archive by applying best practices and principals in <strong>IAM</strong>, <strong>Encryption</strong>, <strong>Complician</strong>, and <strong>Governance</strong>. Of course, best practices aren't enough, you need to learn more. In this post, I only share our best practices and tip when working with AWS SSM Parameter Store. By sharing our best practices, my hope is to encourage you to build and deploy secure and reliable applications and also giving us your feedback. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As you know, AWS Lambda supports native environment variables, you can easy to define and add any environment variables you want during deployment or change on the AWS Console Management. But using native environment variables contains some disadvantages:</p>
<!-- /wp:paragraph -->

<!-- wp:more -->
<!--more-->
<!-- /wp:more -->

<!-- wp:list -->
<ul><li>It stores plaint-text variables which easy to see its value. You had an option to encrypt variables in the console using KMS, but it still fetching per innovation causes increase your bill.</li><li>Hard to share across projects and teams that add complexity to your applications and services. More complexity requires more time to operate and increase the cost, therefore, you won't meed the conditional for the <strong>Operational Excellence</strong> pillar of the Well-Architected framework.</li><li>As per Yan Cui, it hards for implementing fine-grained access to sensitive data. </li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4><strong>What is AWS Systems Manager Parameter Store (aka SSM Parameter Store)?</strong> </h4>
<!-- /wp:heading -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>AWS Systems Manager Parameter Store provides secure, hierarchical storage for configuration data management and secrets management. You can store data such as passwords, database strings, and license codes as parameter values. You can store values as plain text or encrypted data. You can then reference values by using the unique name that you specified when you created the parameter. Highly scalable, available, and durable, Parameter Store is backed by the AWS Cloud. ~<a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html">AWS</a></p></blockquote>
<!-- /wp:quote -->

<!-- wp:heading {"level":4} -->
<h4>What are the benefits?</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>There are a lot of benefits when using AWS SSM Parameter Store, I just copied those from the AWS documentation:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Use a secure, scalable, hosted secrets management service with no servers to manage.</li><li>Improve your security posture by separating your data from your code.</li><li>Store configuration data and secure strings in hierarchies and track versions.</li><li>Control and audit access at granular levels.</li><li>Configure change notifications and trigger automated actions for both parameters and parameter policies.</li><li>Tag parameters individually, and then secure access from different levels, including operational, parameter, Amazon EC2 tag, and path levels.</li><li>Reference AWS Secrets Manager secrets by using Parameter Store parameters.</li><li>Use Parameter Store parameters with other Systems Manager capabilities and AWS services to retrieve secrets and configuration data from a central store. </li><li>Configure integration with the AWS services for encryption, notification, monitoring, and auditing.</li></ul>
<!-- /wp:list -->

<!-- wp:separator -->
<hr class="wp-block-separator"/>
<!-- /wp:separator -->

<!-- wp:paragraph -->
<p>So now you understand what is the SSM parameter store and its challenges, let talk about how we use it by reviewing the following our best practices and tips:</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>#1 - Organizing parameters into hierarchies</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>AWS provides detailed <a href="https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-su-organize.html">instructions</a> on how to organize your SSM <strong>Parameter Store</strong> to define and manage parameters easily. Following its best practices can help you and make your life easier. Below are a couple of formats/conventions that our team normally using:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>/environment/service-name/type/application-name/parameter_name i.e. <em>/prod/billing/databases/invoicing-portal/db_connection_string</em></li><li>You also can add your department name as well i.e.  <em>/prod/human-resource/employee/user_list</em></li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>#2 - Consistent naming convention</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Using a <strong>well-defined</strong> hierarchy helps you to manage and retrieve parameters more efficiently, but you also need to use a consistent <a href="https://en.wikipedia.org/wiki/Naming_convention_(programming)">naming convention</a> across your AWS account, your departments, and your teams.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>By archiving this best practice, it reduces your reviewing efforts by focusing on critical business logic rather than syntax and naming standards and then increase your productivity and quality which can increase your customer satisfaction.  </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>#3 - Restrict IAM permission</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>AWS SSM Parameter Store normally keeps your sensitive information, so restrict permissions are required to improve your security of the application. Each Parameter Store has a unique Resource ARN per account and region, so you can easier to define role and policy base on the hierarchy of the parameter store.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Below is a sample code from the AWS official document shows how to define a policy to restrict access to the Parameter Store</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssm:*"
            ],
            "Resource": "arn:aws:ssm:us-east-2::parameter/*"
        },
        {
            "Effect": "Deny",
            "Action": [
                "ssm:GetParametersByPath"
            ],
            "Condition": {
                "StringEquals": {
                    "ssm:Recursive": [
                        "true"
                    ]
                }
            },
            "Resource": "arn:aws:ssm:us-east-2:123456789012:parameter/Dev/ERP/Oracle/*"
        },
        {
            "Effect": "Deny",
            "Action": [
                "ssm:PutParameter"
            ],
            "Condition": {
                "StringEquals": {
                    "ssm:Overwrite": [
                        "false"
                    ]
                }
            },
            "Resource": "arn:aws:ssm:us-east-2:123456789012:parameter/*"
        }
    ]
}
</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>#4 - Combine into a single parameter likes database connection string and keep it all together (co-location)</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>By using consistency hierarchies and naming convention you can archive this idea. Keep all related parameters all together makes easy to find and retrieve. Using fewer parameters can reduce your bills.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Instead of using 4 separated parameters for the database connection string as below:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>/{env}/{service}/databases/master/host = db.domain.com
                                 /user = username
                                 /password = password
                                 /port = 3306</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>We combine into a single parameter using a standard connection string format:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>/{env}/{service}/databases/master/db_connection = jdbc://username:password@db_host:port/database_name</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Using community library such as <em>connection-string-parser</em>, you can easy to parse the parameter values and use to open connection, see below code snippet:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import { createConnection as createConnectionPromise, Connection } from 'promise-mysql';
import { ConnectionStringParser } from 'connection-string-parser';

const parseConnectionString = (dialect: string, connectionUri: string) => {
  const connectionParser = new ConnectionStringParser({
    scheme: dialect || 'mysql',
    hosts: []
  });
  const connectionStrParams = connectionParser.parse(connectionUri);

  return {
    host: connectionStrParams.hosts[0].host,
    port: connectionStrParams.hosts[0].port || 3306,
    database: connectionStrParams.endpoint,
    user: connectionStrParams.username,
    password: connectionStrParams.password
  };
};

export const createConnection = (connectionUri: string): Promise&lt;Connection> => {
  return createConnectionPromise(parseConnectionString('mysql', connectionUri));
};</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>#5 - Use tool/library to fetch, cache, and export to environment variables at runtime</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You are charged for API integration to SSM parameters, every time you retrieve your parameter from the store, you will increase your bill. What could you do to reduce your billing? </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>By default, <strong>max throughput (transactions per second) to retrieve parameter via API is 1000</strong>, how do you manage and avoid exceed throughput error?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://twitter.com/theburningmonk">@Yan Cui</a> wrote an <a href="https://hackernoon.com/you-should-use-ssm-parameter-store-over-lambda-env-variables-5197fc6ea45b">article</a> describes reasons why you should use AWS SSM Parameter Store over Lambda environment variables, he also mentioned approaches for caching and cache expiration using his custom client library. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Our team is using <a href="https://github.com/middyjs/middy">middy</a> middleware to deal with some cross-cutting concerns outside business logic, like input parsing and validation, output serialization, error handling. Application configuration also an aspect that every developer needs to work out and manage to run business logic. Out of the box, middy provides <a href="https://github.com/middyjs/middy/blob/master/docs/middlewares.md#ssm">ssm</a> middleware support fetch and cache parameters from the AWS SSM Parameter Store, it also supports assign parameter values to environment variables.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here is a sample code on how to use middy to fetch and cache parameter store</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const middy = require('middy');
const { ssm } = require('middy/middlewares');

export const handler = middy((event, context, cb) => {
  // You can access the parameter value inside function handler
  console.log(process.env.HARVESTAR_PCMSS_DB_CONNECTION);

  // Your business logic here
}).use(
  ssm({
    cache: true,
    names: {
      // Should have a prefix that include this micro service i.e. pcmss
      HARVESTAR_PCMSS_DB_CONNECTION: '/dev/harvestar/pcmss/db_connection'
    }
  })
);</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>There are some alternative open-sourced libraries out there:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><a href="https://www.npmjs.com/package/aws-parameter-cache">aws-parameter-cache</a></li></ul>
<!-- /wp:list -->

<!-- wp:list -->
<ul><li><a href="https://github.com/alexcasalboni/ssm-cache-python">ssm-cache-python</a></li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p><strong>Do you really trust the community package? </strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I head from some people, basically, they don't want to assign variables into environment variables (i.e. variables you can access through the <em>process.env</em> global object in Node.js runtime). If you do so, I have some advice as below:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Instead of assign variables to <em>environment variables</em>, you also have another option to assign the <em>context</em> object of the AWS Lambda when using <strong>middy/ssm</strong> middleware.</li><li>To avoid sending your sensitive information such as data credentials, accessing to the <em>/tmp </em>directory, or running a child process when executing your serverless functions. You can use <a href="https://www.npmjs.com/package/@puresec/function-shield">@puresec/function-shield</a> library. We are also using it in our production environment.</li></ul>
<!-- /wp:list -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p><strong>TIPS - Avoid fetching parameters at build/deploy time, fetch it at runtime instead. If you do so, you have to redeploy each time the parameter changed.</strong></p></blockquote>
<!-- /wp:quote -->

<!-- wp:heading {"level":4} -->
<h4>#6 - Using hardcoded environment variables for your local development</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Do you need to run your function locally that fetches AWS SSM Parameter Store directly? The answer is it is optional, for your local environment, you might not need to use AWS SSM Parameter Store, you can use a .<em>env </em>file to keep your local variables. Below are some approaches you can use to archive that idea, note you still need to test your function with your desired approach on  AWS environment:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Use the <a href="https://www.npmjs.com/package/env-cmd">env-cmd</a> library to load, extract and assign to <em>process.env </em>global object. By running <em><strong>env-cmd serverless offline</strong></em> command, you can access all variables defined in your .env file.</li><li>Using the <a href="https://github.com/serverless/serverless-secrets-plugin">serverless-secrets-plugin</a> to define the environment variable in a secured manner, you can easier to share across the team and commit the encrypted file.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Using the same code as below with a modification, you can skip fetching parameter store from AWS and reduce your bill:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>const middy = require('middy');
const { ssm } = require('middy/middlewares');

const isLocalEnv = process.env.IS_OFFLINE || process.env.IS_LOCAL;

export const handler = middy((event, context, cb) => {
  // You can access the parameter value inside function handler
  console.log(process.env.HARVESTAR_PCMSS_DB_CONNECTION);

  // Your business logic here
}).use(
  ssm({
    cache: true,
    // By setting the paramsLoaded, you tell the middleware to
    // not fetch it from AWS SSM
    paramsLoaded: isLocalEnv,
    names: {
      // Should have a prefix that include this micro service i.e. pcmss
      HARVESTAR_PCMSS_DB_CONNECTION: '/dev/harvestar/pcmss/db_connection'
    }
  })
);</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>#7 - Pay attention to services limits</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Likes other AWS services, AWS SSM Parameter Store also has some limits, such as the maximum number of params per account and region, max param value size, max history. Understanding its limits help us design and build applications with high reliability. For example, avoid storing large items into the SSM parameter because of size limits (4KB for standard and 8KB for the advanced parameter). Refer to <a href="https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html">AWS service limits documentation</a> for more others.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Resources</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><a href="https://hackernoon.com/you-should-use-ssm-parameter-store-over-lambda-env-variables-5197fc6ea45b">You should use SSM Parameter Store over Lambda env variables</a></li><li><a href="http://Sharing Secrets with AWS Lambda Using AWS Systems Manager Parameter Store">Sharing Secrets with AWS Lambda Using AWS Systems Manager Parameter Store</a></li><li><a href="https://velotio.com/blog/2018/9/2/managing-secrets-using-aws-systems-manager-parameter-store">Managing Secrets Using AWS Systems Manager Parameter Store and IAM Roles</a></li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":4} -->
<h4>Conclusion</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>By applying best practices, you can implement your applications more <strong>reliable</strong>, <strong>secure</strong>, <strong>efficient, and cost-effective</strong> software on the cloud. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I hope this post brings some ideas to you and save your time.  There are more interesting and useful articles, so find and read them to get more information. Feel free to let me know your recommendations or suggestions by adding comments below.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Thank you for reading!</p>
<!-- /wp:paragraph -->