Handling Secrets in Scripts
Keep credentials out of your code and logs when automating.
Theory
Automation needs credentials, but hardcoding them is a top cause of breaches. The rules:
- Never commit secrets to a repo — they live forever in git history
- Read secrets from the environment or a secrets manager at runtime
- Keep them out of logs, process lists, and error messages
- Prefer short-lived credentials and workload identity over static keys
For local dev, a git-ignored .env file is fine; in production, inject from Vault,
AWS Secrets Manager, Azure Key Vault, or the CI platform’s encrypted store.
Real-World Example
# Bad: secret in code and visible in process list
curl -H "Authorization: Bearer sk_live_abc123" https://api...
# Good: from the environment
export API_TOKEN="$(vault kv get -field=token secret/api)"
curl -H "Authorization: Bearer $API_TOKEN" https://api...
# .gitignore the env file
echo ".env" >> .gitignore
set -a; source .env; set +a # load vars without echoing themimport os
token = os.environ["API_TOKEN"] # fail loudly if missing, never hardcode Hands-On Exercise
- Move a hardcoded token into an environment variable and read it in a script.
- Add a
.envfile to.gitignoreand confirm git ignores it. - Explain why passing a secret as a CLI flag is risky.
- Describe how a secrets manager improves on a static
.envfile in production.
Cheat Sheet▾
| Practice | How |
|---|---|
| Read from env | os.environ["X"] / $X |
| Local dev secrets | git-ignored .env |
| Never commit | add to .gitignore |
| Production source | Vault / Secrets Manager / Key Vault |
| Avoid CLI args | use env vars or stdin |
| Prefer | short-lived / workload identity |
Common Interview Questions▾
Where should secrets come from in an automation script?
From the environment or a secrets manager at runtime — never hardcoded in source or committed to version control, where they persist in history.
Why is passing a secret as a command-line argument risky?
Command-line arguments appear in process listings (ps) and shell history, exposing the secret to other users and logs. Use environment variables or stdin instead.
Official Documentation
📝 My notes on this topic
Auto-saves as you type