Sub topic 4
Secrets Manager basics: creating and storing secrets
AWS Secrets Manager is a managed service for storing sensitive values such as database credentials, API keys, and tokens. It encrypts each value, controls access with IAM, and keeps a version history. This chapter covers what a secret is, how to create and change one, and how to delete one safely.
This chapter assumes you can use the AWS CLI, read JSON, and write basic Python with boto3. It also assumes you know what an IAM role is. Policies for reading secrets are covered in a later chapter, and retrieval, rotation, and versions each get their own chapter.
What a secret is
A secret is a named container. It holds metadata (name, description, tags, encryption key) and one or more versions of a value. The value is either text (SecretString) or binary (SecretBinary). The value can be up to 65,536 bytes.
Most secrets are JSON documents. A single secret can hold several related fields, such as a username, password, host, and port. This keeps related credentials together and lets you replace them as one unit.
Secrets Manager differs from Parameter Store in two ways:
- It is built for values that change. It can generate new credentials and update the database on a schedule.
- It charges per secret and per API call, whereas standard Parameter Store parameters are free.
The comparison is covered in the chapter on choosing between the two services.
Naming secrets
A secret name can be up to 512 characters. It may contain letters, digits, and the characters /_+=.@-. Slashes let you build paths such as myapp/prod/db, which mirror the hierarchy you use in Parameter Store.
Unlike Parameter Store, the slashes in a secret name are only a naming convention. They do not create a real hierarchy, and no API returns "all secrets under a path". You can still use the path in IAM policy resources and in list filters, so choose a consistent scheme such as app/environment/purpose.
Every secret also has an ARN. Secrets Manager appends a hyphen and six random characters to the name:
arn:aws:secretsmanager:us-east-1:111122223333:secret:myapp/prod/db-AbC1dEThe suffix means that deleting a secret and recreating one with the same name produces a different ARN. It also explains why IAM policies end in db-* rather than the bare name.
Creating a secret with the CLI
The following command creates a secret that holds a JSON document:
aws secretsmanager create-secret \
--name myapp/prod/db \
--description "Application database credentials" \
--secret-string '{"username":"app","password":"REPLACE_ME"}' \
--tags Key=app,Value=myapp Key=env,Value=prodThe response contains the ARN, the name, and a VersionId. It does not contain the value.
Putting a real password on the command line has a cost. The shell stores it in your history, and other users on the same machine may see it in the process list. For real values, read the secret from a file or from standard input:
umask 077
cat > db-secret.json <<'EOF'
{"username":"app","password":"REPLACE_ME"}
EOF
aws secretsmanager create-secret \
--name myapp/prod/db \
--secret-string file://db-secret.json
shred -u db-secret.jsonThe umask 077 line makes the temporary file readable only by you. The shred command deletes it after the call. If the secret is a password for a database you manage, you can also have Secrets Manager generate the password for you:
aws secretsmanager get-random-password \
--password-length 32 \
--exclude-punctuation \
--query RandomPassword \
--output textUse --exclude-punctuation when the password goes into a connection string, because characters such as @ and / break URL parsing.
Creating a secret with boto3
The same operation in Python:
import json
import boto3
from botocore.exceptions import ClientError
client = boto3.client("secretsmanager")
secret_value = {"username": "app", "password": "REPLACE_ME"}
try:
response = client.create_secret(
Name="myapp/prod/db",
Description="Application database credentials",
SecretString=json.dumps(secret_value),
Tags=[
{"Key": "app", "Value": "myapp"},
{"Key": "env", "Value": "prod"},
],
)
print(response["ARN"])
except ClientError as err:
if err.response["Error"]["Code"] == "ResourceExistsException":
print("Secret already exists; use put_secret_value to change it")
else:
raisecreate_secret is not an upsert. If the name already exists, you get ResourceExistsException. The code above handles that case rather than overwriting anything.
Structuring JSON secrets
A flat JSON object with string values works best, because tools that read secrets can pick out a single key. The Secrets Manager rotation templates for Amazon RDS expect specific keys:
| Key | Meaning |
|---|---|
| `username` | Database user name |
| `password` | Database password |
| `engine` | Database engine, such as `mysql` or `postgres` |
| `host` | Endpoint host name |
| `port` | Port number |
| `dbname` | Database name |
| `dbInstanceIdentifier` | RDS instance or cluster identifier |
Use these key names even if you do not plan to rotate yet. That way, you can turn rotation on later without reshaping the secret.
Group values that change together into one secret. Keep values with different owners or different rotation schedules in separate secrets. Each secret costs money, but a combined secret also grants every reader access to every field, which weakens least privilege.
Encryption at creation
Secrets Manager always encrypts the value with AWS KMS. If you do not choose a key, it uses the AWS managed key aws/secretsmanager. To use a customer managed key, pass --kms-key-id:
aws secretsmanager create-secret \
--name myapp/prod/api-key \
--secret-string 'REPLACE_ME' \
--kms-key-id alias/myapp-prodThe managed key cannot be used from another account, because its policy cannot be edited. If a secret will be shared across accounts, choose a customer managed key from the start. Changing the key later is possible but requires an update call and care with existing readers. Key policies and grants belong to the KMS chapter.
Changing, inspecting and listing
describe-secret returns metadata only: name, description, key, tags, rotation settings, and version stages. It never returns the value, so it is safe to allow broadly in IAM.
aws secretsmanager describe-secret --secret-id myapp/prod/db
aws secretsmanager list-secrets --filters Key=name,Values=myapp/prodTo change a value, call put-secret-value. It creates a new version and moves the AWSCURRENT label to it:
aws secretsmanager put-secret-value \
--secret-id myapp/prod/db \
--secret-string file://db-secret.jsonThe old version stays available with the AWSPREVIOUS label. The versions chapter covers this in detail. To change metadata or the key, use update-secret.
Deleting secrets
Deleting a secret does not remove it at once. Secrets Manager schedules the deletion and keeps the secret for a recovery window of 7 to 30 days. The default is 30.
aws secretsmanager delete-secret \
--secret-id myapp/prod/db \
--recovery-window-in-days 7
aws secretsmanager restore-secret --secret-id myapp/prod/dbDuring the window, nobody can read the value, and you cannot create a new secret with the same name. restore-secret cancels the deletion. The --force-delete-without-recovery flag removes the secret immediately and permanently. Use it only when you are sure, for example in a disposable test account.
Common mistakes
- Wrong value shape. Storing a plain string and later expecting JSON, or the reverse, causes
json.loadsfailures in application code. Decide on the format first and document it in the description. - Secrets in shell history. Use
file://or an SDK call from a secure source. - Using the AWS managed key for shared secrets. Cross-account readers cannot decrypt with it.
- Policies that omit the suffix. A resource of
secret:myapp/prod/dbmatches nothing. Usedb-*. - Expecting a name to be reusable right after deletion. The name stays reserved until the window ends or you force deletion.
Exercise
You run aws secretsmanager create-secret --name myapp/prod/db ... a second time with a new password. What happens, and which command should you use instead?
Show answer
The call fails with ResourceExistsException because create-secret does not overwrite existing secrets. Use put-secret-value to add a new version with the new password, which becomes AWSCURRENT while the old one becomes AWSPREVIOUS.
Exercise
A teammate deletes a secret with the default settings and immediately tries to create another secret with the same name. Why does it fail, and what are two ways to resolve it?
Show answer
The deleted secret is in a recovery window of 7 to 30 days (30 by default), and its name stays reserved. You can run restore-secret to cancel the deletion, or run delete-secret again with --force-delete-without-recovery to remove it permanently so the name can be reused.