使用 Claude Code 管理环境变量与密钥的实战指南
90% 的 API Key 泄露都是人为失误。用 Claude Code 自动化 .env 管理、密钥检测与轮换。
不小心把 API Key 提交到 GitHub,瞬间冷汗直冒——每个开发者都经历过。90% 的密钥泄露都是人为失误。接入 Claude Code,你可以从 .env 初始化到检测、轮换、应急响应,机械化地强制执行安全规则。
1. 自动化 .env 初始化
新入职的开发者最头疼的就是凑齐环境变量。直接从 .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.
"
大幅加速新开发者入职流程。
2. 通过 Pre-Commit 拦截误提交
在 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 是业界标准——配合 Claude Code 还能自动修复命中项。
3. 审计已有的提交历史
检查过去的泄露是否还留存。
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 泄露的密钥 = 立即吊销并轮换
即使清理了历史,也要假设 forks 和缓存里仍然留有副本。 :::
4. 让 .env.example 保持同步
.env 变动时自动更新 .env.example。
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. 将生产密钥迁移到 Secrets Manager
把生产密钥从 .env 迁移到 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.
"
最终状态:代码与代码仓库中不再有任何生产密钥。
6. 安排定期密钥轮换
每 90 天自动轮换。
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 天轮换往往本来就是合规要求。
7. 泄露事件应急手册
事先准备好,事到临头才不会手忙脚乱。
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.
"
把安全规则写进 CLAUDE.md
约束 Claude Code 自身的行为。
## 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
这样可以降低 Claude Code 不小心把密钥硬编码进代码的概率。
反模式
❌ 放任 .env.example 走样
新成员跑不起来项目,一片混乱。务必让两者保持同步。
❌ 在 Slack / Zoom 里分享 API Key
它们会永久留在聊天记录里。请使用密钥共享工具(1Password / Doppler)。
❌ 记录敏感数据日志
console.log(req.headers) 会暴露 Authorization 头。请激进地做脱敏。
❌ 抱着”没人会发现”的心态
机器人 5 秒内就能检测并利用密钥。把每一次 commit 都当成公开发布来对待。
结语
- 交互式初始化 .env
- Pre-commit 检测密钥泄露
- 审计历史提交
- 保持 .env.example 同步
- 将生产密钥迁移到 Secrets Manager
- 自动化 90 天轮换
- 准备应急手册
- 用 CLAUDE.md 约束 AI 行为
密钥管理是系统性问题。Claude Code 让你从临时抽查切换到机械化的安全兜底。
相关阅读:安全审计 / Web 安全响应头 / Hooks 指南
官方文档:Anthropic Claude Code / gitleaks
免费 PDF:5 分钟看懂 Claude Code 速查表
只需留下邮箱,我们就会立即把这份 A4 一页速查表 PDF 发送给你。
我们会严格保护你的个人信息,绝不发送垃圾邮件。
本文作者
Masa
深度使用 Claude Code 的工程师。运营 claudecode-lab.com——一个涵盖 10 种语言、超过 2,000 页内容的科技媒体。
相关文章
Claude Code API费用完全攻略:用5个实战技巧将月账单从$450降到$45
用真实数字解析Claude Code API收费机制。通过提示词缓存、模型优化和批量处理,实现从$450到$45/月的90%费用削减——全程公开。
Claude Code 引发的7起生产事故:含RCA与预防措施的完整恢复方案
公开7起与 Claude Code 相关的真实生产事故:API密钥泄露、数据库删除、账单爆炸、服务宕机的原因、恢复步骤、根本原因分析及再发防止措施。
Claude Code的10个危险Prompt模式 | 绝对不能用的指令与安全替代方案
介绍10个绝对不能给Claude Code的危险Prompt模式。了解模糊指令如何导致代码消失、数据库毁坏、账单暴增和密钥泄露,并附上安全替代方案。