A complete guide to using the AWS Systems Manager Parameter Store in your cloud applications
Tags: aws, devops, python
Published: 2020-05-24 13:06:56

<!-- wp:paragraph -->
<p>Environment variables are used by nearly every developer. They are great for setting parameters that change based on the environment of the system. Unfortunately, they don't scale well. Sure, I agree, there are ways to do it, but it isn't a fun process. AWS offers a product I think can take the place of environment variables (or at least reduce your reliance on them). The AWS Systems Manager Parameter Store is a perfect solution for building modern cloud applications.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="0-what-is-aws-systems-manager-parameter-store">What is AWS Systems Manager Parameter Store?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><a href="https://aws.amazon.com/systems-manager/features/">AWS Systems Manager </a>is a product designed to help you manage large groups of servers deployed into the cloud. For instance, it provides a remote connection to systems, security and patch updates, remote command execution, and other administration tasks at scale.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It also provides a feature called the Parameter Store. The parameter store is a superb place to store centralized data like API keys, database strings, passwords, and other configuration data. </p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="1-why-use-the-aws-systems-manager-parameter-store">Why use the AWS Systems Manager Parameter Store?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The Parameter Store is a great way to make your application less stateful and improve your ability to deploy across several environments. The parameter store has a few advantages over other methods of managing variables:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Easy to update from a central interface</li><li>Hierarchy structure</li><li>Supports encryption to store secrets like passwords</li><li>Supports versioning and roll back of parameters</li><li>Allows access control, both for IAM users and roles</li><li>Ability to audit parameter access using CloudTrail</li><li>Supports throughput of 1,000 transactions per second (must be increased in your settings)</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>I choose parameters over environment variables because I can update the parameter in one location and the changes are instantly available to any code using the parameter. </p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="2-hierarchy-structure">Hierarchy Structure</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Perhaps the most interesting thing about the Parameter Store is the hierarchy structure. Hierarchies are parameters that start with a slash. They are a great way to organize parameters in a manageable fashion. I often create parameters for dev, test, and prod.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-bash"} -->
```bash
/dev/API_KEY
/dev/DB_STRING
/test/API_KEY
/test/DB_STRING
/prod/API_KEY
/prod/DB_STRING
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>This is a painless way to separate and manage parameters even when you have thousands of them. </p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":874,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://i1.wp.com/seanjziegler.com/wp-content/uploads/2020/05/ParameterStoreGraphic.jpg?fit=1024%2C358&amp;ssl=1" alt="" class="wp-image-874"/><figcaption>Even with multiple environments, each part of your application can request the data it needs using the hierarchy structure.</figcaption></figure>
<!-- /wp:image -->

<!-- wp:heading -->
<h2 id="3-parameter-types">Parameter Types</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>A parameter is a piece of data stored within AWS Systems Manager Parameter Store. AWS provides no validation on any parameters (with one exception covered later).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>There are three types of Parameter Store parameters (and a fourth kinda-weird bonus type).</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>String</li><li>StringList</li><li>SecureString</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3 id="4--string-"><strong>String</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Strings are exactly what you expect. Strings are any block of text such as <code>Hello World</code>, <code>test</code>, or <code>wow this is a great blog post</code>. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="5--stringlist-"><strong>StringList</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>StringList is, again, rather intuitive. A StringList is a collection of strings separated by a comma. For example, <code>Cat,Dog,Rabbit</code> and <code>Mercury,Mars,Melons</code> are two examples of string lists.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="6--securestring-"><strong>SecureString</strong></h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>SecureString is used for sensitive data like passwords and API Keys. Data stored in a SecureString parameter are encrypted using keys managed by the AWS Key Management Service. You should know that these parameters are free to use, but AWS will charge you for the Key Management Service as usual. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="7-subtype---ami-datatype">Subtype - AMI Datatype</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>There is one strange "bonus" type you should know. When using a string attribute, you can use an additional parameter <code>--data-type</code> and then specify an Amazon machine image resource number.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-bash"} -->
```bash
aws ssm put-parameter \
    --name "\amis\linux\golden-ami" \
    --type "String" \
    --data-type "aws:ec2:image" \
    --value "ami-12345abcdeEXAMPLE"
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The parameter store will validate that the AMI image is valid, then you'll be able to use the AMI in other services by referencing the parameter.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="8-parameter-tiers">Parameter Tiers</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>There are two types of parameters: standard parameters and advanced parameters. Advanced parameters support parameter policies which can set parameter expiration, notify you if parameters expire, and let you know if a parameter hasn't changed in a while.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can upgrade parameters to advanced parameters, but you can never downgrade to a standard parameter. There's really no reason to use an advanced parameter unless you run up against one of the limits below or you need the advanced policies they offer for notifications.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="9--standard-parameters-"><strong>Standard Parameters</strong></h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Free</li><li>Max of 10,000 parameters (per region)</li><li>4KB max size</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3 id="10--advanced-parameters-"><strong>Advanced Parameters</strong></h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Paid</li><li>Max of 100,000 parameters (per region)</li><li>8KB max size</li><li>Supports parameter policies</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3 id="11-intelligent-tiering">Intelligent Tiering</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>This option is a blend of the two standard options. When you select intelligent tiering, the parameter store will inspect each parameter to see if requires advanced features. If it does, the store automatically upgrades the parameter to the advanced tier. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Intelligent tiering helps control cost and prevent failures because you hit the limit on standard parameters or tried to store a key larger than 4KB. If you don't mind spending the money on advanced parameters, it's worth considering.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="12-managing-parameters-using-the-aws-cli">Managing Parameters using the AWS CLI</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You'll need to install and configure the <a href="https://aws.amazon.com/cli/">AWS CLI</a> if you haven't already.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Creating parameters is very easy. There's a built in command to create parameters.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-bash"} -->
```bash
aws ssm put-parameter --name "/test/email/liscence" --type "String" --value "XM56HE1I9M2AC9W30UM1"
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>To create a SecureString, add a <code>--Key-Id</code> and specify a KMS Key ARN. </p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-bash"} -->
```bash
aws ssm put-parameter --name "/test/email/password" --value "4G00DPA$$W0RD" --type "SecureString" --key-id "arn:aws:kms:us-east-2:123456789012:key/1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e"
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Getting parameters is even more fun. To get a parameter by name, use <code>get-parameters</code>.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-bash"} -->
```bash
aws ssm get-parameters --names "/dev/API_KEY" "/test/API_KEY" "/prod/API_KEY"
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>SecureString parameters require a <code>--with-decryption</code> flag. </p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-bash"} -->
```bash
aws ssm get-parameters --names "/prod/API_KEY" --with-decryption
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>You can get all the parameters in hierarchy</p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-bash"} -->
```bash
aws ssm get-parameters-by-path --path "/dev"
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>and use <code>describe-parameters</code> to query parameters by type. </p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-bash"} -->
```bash
aws ssm describe-parameters --filters "Key=Type,Values=StringList"
```
<!-- /wp:code -->

<!-- wp:heading -->
<h2 id="13-parameter-versioning">Parameter Versioning</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Versioning is another great feature of the parameter store.  If you overwrite a parameter that already exists, the parameter's version will increment. </p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-bash"} -->
```bash
aws ssm put-parameter --name "/test/email/liscence" --type "String" --value "XM56HE1I9M2AC9W30UM1"

aws ssm put-parameter --name "/test/email/liscence" --type "String" --value "XM56HE1I000000000000" --overwrite
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Lets inspect the parameter's history. </p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-json"} -->
```json
aws ssm get-parameter-history --name "/test/email/liscence"

{
    "Parameters": &#91;
        {
            "Name": "/test/email/liscence",
            "Type": "String",
            "LastModifiedDate": "2020-05-22T16:25:04.303000-04:00",
            "LastModifiedUser": "arn:aws:iam::&lt;redacted>",
            "Value": "XM56HE1I9M2AC9W30UM1",
            "Version": 1,
            "Labels": &#91;],
            "Tier": "Standard",
            "Policies": &#91;]
        },
        {
            "Name": "/test/email/liscence",
            "Type": "String",
            "LastModifiedDate": "2020-05-22T16:25:38.281000-04:00",
            "LastModifiedUser": "arn:aws:iam::&lt;redacted>",
            "Value": "XM56HE1I000000000000",
            "Version": 2,
            "Labels": &#91;],
            "Tier": "Standard",
            "Policies": &#91;]
        }
    ]
}
```
<!-- /wp:code -->

<!-- wp:heading -->
<h2 id="14-parameter-policies">Parameter Policies</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Parameter polices allow you to set expirations for parameters, get notified when a parameter expires, and also get notified if a parameter hasn't changed in a while. Don't ask me why policies are only good for these three things, but that's how it works. Maybe AWS will add more options. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can set an expiration time with policies.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-json"} -->
```json
{
   "Type":"Expiration",
   "Version":"1.0",
   "Attributes":{
      "Timestamp":"2018-12-02T21:34:33.000Z"
   }
}
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>You can set up notifications if a parameter is expiring.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-json"} -->
```json
{
   "Type":"ExpirationNotification",
   "Version":"1.0",
   "Attributes":{
      "Before":"15",
      "Unit":"Days"
   }
}
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>And finally, you can set up notifications if a parameter has <em>not </em>changed in a set time period.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-json"} -->
```json
{
   "Type":"NoChangeNotification",
   "Version":"1.0",
   "Attributes":{
      "After":"20",
      "Unit":"Days"
   }
}
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Assigning a parameter policy with the AWS CLI is relatively straightforward.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-bash"} -->
```bash
aws ssm put-parameter   
    --name "/dev/apikey" \
    --value "XM56HE1I9M2AC9W30UM1" \
    --type "String" \
    --overwrite \    
    --policies "&#91;{policies-enclosed-in-brackets-and-curly-braces}]"
```
<!-- /wp:code -->

<!-- wp:heading -->
<h2 id="15-setting-up-service-roles-for-ec2">Setting up service roles for EC2</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>If you want to use the Parameter Store with other services (you probably do), you'll need to grant that service access via a service role.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I've included a role here which will give you access to the Parameter Store for whatever service assumes the role (Just don't forget to attach this to your service role). </p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-json"} -->
```json
{
    "Version": "2012-10-17",
    "Statement": &#91;
        {
            "Sid": "AllowSSMAccess",
            "Effect": "Allow",
            "Action": &#91;
                "ssm:PutParameter",
                "ssm:DeleteParameter",
                "ssm:GetParameterHistory",
                "ssm:GetParametersByPath",
                "ssm:GetParameters",
                "ssm:GetParameter",
                "ssm:DescribeParameters",
                "ssm:DeleteParameters"
            ],
            "Resource": "arn:aws:ssm:*:*:parameter/*"
        },
    ]
}
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>If you require more strict access control, you can limit access to read-only or only allow access to certain parameters.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="16-using-boto3-to-interact-with-the-parameter-store">Using Boto3 to interact with the Parameter Store</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Obviously, no service would be complete with a way to interact with it from code and the Parameter Store is no exception. The <a href="https://aws.amazon.com/tools/">AWS SDK</a>, in my case <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">Boto3</a> since I use python, offers a straightforward way to interface with the Parameter Store.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For example, in the code below I access three different prefixes based on a single environment variable set on the host (you can do this with <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html">EC2 user data</a> or a Dockerfile) and then my application knows which set of parameters to retrieve. I use it to a variety of things including API keys, log file locations, ports, debug status, and more. </p>
<!-- /wp:paragraph -->

<!-- wp:code {"className":"language-python"} -->
```python
## PIP
import boto3

ssm = boto3.client('ssm', region_name='us-east-1')
env = os.environ.get('env')

# Select SSM parameters based on the 'env' environment variable
if env == 'DEV':
    prefix = '/&lt;project>-dev/'

elif env == 'TEST':
    prefix = '/&lt;project>-test/'

elif env == 'PROD':
    prefix = '/&lt;project>-prod/'

# If env is not set, raise error to stop server from starting
else:
    raise AttributeError('No value set for environment type (env)')

secrets = {
    'ENV' : env,
    'DEBUG' : ssm.get_parameter(Name= prefix + 'DEBUG')&#91;'Parameter']&#91;'Value'],
    'PORT' : ssm.get_parameter(Name= prefix + 'PORT')&#91;'Parameter']&#91;'Value'],
    'FLASK_SECRET_KEY' : ssm.get_parameter(Name= prefix + 'FLASK_SECRET_KEY', WithDecryption=True)&#91;'Parameter']&#91;'Value'],

    'COGNITO_ID' : ssm.get_parameter(Name= prefix + 'COGNITO_ID', WithDecryption=True)&#91;'Parameter']&#91;'Value'],
    'CLIENT_ID' : ssm.get_parameter(Name= prefix + 'CLIENT_ID', WithDecryption=True)&#91;'Parameter']&#91;'Value'],
    'INVOKE_API' : ssm.get_parameter(Name= prefix + 'INVOKE_API', WithDecryption=True)&#91;'Parameter']&#91;'Value'],
    'API_GATEWAY_KEY' : ssm.get_parameter(Name= prefix + 'API_GATEWAY_KEY', WithDecryption=True)&#91;'Parameter']&#91;'Value'],
    'SNS_CONTACT_ARN' : ssm.get_parameter(Name= prefix + 'SNS_CONTACT_ARN')&#91;'Parameter']&#91;'Value'],

    'RAINFOREST_API_KEY' : ssm.get_parameter(Name= prefix + 'RAINFOREST_API_KEY', WithDecryption=True)&#91;'Parameter']&#91;'Value'],

    'LOG_FILE' : ssm.get_parameter(Name= 'LOG_FILE')&#91;'Parameter']&#91;'Value']
}
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Don't forget to add the service role for any machine that will run code that accesses the Parameter Store!</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="17-conclusion">Conclusion</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>That's everything that you need to know about how to integrate the AWS Systems Manager Parameter Store. Hopefully, you learned how to use the AWS Parameter Store a little better and can incorporate it into your future work.</p>
<!-- /wp:paragraph -->

<!-- wp:html -->
<p>If you enjoyed this content, follow me on Twitter to see more like this!<br></p>

<a href="https://twitter.com/sean_ziegler?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-show-count="false">Follow @Sean_Ziegler</a><script async="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<!-- /wp:html -->