Sub topic 15
When to Move to a Secret Manager
This chapter assumes you already know the earlier material. That means environment variables, a git-ignored .env file, CI secrets, and the steps for revoking and rotating a key. It also assumes you can read short Python snippets and have a rough idea of how cloud permissions work. The examples use AWS Secrets Manager. The ideas apply to any secret manager.
What a secret manager adds
A secret manager is a service that stores secrets encrypted, controls who can read them, and records each read. Examples are AWS Secrets Manager, Google Secret Manager, Azure Key Vault, HashiCorp Vault, and Doppler. Your application asks the service for the key when it needs it. The key is not copied into a file or a deploy configuration first.
Environment variables and .env files only hold a value. They do not control who can read it, and they do not record who did. A secret manager adds these features:
- Access control per secret. You decide which identities can read which secrets.
- Audit logs. Each read is recorded with the caller and the time.
- Versioning. You can store a new key version next to the old one and roll back.
- Rotation support. Some managers can run a rotation on a schedule.
- One source of truth. Ten services read the same secret instead of ten copies.
Compare this with the setup you built earlier. A key set as an environment variable in a deploy tool lives in that tool's settings, in the process environment, and often in someone's notes. Revoking it means finding every copy. With a manager there is one copy to update.
Signs you have outgrown environment variables
You do not need a secret manager on day one. A solo project with one key, one server, and one developer is well served by environment variables or CI secrets. Move when you see problems like these:
- Several people or teams need the key. You are pasting it into chat or documents to share it.
- Several services or environments use it. You have copies in staging, production, workers, and scheduled jobs, and they drift apart.
- You must rotate on a schedule. A policy or customer contract requires it, and manual rotation is error-prone.
- You need to know who read the key. After an incident, "someone with access to the deploy tool" is not an answer.
- Staff turnover. Someone who knew the key leaves, and you cannot prove which secrets they could see.
- Compliance requirements. Standards such as SOC 2 expect access control and logging for credentials.
- You hold many secrets. An LLM key is joined by database passwords, webhook signing secrets, and other provider keys.
One or two of these signs may not justify the extra work. Three or more usually do.
What a manager does not fix
A secret manager moves the problem. It does not remove it. Keep these limits in mind:
- Your code still ends up holding the key in memory. If your app logs the key, prints it in an error, or returns it in a response, the manager cannot help.
- Access to the manager becomes the new secret. Your app needs credentials to read secrets. If those credentials are a long-lived access key stored in an environment variable, you have only moved the problem one step back.
- It costs money and adds a dependency. Managed services charge per secret and per API call. If the manager is unreachable at startup, your app may not start.
- It adds operational work. Someone must set up policies, review access, and keep the configuration current.
Reducing the "secret zero" problem
The question of how your app first proves who it is to the manager is called the secret zero problem. The best answer is to avoid storing any credential at all. Cloud platforms give workloads an identity, such as an AWS IAM role attached to a Lambda function, container task, or virtual machine. The platform signs requests for you, and short-lived credentials are issued automatically. Your code and configuration contain no access key.
In CI, use the provider's federation feature where it exists. For example, GitHub Actions can obtain short-lived AWS credentials through OpenID Connect instead of storing a long-lived AWS key as a repository secret.
Least-privilege access
Give the application permission to read only its own secret. This AWS IAM policy allows reading one secret and nothing else. The -* at the end is needed because AWS adds a random suffix to the secret's full name.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "secretsmanager:GetSecretValue",
"Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/llm/api-key-*"
}
]
}The account ID and region above are placeholders. Replace them with your own. Do not grant the application permission to list or change secrets. A compromised app should not be able to read your other secrets or overwrite this one.
Reading the key in code
The pattern is the same as before, except that the value comes from the manager and not from os.environ. The environment now holds only the secret's name, which is not sensitive.
import os
import time
import boto3 # pip install boto3
CACHE_SECONDS = 300
_client = boto3.client("secretsmanager")
_cache = {"value": None, "fetched_at": 0.0}
def get_llm_api_key(force_refresh: bool = False) -> str:
"""Return the LLM key, refreshing it from the manager every few minutes."""
now = time.monotonic()
expired = now - _cache["fetched_at"] > CACHE_SECONDS
if force_refresh or _cache["value"] is None or expired:
response = _client.get_secret_value(SecretId=os.environ["LLM_SECRET_ID"])
_cache["value"] = response["SecretString"]
_cache["fetched_at"] = now
return _cache["value"]This code needs an AWS region, which comes from the AWS_REGION environment variable or your AWS configuration. It also needs LLM_SECRET_ID set to something like prod/llm/api-key.
The cache matters for two reasons. Each call to the manager costs money and adds latency, so you do not want one per LLM request. A cache that never expires has the opposite problem. After you rotate the key, the app keeps using the old value until it restarts. A short time limit balances the two.
If the provider rejects the key with an authentication error, call get_llm_api_key(force_refresh=True) once and retry. This handles a rotation that happened between cache refreshes.
Rotation with a manager
Rotation becomes simpler because the new key goes in one place. A common sequence is:
- Create a new key in the provider console.
- Store it as a new version of the secret.
- Wait for running apps to refresh their cache, or restart them.
- Check the audit log and the provider's usage page to confirm that nothing still uses the old key.
- Revoke the old key in the provider console.
Some managers can run steps 1 and 2 automatically with a rotation function, but only if the provider has an API for creating keys. Many LLM providers do not, so rotation often stays partly manual. Check your provider's documentation before planning around automation.
Choosing an option
| Option | Fits when | Main limit |
|---|---|---|
| `.env` file | Local development, one person | No access control or logging |
| Environment variable on the host | One service, small team | Copies spread across tools |
| CI secrets | Pipelines and tests | Scoped to the CI system only |
| Cloud secret manager | Several services, audit needs, cloud-hosted | Costs money, ties you to a platform |
| Self-hosted Vault or similar | Multi-cloud or strict control | You operate and secure it yourself |
If your app already runs on one cloud provider, use that provider's manager. It integrates with the identity system you already have. Choose a self-hosted option only when you have a reason and someone to operate it.
Common mistakes
- Storing the manager's own access key in a
.envfile or CI variable when a platform identity was available. - Granting wildcard read access such as
secretsmanager:*on all secrets, so one compromised service exposes everything. - Fetching the secret on every request, which raises cost and adds failures when the manager is slow.
- Caching forever, so a rotated or revoked key keeps being used.
- Skipping the audit log review. Logs that nobody reads do not help during an incident. Set an alert on unusual reads.
- Adopting a manager too early for a prototype, and spending days on setup that a CI secret would have covered.
Exercise
Your team runs a chatbot on AWS with three services that call the same LLM provider. You store the provider key in an AWS Secrets Manager secret. Describe how each service should get access without storing any AWS access key, and name one thing your code should do to handle key rotation.
Show answer
Attach an IAM role to each service (for example, a task role or function role) with a policy that allows only secretsmanager:GetSecretValue on that one secret's ARN. The services then receive short-lived credentials from the platform, so no AWS access key is stored in code, configuration, or CI. To handle rotation, cache the key for a short time (for example, five minutes) instead of forever, and on an authentication error from the LLM provider, refetch the secret once and retry. After all services use the new version, revoke the old key at the provider.