AWS provides two ways to store and manage your application configuration data.
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.
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:
retrieve(key, “parameter”)
to retrieve the parameterretrieve(key)
to retrieve the secretThat's it!