Introduction
AWS Secrets Manager is an essential AWS service for handling secrets like database passwords, API keys, or authentication tokens. Unlike exposed environment variables, it encrypts secrets at rest using AWS KMS, controls access via IAM, and automates rotations.
Why use it in 2026? Security breaches cost millions; Secrets Manager minimizes risks by centralizing management, auditing access, and natively integrating with RDS, Lambda, and ECS. This beginner tutorial guides you step by step: from CLI setup to Node.js integration. By the end, you'll know how to create, retrieve, and protect secrets in production. Think of it as a digital vault: you store your keys, and AWS handles the locks.
Prerequisites
- Free AWS account (Secrets Manager eligible for Free Tier).
- AWS CLI v2 installed (download).
- Node.js 20+ and npm/yarn.
- Basic terminal and TypeScript knowledge (optional).
- Default AWS region: us-east-1 (changeable via
--region).
Configure AWS CLI
aws configure set aws_access_key_id YOUR_ACCESS_KEY_ID
aws configure set aws_secret_access_key YOUR_SECRET_ACCESS_KEY
aws configure set default.region us-east-1
aws configure set default.output json
echo "Configuration terminée. Vérifiez avec : aws sts get-caller-identity"This script configures your AWS CLI credentials with an IAM access key (create one without MFA for testing). It sets the region and JSON output format. Avoid using the root account: create an IAM user with SecretsManagerFullAccess.
Verify the configuration
Run the previous script, then aws sts get-caller-identity to confirm. You'll see your UserId and Account. Analogy: Like setting your GPS before an AWS road trip.
Create a secret via CLI
SECRET_NAME=my-app-db-password
SECRET_VALUE='{"username":"admin","password":"SuperSecret123!"}'
aws secretsmanager create-secret \
--name $SECRET_NAME \
--description "Mot de passe base de données pour l'app de démo" \
--secret-string $SECRET_VALUE
aws secretsmanager describe-secret --secret-id $SECRET_NAMEThis code creates an encrypted JSON secret. Use --secret-string for text, --secret-binary for binary. Pitfall: Use unique names (no duplicates); check the returned ARN for future references.
Retrieve a secret via CLI
SECRET_NAME=my-app-db-password
aws secretsmanager get-secret-value \
--secret-id $SECRET_NAME \
--query SecretString \
--output text | jq .Retrieves the decrypted value as JSON output. --query extracts SecretString; jq formats it (install via brew install jq). Pitfall: Without IAM permissions, you'll get AccessDeniedException.
Integrate with Node.js SDK
Now for code: install the modern AWS SDK v3 (tree-shakeable). Analogy: CLI for admin tasks, SDK for runtime apps.
Install Node.js dependencies
mkdir aws-secrets-demo && cd aws-secrets-demo
npm init -y
npm install @aws-sdk/client-secrets-manager @types/node typescript ts-node
npm install -D @types/node
echo '{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"strict": true
}
}' > tsconfig.jsonInitializes a Node.js project with AWS SDK v3. ts-node runs TS directly. Configures tsconfig.json for type safety. Run npm run afterward.
Create a secret with SDK
import { SecretsManagerClient, CreateSecretCommand } from '@aws-sdk/client-secrets-manager';
const client = new SecretsManagerClient({ region: 'us-east-1' });
const secretName = 'my-app-api-key';
const secretValue = JSON.stringify({ apiKey: 'sk-abc123def456ghi789' });
const command = new CreateSecretCommand({
Name: secretName,
Description: 'Clé API pour l\'app de démo',
SecretString: secretValue,
});
async function createSecret() {
try {
const response = await client.send(command);
console.log('Secret créé:', response.ARN);
} catch (error) {
console.error('Erreur:', error);
}
}
createSecret();Creates a secret via SDK with async commands. Use fromIni for auto credentials (~/.aws/credentials). Pitfall: Handle ResourceExistsException for duplicates; add KmsKeyId for custom KMS.
Retrieve and use a secret
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
const client = new SecretsManagerClient({ region: 'us-east-1' });
const secretName = 'my-app-db-password';
async function getSecret() {
try {
const command = new GetSecretValueCommand({ SecretId: secretName });
const response = await client.send(command);
const secret = JSON.parse(response.SecretString!);
console.log('DB Username:', secret.username);
console.log('DB Password:', secret.password);
// Utilisez en prod : const db = await connect(secret.username, secret.password);
} catch (error) {
console.error('Erreur récupération:', error);
}
}
getSecret();Retrieves, parses JSON, and uses the secret (e.g., DB connection). Optional caching via Cache pattern. Pitfall: NEVER log secrets in production; use process.env as fallback.
Best practices
- Least-privilege permissions: Attach specific IAM policies (
secretsmanager:GetSecretValueonly). - Automatic rotation: Enable for databases (Lambda rotates every 30 days).
- Custom KMS keys: For cross-account control.
- Tags: Add
Environment:prodfor billing/auditing. - Client-side caching: TTL 1h to reduce API costs.
Common errors to avoid
- Unconfigured credentials:
NoCredentialProvidererror. Fix:aws configureor env vars. - Region mismatch: Secret in eu-west-1, query in us-east-1 →
ResourceNotFound. - Secrets in logs: Use structured logging without values.
- No JSON parsing:
SecretStringis a string; always useJSON.parse().
Next steps
Master advanced AWS with our Learni trainings. Resources: AWS Secrets Manager Docs, GitHub Examples.