Hands-On: Store & Read a Secret
Create a secret, then read it from Lambda efficiently with caching.
Secrets can be plain strings or JSON key/value pairs. JSON is handy for groups of related values:
aws secretsmanager create-secret --name notesnap/email-api --secret-string '{"apiKey": "sk_live_abc123", "sender": "hello@notesnap.app"}'Read it in Lambda. Fetch it outside the handler so warm invocations reuse the value instead of calling Secrets Manager every time:
Try it
import json
import os
import boto3
_secrets = boto3.client("secretsmanager")
def load_secret(name):
return json.loads(_secrets.get_secret_value(SecretId=name)["SecretString"])
# Loaded once per cold start, then cached for warm invocations
EMAIL = load_secret(os.environ.get("EMAIL_SECRET", "notesnap/email-api"))
def lambda_handler(event, context):
send_email(api_key=EMAIL["apiKey"], sender=EMAIL["sender"], to=event["to"])
return {"sent": True}The function's role needs secretsmanager:GetSecretValue on that secret's ARN only, plus kms:Decrypt
if you encrypted it with your own KMS key.
If your secrets rotate, caching forever means old values linger. Refresh the cache every few minutes, or use the AWS Parameters and Secrets Lambda Extension, which caches with a configurable TTL.
Never print() a secret. Logs are much more widely readable than the secret itself.
Key takeaways
- create-secret stores a string or JSON value.
- Fetch secrets outside the handler and cache them, refreshing if they rotate.
- Grant GetSecretValue on specific secret ARNs only, and never log secret values.
Check your understanding
Pick an answer to see the explanation.
1. Why load the secret outside the handler?