Handling Secrets in Scripts

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · Automation Concepts

Handling Secrets in Scripts

Intermediate ⭐ 80 XP ⏱ 15 min #automation#secrets#security

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 them
import os
token = os.environ["API_TOKEN"]    # fail loudly if missing, never hardcode
✍️Hands-On Exercise
  1. Move a hardcoded token into an environment variable and read it in a script.
  2. Add a .env file to .gitignore and confirm git ignores it.
  3. Explain why passing a secret as a CLI flag is risky.
  4. Describe how a secrets manager improves on a static .env file in production.
🧾Cheat Sheet
PracticeHow
Read from envos.environ["X"] / $X
Local dev secretsgit-ignored .env
Never commitadd to .gitignore
Production sourceVault / Secrets Manager / Key Vault
Avoid CLI argsuse env vars or stdin
Prefershort-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