如何在 GitHub Actions 中使用 Claude Code (2026)
在 CI/CD 中实现 AI 驱动的代码审查和生成自动化
开始使用 Hypereal 构建
通过单个 API 访问 Kling、Flux、Sora、Veo 等。免费积分开始,扩展到数百万。
无需信用卡 • 10万+ 开发者 • 企业级服务
如何在 GitHub Actions 中使用 Claude Code (2026)
Claude Code 是 Anthropic 推出的 CLI 工具,可将 Claude 直接引入您的终端和代码库。通过将其集成到 GitHub Actions 中,您可以实现 AI 驱动的代码审查自动化、生成 PR 摘要、运行自动重构,并为 CI/CD 流水线添加智能质量检测。本指南将逐步介绍如何进行配置。
Claude Code 在 CI/CD 中能做什么?
以下是 Claude Code 在 GitHub Actions 中最实用的场景:
| 使用场景 | 描述 | 触发条件 |
|---|---|---|
| PR 代码审查 | 提供改进建议的自动化审查 | Pull request 已创建/已更新 |
| PR 摘要 | 根据差异(diff)生成描述 | Pull request 已创建 |
| 缺陷检测 | 扫描修改后的文件以查找常见 bug | Pull request, push |
| 文档编写 | 为新函数自动生成文档 | Pull request |
| 测试生成 | 为变更的代码创建测试用例 | Pull request |
| 迁移辅助 | 针对依赖项变更提供更新建议 | 定时任务, 手动触发 |
前提条件
- 一个 GitHub 仓库
- Anthropic API key(在 console.anthropic.com 获取)
- 对 GitHub Actions YAML 语法有基本了解
第 1 步:将 API Key 存储为 Secret
切勿在工作流文件中硬编码 API Key。请将您的 Anthropic API key 添加为 GitHub 仓库的 secret:
1. 进入 GitHub 上的仓库
2. 点击 Settings > Secrets and variables > Actions
3. 点击 "New repository secret"
4. 名称 (Name): ANTHROPIC_API_KEY
5. 值 (Value): sk-ant-xxxxx (您的 key)
6. 点击 "Add secret"
第 2 步:基础 Claude Code 工作流
在 .github/workflows/claude-review.yml 处创建一个工作流文件:
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
permissions:
contents: read
pull-requests: write
jobs:
claude-review:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0 # 获取完整历史记录以进行 diff
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Get PR diff
id: diff
run: |
git diff origin/${{ github.base_ref }}...HEAD > pr_diff.txt
echo "diff_size=$(wc -c < pr_diff.txt)" >> $GITHUB_OUTPUT
- name: Run Claude Code Review
if: steps.diff.outputs.diff_size > 0
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude -p --output-format text "$(cat <<'PROMPT'
Review the following pull request diff. Focus on:
1. Potential bugs or logic errors
2. Security concerns
3. Performance issues
4. Code style and readability
Be concise. Only mention real issues, not style nitpicks.
Format your response as a markdown list.
Diff:
$(cat pr_diff.txt)
PROMPT
)" > review_output.md
- name: Post review comment
if: steps.diff.outputs.diff_size > 0
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('review_output.md', 'utf8');
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `## Claude Code Review\n\n${review}\n\n---\n*Automated review by Claude Code*`
});
第 3 步:PR 摘要生成器
根据代码变更自动生成 PR 描述:
name: Claude PR Summary
on:
pull_request:
types: [opened]
permissions:
contents: read
pull-requests: write
jobs:
generate-summary:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Generate PR summary
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
# 获取 diff
DIFF=$(git diff origin/${{ github.base_ref }}...HEAD)
# 获取提交信息
COMMITS=$(git log origin/${{ github.base_ref }}...HEAD --oneline)
claude -p --output-format text "$(cat <<PROMPT
Generate a pull request summary based on these changes.
Format:
## Summary
(2-3 sentences describing what this PR does)
## Changes
(Bulleted list of key changes)
## Testing
(Suggested testing steps)
Commits:
$COMMITS
Diff:
$DIFF
PROMPT
)" > summary.md
- name: Update PR description
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const summary = fs.readFileSync('summary.md', 'utf8');
await github.rest.pulls.update({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number,
body: summary
});
第 4 步:自动化测试生成
为新文件或修改后的文件生成测试:
name: Claude Test Generator
on:
pull_request:
types: [opened, synchronize]
paths:
- "src/**/*.ts"
- "src/**/*.js"
- "!src/**/*.test.*"
- "!src/**/*.spec.*"
permissions:
contents: write
pull-requests: write
jobs:
generate-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: ${{ github.head_ref }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install dependencies
run: |
npm ci
npm install -g @anthropic-ai/claude-code
- name: Find changed files without tests
id: changed
run: |
FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD \
| grep -E '^src/.*\.(ts|js)$' \
| grep -v -E '\.(test|spec)\.' \
| head -5)
echo "files=$FILES" >> $GITHUB_OUTPUT
- name: Generate tests with Claude
if: steps.changed.outputs.files != ''
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
for FILE in ${{ steps.changed.outputs.files }}; do
TEST_FILE="${FILE%.ts}.test.ts"
if [ ! -f "$TEST_FILE" ]; then
echo "Generating tests for $FILE..."
claude -p --output-format text \
"Read the file $FILE and generate comprehensive unit tests for it. \
Use the existing test framework in this project. \
Output only the test file content, no explanations." \
> "$TEST_FILE"
fi
done
- name: Commit generated tests
run: |
git config user.name "claude-code[bot]"
git config user.email "claude-code[bot]@users.noreply.github.com"
git add "src/**/*.test.ts"
git diff --staged --quiet || git commit -m "test: add AI-generated tests for changed files"
git push
第 5 步:安全扫描工作流
使用 Claude 识别代码变更中的安全问题:
name: Claude Security Scan
on:
pull_request:
types: [opened, synchronize]
permissions:
contents: read
pull-requests: write
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: Run security analysis
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
DIFF=$(git diff origin/${{ github.base_ref }}...HEAD)
claude -p --output-format text "$(cat <<PROMPT
Analyze this code diff for security vulnerabilities.
Check for:
- SQL injection
- XSS vulnerabilities
- Hardcoded secrets or credentials
- Insecure deserialization
- Path traversal
- Missing input validation
- Insecure dependencies
If no issues found, respond with "No security issues detected."
If issues found, list each with severity (HIGH/MEDIUM/LOW),
the file and line, and a suggested fix.
Diff:
$DIFF
PROMPT
)" > security_report.md
- name: Post security report
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const report = fs.readFileSync('security_report.md', 'utf8');
if (!report.includes('No security issues detected')) {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: `## Security Scan Results\n\n${report}\n\n---\n*Scanned by Claude Code*`
});
}
成本管理
在 CI/CD 中使用 Claude Code 可能会快速消耗 API 额度。以下是控制成本的策略:
| 策略 | 实现方式 |
|---|---|
| 限制 Diff 大小 | 截断超过 10,000 行的 diff |
| 跳过草稿 PR | 添加 if: github.event.pull_request.draft == false |
| 按文件类型过滤 | 在触发器中使用 paths 过滤器 |
| 使用缓存 | 缓存 Claude Code 的 npm 安装过程 |
| 速率限制 | 仅在最后一次 commit 时运行,而非每次 push |
使用 --max-turns 1 |
防止 Agent 进入多轮对话循环 |
Diff 大小防护门限制
- name: Check diff size
id: size_check
run: |
DIFF_LINES=$(git diff origin/${{ github.base_ref }}...HEAD | wc -l)
if [ "$DIFF_LINES" -gt 5000 ]; then
echo "skip=true" >> $GITHUB_OUTPUT
echo "Diff too large ($DIFF_LINES lines), skipping AI review"
else
echo "skip=false" >> $GITHUB_OUTPUT
fi
- name: Run Claude review
if: steps.size_check.outputs.skip == 'false'
# ... step 的其余部分
故障排除
| 问题 | 原因 | 解决方案 |
|---|---|---|
| "API key not found" | Secret 未配置 | 将 ANTHROPIC_API_KEY 添加到仓库 secrets |
| 工作流超时 | Diff 过大或响应缓慢 | 在 job 中添加 timeout-minutes: 10 |
| 审查输出为空 | Diff 超过上下文长度 | 截断 diff 或仅审查特定文件 |
| PR 评论权限被拒绝 | 缺少权限配置 | 在 permissions 中添加 pull-requests: write |
| 找不到 Claude Code | 安装失败 | 固定 npm 版本:npm install -g @anthropic-ai/claude-code@latest |
最佳实践
- 设置超时。 添加
timeout-minutes: 10以防止无休止的工作流运行。 - 使用
--print模式。 在 CI 中务必使用claude -p以避免交互式提示。 - 限制上下文。 仅发送 diff 和相关文件,不要发送整个代码库。
- 从容处理失败。 使用
continue-on-error: true,确保 AI 审查不会阻塞代码合并。 - 审视 AI 输出。 将 Claude 的评论视为建议,而非权威裁定。
- 固定版本。 固定 Claude Code 和 action 的版本以确保构建的可复现性。
结论
将 Claude Code 集成到 GitHub Actions 中可以为您的 CI/CD 流水线增添一个智能层。无论您将其用于代码审查、PR 摘要、测试生成还是安全扫描,其配置过程都非常直接:安装 Claude Code、传递 diff 并发布结果。关键在于通过过滤触发器和限制 diff 大小来管理成本。
对于正在构建 AI 生成媒体(视频、图像或数智人)应用程序的开发团队,Hypereal AI 提供了生产级的 API,可自然地集成到 CI/CD 流水线中,实现自动化的资源生成和测试。
