Tips & Tricks

A Practical Guide to Managing Env Vars and Secrets with Claude Code

90% of API key leaks are human error. Use Claude Code to automate .env management, secret detection, and rotation.

Accidentally commit an API key to GitHub and you’ll break into a cold sweat — every developer has been there. 90% of secret leaks are human error. Wire Claude Code in and you can mechanically enforce safety from .env setup through detection, rotation, and incident response.

1. Automate .env Setup

New developers struggle to gather env vars. Generate from .env.example.

claude -p "
Read .env.example and interactively create a .env for this project.

For each variable:
1. What it's for
2. Where to get it (with URLs)
3. Recommended local dev value
4. Required or optional

Confirm .env is gitignored before saving.
"

Drastically speeds up new developer onboarding.

2. Block Accidental Commits via Pre-Commit

Catch secrets the moment someone runs git commit.

claude -p "
Create .husky/pre-commit.

Requirements:
- Check staged files for:
  - AWS access keys: AKIA[0-9A-Z]{16}
  - Stripe: sk_live_[0-9a-zA-Z]{24}
  - GitHub PAT: ghp_[0-9a-zA-Z]{36}
  - Generic API-key-looking strings
- Reject commit and show file/line on detection
- Allow // secrets-ignore comment for false positives

Also compare with trufflehog and gitleaks, and
recommend a team-friendly setup.
"

gitleaks is the industry standard — combined with Claude Code it can auto-remediate findings.

3. Audit Existing Commit History

Check whether past leaks remain.

claude -p "
Scan the entire commit history for secrets:

1. Run gitleaks detect --source . --no-git
2. Categorize findings (active / already revoked / false positive)
3. For active leaks, show immediate rotation steps
4. Git history purge steps (git filter-branch or BFG Repo Cleaner)

Output to docs/security/secret-audit.md (treat as confidential).
"

:::message alert Leaked secrets = immediately revoke and rotate

Even if you purge history, assume forks and caches still have it. :::

4. Keep .env.example in Sync

Update .env.example automatically when .env changes.

claude -p "
Compare .env and .env.example:

1. Vars in .env but not .env.example → add with placeholders
2. Vars in .env.example but not .env → propose removal if obsolete
3. Improve comments (purpose docs)
4. Confirm secret values remain as placeholders

Save .env.example in a git-diff-reviewable state.
"

5. Migrate Production Secrets to a Secrets Manager

Move prod secrets from .env to AWS Secrets Manager / Cloudflare Secrets / Doppler.

claude -p "
Migrate 10 production secrets from .env to AWS Secrets Manager:

1. aws secretsmanager create-secret commands
2. Least-privilege IAM read policy
3. App-side fetch code (with caching)
4. Deploy procedure (cut over from .env)
5. Rollback plan

Output Terraform definitions too.
"

End state: no production secrets live in code or repos.

6. Schedule Periodic Secret Rotation

Rotate every 90 days, automatically.

claude -p "
Design a script to auto-rotate API keys for Stripe, OpenAI, Resend every 90 days:

1. Issue new keys via each service's API
2. Save to Secrets Manager / Cloudflare Secrets
3. Trigger deploy to pick up new keys
4. Revoke old keys
5. Append to docs/security/rotation-log.md

Provide a monthly GitHub Actions schedule YAML.
"

90-day rotation is often a compliance requirement anyway.

7. Incident Playbook for Leaks

Prepare so you don’t panic when it happens.

claude -p "
Write docs/security/incident-playbook.md for:

Scenario: AWS access key accidentally committed to a public GitHub repo

0-15 min:
- Revoke key in AWS Console
- Make the repo private

15 min - 1 hour:
- Check CloudTrail for unauthorized use
- Remove key from git history (git filter-branch)
- Issue new key, register in Secrets Manager

1 hour+:
- Notify security team
- Decide on customer disclosure

Include exact commands and designated owners.
"

Encode Security Rules in CLAUDE.md

Constrain Claude Code’s own behavior.

## Secret Handling Rules

### Forbidden
- Hardcoding .env values in source code
- Logging API keys (including console.log)
- Putting secrets in comments
- Putting secrets in README / docs

### Required
- Update .env.example whenever API keys change
- Register new external service keys in Secrets Manager
- Pre-commit secret scan must pass

### AI Instructions
- Always use process.env.XXX for key values in generated code
- Never copy .env contents elsewhere
- Route secret-related changes through human review

This reduces the chance Claude Code accidentally hardcodes a key.

Anti-Patterns

❌ Letting .env.example drift

New hires can’t run the app and chaos ensues. Keep them in sync.

❌ Sharing API keys in Slack / Zoom

They live forever in history. Use secret-sharing tools (1Password / Doppler).

❌ Logging sensitive data

console.log(req.headers) exposes the Authorization header. Mask aggressively.

❌ Assuming “no one will notice”

Bots detect and mine keys within 5 seconds. Treat every commit as public.

Conclusion

  • Interactively set up .env
  • Pre-commit detects secret leaks
  • Audit historical commits
  • Keep .env.example in sync
  • Migrate prod secrets to a Secrets Manager
  • Automate 90-day rotation
  • Prepare an incident playbook
  • Constrain AI behavior in CLAUDE.md

Secret management is a systemic problem. Claude Code lets you shift from ad-hoc checks to mechanical safety nets.

Related: Security Audit / Web Security Headers / Hooks Guide

Official docs: Anthropic Claude Code / gitleaks

#claude-code #security #secrets-management #devops

Level up your Claude Code workflow

50 battle-tested prompt templates you can copy-paste into Claude Code right now.

Free

Free PDF: Claude Code Cheatsheet in 5 Minutes

Just enter your email and we'll send you the single-page A4 cheatsheet right away.

We handle your data with care and never send spam.

Masa

About the Author

Masa

Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.