Use SSM to Retrieve Both Parameter Store Parameters and Secrets Manager Secrets
Adam C. |

AWS provides two ways to store and manage your application configuration data. 

  1. Parameter Store - it's designed to say any application variable like URLs, Token, etc.
  2. Secrets Manager - as the name says, it is mainly for secret keys, like passwords and API Keys, because the entry is encrypted by default.

Both access can be restricted through IAM, although Secrets Manager provides an additional layer of security. The main differences are the cost and secrets rotation. Check this excellent article to see the comparison.

Photo by Kristina Flour on Unsplash

We can use @aws-sdk/client-ssm to retrieve the Parameters from Parameter Store, like below:

import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";

const getParameter = async (parameterName) => {
  const params = {
    Name: parameterName,
    WithDecryption: true,
  };

  const command = new GetParameterCommand(params);
  const result = await ssm.send(command);
  return result.Parameter.Value;
};

And we can use @aws-sdk/client-secrets-manager to retrieve the Secrets from Secret Manager, like below:

import {
  	SecretsManagerClient,
	GetSecretValueCommand,
} from "@aws-sdk/client-secrets-manager";

export const getSecretConnection = async (secretId) => {
  
  try {
    const command = new GetSecretValueCommand({
      SecretId: secretId,
    });
    const result = await secretsmanager.send(command);

    if (result) {
      return JSON.parse(result.SecretString);
    }
  } catch (error) {
    handleErrorLogging('GET DB CONNECTION FAILED: ', error,'');
  }
  return {};
};

And today, I learned that we could  use  @aws-sdk/client-ssm to retrieve Secrets from the secret manager as well. That is called Referencing AWS Secrets Manager secrets from Parameter Store parameters.

Just keep in mind, 

When you retrieve a Secrets Manager secret from Parameter Store, the name must begin with the following reserved path: /aws/reference/secretsmanager/secret_ID_in_Secrets_Manager.

That's cool, we can simplify the code as below:

import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";

const retrieve = async (key, type="secret") => {
. const parameterName = type === "secret" ? 
	`/aws/reference/secretsmanager/${key}` : key;
  const params = {
    Name: parameterName,
    WithDecryption: true,
  };

  const command = new GetParameterCommand(params);
  const result = await ssm.send(command);
  return result.Parameter.Value;
};

Note: 

  1. use retrieve(key, “parameter”) to retrieve the parameter
  2. use retrieve(key) to retrieve the secret
  3. you may add try-catch as I did in the previous example

That's it!