Skip to main content

Cloud and deployment · Intermediate · 22 min

Store app secrets in AWS Secrets Manager and Parameter Store

By Padding · Updated 18 Nov 2026
Debian (node:26 image) and Ubuntu 26.04 · Node.js 26.13.1 · AWS CLI 2.42.4 · AWS SDK for JavaScript 3.1178.0

You will keep a database URL in Secrets Manager and a feature flag in Parameter Store, load both into a Node.js app at start-up with a cache, limit one IAM role to exactly those two values, and put an RDS password on a rotation schedule.

On this page

Every app has a handful of values it needs at start-up that must not live in Git: a database URL with a password in it, an API key, a signing secret. It also has settings that are not secret but change without a deploy, such as a feature flag. AWS offers two places for both. Secrets Manager stores secrets, encrypts them, and can rotate them for you. Parameter Store, part of AWS Systems Manager, stores configuration as a tree of named values, with an encrypted SecureString type and a free standard tier.

In this tutorial you put a database URL in Secrets Manager without it ever touching your shell history, store a feature flag as a SecureString parameter, and decide which service suits which value. Then you write a small Node.js 26 loader that reads both when the app starts and caches them, give the app's IAM role read access to those two values and nothing else, and put an RDS master password on a rotation schedule.

Everything is named secrets-demo, and files live in ~/secrets-demo, so nothing collides with what your account already holds. One secret costs a few US cents for the days it exists; the clean-up step deletes it.

Step 1 · Install the tools and point them at your account

Install curl, unzip and jq, then version 2.42.4 of the AWS CLI from Amazon's versioned installer. uname -m prints x86_64 or aarch64, which matches Amazon's file names:

Bash
sudo apt update
sudo apt install -y curl unzip jq ca-certificates
AWS_CLI_VERSION=2.42.4
cd "$(mktemp -d)"
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install
aws --version
node --version

If the AWS CLI is already installed, run sudo ./aws/install --update instead. It gets no updates from apt; to upgrade later, run the same commands with a newer version number.

Point the CLI at your sandbox account (export AWS_PROFILE=<your-sandbox-profile> if you use a named profile; replace the placeholder) and choose a Region. The commands use London, eu-west-2. Cape Town, af-south-1, is closer for users in southern and East Africa, but it is an opt-in Region you must enable in the account first. Secrets and parameters belong to one Region, so the app must read them from the Region where you create them. The Node.js SDK reads AWS_REGION and the CLI reads AWS_DEFAULT_REGION, so set both:

Bash
export AWS_REGION=eu-west-2 AWS_DEFAULT_REGION=eu-west-2
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
echo "$ACCOUNT_ID"
mkdir -p ~/secrets-demo
cd ~/secrets-demo

Check it worked

aws --version starts with aws-cli/2.42.4, node --version prints v26 followed by a minor and patch number, and echo "$ACCOUNT_ID" prints your 12-digit account ID. If the CLI says it cannot find credentials, sign in again (aws sso login for an SSO profile) and rerun the export line.

Step 2 · Put the database URL in Secrets Manager from a file

A value passed on the command line ends up in shell history and, while the command runs, in the process list that other users on the machine can read. So the URL goes from a hidden prompt into a private file, and the CLI reads the file.

Create an empty file only you can read, before anything is written to it:

Bash
cd ~/secrets-demo
install -m 600 /dev/null secret.json

Ask for the URL without echoing it. Paste your real database URL, in the form postgres://user:password@host:5432/dbname, and press Enter. read is a shell built-in, so the value never appears in the process list:

Bash
read -rsp 'Database URL: ' DB_URL; echo

Write it into the file as JSON and forget it. printf is also a built-in. If your password contains " or ``, percent-encode it first, as URLs expect anyway:

Bash
printf '{"url":"%s"}\n' "$DB_URL" > secret.json
unset DB_URL

Now create the secret. file:// tells the CLI to read the value from the file. The name uses slashes to read as app, environment and purpose; Secrets Manager treats them as ordinary characters:

Bash
export SECRET_ARN=$(aws secretsmanager create-secret \
  --name secrets-demo/prod/database \
  --description "Database URL for the secrets-demo app" \
  --secret-string file://secret.json \
  --query ARN --output text)
echo "$SECRET_ARN"
rm secret.json

Storing a JSON object rather than a bare string leaves room to add keys later (a read-only URL, say) without paying for a second secret. With no --kms-key-id, Secrets Manager encrypts the value with the AWS managed key aws/secretsmanager.

Check it worked

The ARN ends in your secret name, a hyphen and six random characters, for example arn:aws:secretsmanager:eu-west-2:123456789012:secret:secrets-demo/prod/database-a1B2c3. Read the value back with the password masked, so it does not land on your screen or in a terminal recording:

Bash
aws secretsmanager get-secret-value --secret-id "$SECRET_ARN" \
  --query SecretString --output text | jq -r '.url | sub(":[^:@/]+@"; ":****@")'

It prints your URL with the password replaced, something like postgres://notes_app:****@db.internal:5432/notes. ls ~/secrets-demo shows no secret.json, and history | tail -5 shows the read command but not the URL.

Step 3 · Store a feature flag as a SecureString parameter

The flag switches on a new editor in the app. It is not a secret, but storing it as a SecureString shows the type you would use for a secret in Parameter Store, and it means only roles allowed to decrypt can read it. A short, non-sensitive value like on is fine on the command line; for a real secret, use --value file://... as you did above.

Parameter names are paths. Grouping everything for one app and environment under /secrets-demo/prod/ lets you list or grant them as a set later. Ask for the standard tier explicitly, because it is the free one and the account default can be changed:

Bash
aws ssm put-parameter \
  --name /secrets-demo/prod/feature/new-editor \
  --type SecureString \
  --tier Standard \
  --description "Turns the new editor on for everyone" \
  --value on \
  --query Version --output text
export PARAM_ARN="arn:aws:ssm:${AWS_REGION}:${ACCOUNT_ID}:parameter/secrets-demo/prod/feature/new-editor"

With no --key-id, Parameter Store encrypts the value with the AWS managed key aws/ssm. Note the parameter ARN: it is parameter/ followed by the name without its leading slash.

Check it worked

put-parameter prints 1, the first version. Read the flag twice, once without and once with decryption:

Bash
aws ssm get-parameter --name /secrets-demo/prod/feature/new-editor \
  --query Parameter.Value --output text
aws ssm get-parameter --name /secrets-demo/prod/feature/new-editor \
  --with-decryption --query Parameter.Value --output text

The first prints a long encrypted string, not on. The second prints on. Anyone who can call ssm:GetParameter but not decrypt sees only the first.

Step 4 · Decide which service holds which value

You now have one value in each service. They overlap, so choose on these points. Prices and limits were checked on 26 November 2026 on AWS's pricing and quotas pages; check them again before you plan a budget.

  • Rotation. Secrets Manager rotates secrets on a schedule: RDS, Aurora, Redshift and DocumentDB manage rotation of their master passwords themselves, and for anything else you supply a Lambda function that sets the new value. Parameter Store has no rotation of its own; you would build and schedule it yourself.
  • Cost. Secrets Manager charges 0.40 USD per secret per month plus 0.05 USD per 10,000 API calls. Standard parameters cost nothing extra, and so do their API calls at standard throughput. Advanced parameters cost 0.05 USD each per month, and their API calls are charged too.
  • Size. A secret can hold up to 65,536 bytes. A standard parameter holds up to 4 KB, an advanced one up to 8 KB.
  • Count. Standard parameters are capped at 10,000 per account and Region, advanced ones at 100,000. Secrets Manager allows 500,000 secrets per Region.
  • Cross-account access. A secret can carry a resource policy that lets a role in another account read it, as long as it is encrypted with a KMS key you created; the aws/secretsmanager key cannot be shared. Advanced parameters can be shared with other accounts; standard ones cannot.

A rule that works for most apps: credentials that should change on a schedule (database passwords, third-party API keys) go in Secrets Manager, one JSON secret per app and environment. Everything else (flags, URLs of other services, limits) goes in standard parameters. Secrets Manager is billed in US dollars per secret, so if your team pays by card in naira, cedis or shillings, grouping keys in one JSON secret keeps the monthly count and the exchange-rate surprises small.

Check it worked

List what this tutorial is paying for and how the flag is stored:

Bash
aws secretsmanager list-secrets --filters Key=name,Values=secrets-demo/ \
  --query 'length(SecretList)' --output text
aws ssm describe-parameters \
  --parameter-filters Key=Name,Values=/secrets-demo/prod/feature/new-editor \
  --query 'Parameters[0].[Type,Tier]' --output text

The first prints 1: one billed secret. The second prints SecureString and Standard: an encrypted parameter in the free tier. Write down, for your own app, which of its settings belong in each list.

Step 5 · Load both values when the app starts, with a cache

The app reads its configuration once at start-up and keeps it in memory. That keeps requests fast, keeps the API bill near zero, and means a missing permission stops the app at once instead of failing on the first user's request. A time limit on the cache lets a long-running process pick up a rotated password or a changed flag without a restart.

Install the two SDK clients at exact versions:

Bash
cd ~/secrets-demo
npm init -y > /dev/null
npm install @aws-sdk/client-secrets-manager@3.1178.0 @aws-sdk/client-ssm@3.1178.0

Create config.mjs. The names come from environment variables with the demo names as defaults, so the same code runs in every environment:

Bash
cat > config.mjs <<'JS'
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
import { SSMClient, GetParameterCommand } from '@aws-sdk/client-ssm';

const SECRET_ID = process.env.DB_SECRET_ID ?? 'secrets-demo/prod/database';
const FLAG_NAME = process.env.FLAG_PARAM ?? '/secrets-demo/prod/feature/new-editor';
const TTL_MS = Number(process.env.CONFIG_TTL_MS ?? 5 * 60 * 1000);

// Region and credentials come from the environment, the profile or the instance role.
const secrets = new SecretsManagerClient({});
const ssm = new SSMClient({});

let pending = null;
let loadedAt = 0;
let calls = 0;

async function load() {
  calls += 2;
  const [secret, flag] = await Promise.all([
    secrets.send(new GetSecretValueCommand({ SecretId: SECRET_ID })),
    ssm.send(new GetParameterCommand({ Name: FLAG_NAME, WithDecryption: true })),
  ]);
  const { url } = JSON.parse(secret.SecretString);
  return { databaseUrl: url, newEditor: flag.Parameter.Value === 'on' };
}

// Every caller shares one request while it is in flight, and one result until it expires.
export function getConfig() {
  if (!pending || Date.now() - loadedAt > TTL_MS) {
    loadedAt = Date.now();
    pending = load().catch((err) => {
      pending = null;
      throw err;
    });
  }
  return pending;
}

// Call this when the database rejects the password, then retry once.
export function forgetConfig() {
  pending = null;
}

export function awsCallCount() {
  return calls;
}
JS

Two details matter. The cache holds the promise, not the result, so ten requests arriving together at start-up make one pair of AWS calls, not ten. And a failed load is not cached, so the next caller tries again.

Now the app itself. It loads its configuration before doing anything else and prints what it got, without the password:

Bash
cat > app.mjs <<'JS'
import { getConfig } from './config.mjs';

const config = await getConfig();
const db = new URL(config.databaseUrl);
console.log(
  `secrets-demo ready: database ${db.hostname}${db.pathname} as ${db.username}, ` +
    `new editor ${config.newEditor ? 'on' : 'off'}`,
);
JS
node app.mjs

Check it worked

node app.mjs prints something like secrets-demo ready: database db.internal/notes as notes_app, new editor on, with your own host, database and user. If it fails with AccessDeniedException or ResourceNotFoundException, check the Region and the profile you exported in the first step.

Prove the cache works. This script asks for the configuration three times:

Bash
cat > cache-demo.mjs <<'JS'
import { getConfig, awsCallCount } from './config.mjs';

for (let i = 1; i <= 3; i++) {
  const config = await getConfig();
  console.log(`request ${i}: new editor ${config.newEditor ? 'on' : 'off'}`);
}
console.log(`AWS calls: ${awsCallCount()}`);
JS
node cache-demo.mjs

It prints three request lines and AWS calls: 2: one call to each service, however many times the app asks. Now turn the flag off and start the app again:

Bash
aws ssm put-parameter --name /secrets-demo/prod/feature/new-editor \
  --type SecureString --value off --overwrite --query Version --output text
node app.mjs

put-parameter prints 2, and the app now ends with new editor off. A process that is already running sees the change once its five-minute cache expires.

Step 6 · Let the app's role read those two values and nothing else

On AWS the app should not use your credentials. It runs with a role, here one for an EC2 instance; for ECS tasks the trusted service is ecs-tasks.amazonaws.com instead. Write the trust policy and create the role:

Bash
cd ~/secrets-demo
cat > trust.json <<'JSON'
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "ec2.amazonaws.com" },
      "Action": "sts:AssumeRole"
    }
  ]
}
JSON
export ROLE_ARN=$(aws iam create-role --role-name secrets-demo-app \
  --assume-role-policy-document file://trust.json \
  --query Role.Arn --output text)
echo "$ROLE_ARN"

Now the permissions. Each statement names one action and one full ARN, taken from the variables you exported. The heredoc is unquoted on purpose so the shell fills them in:

Bash
cat > read-config.json <<JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadTheDatabaseSecret",
      "Effect": "Allow",
      "Action": "secretsmanager:GetSecretValue",
      "Resource": "${SECRET_ARN}"
    },
    {
      "Sid": "ReadTheFeatureFlag",
      "Effect": "Allow",
      "Action": "ssm:GetParameter",
      "Resource": "${PARAM_ARN}"
    }
  ]
}
JSON
aws iam put-role-policy --role-name secrets-demo-app \
  --policy-name read-config --policy-document file://read-config.json
  • The secret ARN ends in six random characters. Naming the full ARN means that if someone deletes the secret and creates a new one with the same name, the role cannot read the new one until you update the policy. AWS also documents a secrets-demo/prod/database-?????? pattern for granting a secret before it exists; avoid database-*, which would also match names that start with database- and continue.
  • There is no KMS statement. Both values use the AWS managed keys aws/secretsmanager and aws/ssm, which any principal allowed to read the value may use through the service. If you encrypt with a key of your own, add kms:Decrypt on that key's ARN.
  • There is no ssm:GetParametersByPath or secretsmanager:ListSecrets. The app knows the names it needs, so it never has to browse.

Check it worked

Read the policy back from IAM:

Bash
aws iam get-role-policy --role-name secrets-demo-app --policy-name read-config \
  --query 'PolicyDocument.Statement[].[Action,Resource]' --output text

It prints two lines: secretsmanager:GetSecretValue with your secret ARN, and ssm:GetParameter with your parameter ARN.

Then ask the IAM policy simulator what the role may do, without attaching it to anything. The second resource in each call is a made-up neighbour the role should not reach:

Bash
aws iam simulate-principal-policy --policy-source-arn "$ROLE_ARN" \
  --action-names secretsmanager:GetSecretValue \
  --resource-arns "$SECRET_ARN" \
    "arn:aws:secretsmanager:${AWS_REGION}:${ACCOUNT_ID}:secret:secrets-demo/prod/payments-AbCdEf" \
  --query 'EvaluationResults[0].ResourceSpecificResults[].[EvalResourceName,EvalResourceDecision]' \
  --output text
aws iam simulate-principal-policy --policy-source-arn "$ROLE_ARN" \
  --action-names ssm:GetParameter \
  --resource-arns "$PARAM_ARN" \
    "arn:aws:ssm:${AWS_REGION}:${ACCOUNT_ID}:parameter/secrets-demo/prod/feature/billing" \
  --query 'EvaluationResults[0].ResourceSpecificResults[].[EvalResourceName,EvalResourceDecision]' \
  --output text

Each call prints allowed next to your real ARN and implicitDeny next to the made-up one. To give the role to an instance, follow the instance profile step in /tutorials/create-an-iam-role-with-a-least-privilege-policy; the loader then picks up the role's credentials with no code change.

Step 7 · Put an RDS master password on a rotation schedule

A database password that never changes is only as safe as every laptop, log and backup it has ever passed through. Secrets Manager rotation fixes that, and for RDS it needs no code: when you create an instance with --manage-master-user-password, RDS keeps the master password in a secret it owns and rotates it every seven days by default. This step uses the instance from /tutorials/run-a-managed-postgresql-database-on-amazon-rds; if you have not built it, read on and come back.

For a secret you created yourself, like the URL above, rotation needs a Lambda function that sets the new password on the database and writes it to the secret. AWS publishes templates for that; it is a project of its own.

Find the RDS-managed secret. Replace <your-db-instance> with your instance identifier:

Bash
export RDS_SECRET_ARN=$(aws rds describe-db-instances \
  --db-instance-identifier <your-db-instance> \
  --query 'DBInstances[0].MasterUserSecret.SecretArn' --output text)
echo "$RDS_SECRET_ARN"

Change the schedule to every Sunday between 01:00 and 03:00 UTC, a quiet window for most users in Africa and Europe. Read this before you run it: by default rotate-secret also rotates the password straight away, so any process still holding the old one loses its connections and must read the secret again, which the loader's forgetConfig and the cache expiry handle. Rotation usually finishes within a minute:

Bash
aws secretsmanager rotate-secret --secret-id "$RDS_SECRET_ARN" \
  --rotation-rules '{"ScheduleExpression": "cron(0 1 ? * SUN *)", "Duration": "2h"}'

Rotation runs in UTC and can be as frequent as every four hours. Weekly is a common choice for a master password your apps should not use day to day; give each app its own database user with only the rights it needs.

Check it worked

Bash
aws secretsmanager describe-secret --secret-id "$RDS_SECRET_ARN" \
  --query '[RotationEnabled,RotationRules.ScheduleExpression,LastRotatedDate,NextRotationDate]' \
  --output text

It prints True, cron(0 1 ? * SUN *), a last-rotated time from a minute ago and a next rotation on the coming Sunday. aws secretsmanager list-secret-version-ids --secret-id "$RDS_SECRET_ARN" shows a new version labelled AWSCURRENT and the old one labelled AWSPREVIOUS.

Step 8 · Clean up

Read this first: --force-delete-without-recovery deletes the secret at once, with no recovery window. Leave it off for any secret you might need back; Secrets Manager then keeps it for 30 days by default, and you can restore it with aws secretsmanager restore-secret. Do not delete the RDS-managed secret; RDS removes it when you delete the instance.

Bash
aws secretsmanager delete-secret --secret-id "$SECRET_ARN" \
  --force-delete-without-recovery --query Name --output text
aws ssm delete-parameter --name /secrets-demo/prod/feature/new-editor
aws iam delete-role-policy --role-name secrets-demo-app --policy-name read-config
aws iam delete-role --role-name secrets-demo-app
cd ~
rm -rf ~/secrets-demo

If you changed the RDS rotation schedule only to try it, set it back with the same rotate-secret command and "ScheduleExpression": "rate(7 days)", or leave the weekly window in place.

Check it worked

delete-secret prints secrets-demo/prod/database. aws secretsmanager list-secrets --filters Key=name,Values=secrets-demo/ returns an empty list, aws ssm get-parameter --name /secrets-demo/prod/feature/new-editor fails with ParameterNotFound, aws iam get-role --role-name secrets-demo-app fails with NoSuchEntity, and ~/secrets-demo is gone.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.