精選
CI/CD GitHub Actions GitLab Automation
CI/CD 整合:在你的 Pipeline 中使用 Claude Code
將 Claude Code 整合到 GitHub Actions 和 GitLab CI/CD。在你的開發 pipeline 中自動化 PR 審查、Issue 實作、安全稽核和文件更新。
2026年1月10日 • 20 分鐘閱讀 • 作者:ClaudeWorld
⚠️ 社群模式聲明: 本 CI/CD 整合指南描述的是社群開發的模式,而非 Claude Code 的官方功能。像
claude code review和/github-action-setup這樣的 CLI 指令是基於 Claude Code 如何整合到 CI/CD pipeline 的概念範例。官方 Claude Code 功能請參閱 docs.anthropic.com。
Claude Code 不僅僅是一個本地開發工具——它可以整合到你的 CI/CD pipeline 中,用於自動化 PR 審查、Issue 實作、安全稽核等。
本指南涵蓋 GitHub Actions 和 GitLab CI/CD 的整合模式。
為什麼要整合 CI/CD?
傳統 CI/CD:
└── 執行測試
└── 執行 linting
└── 部署(如果通過)
使用 Claude Code:
└── 執行測試
└── 執行 linting
└── AI 驅動的程式碼審查
└── 自動化安全稽核
└── 文件同步檢查
└── Issue 自動分類
└── 從 Issue 實作功能
└── 部署(如果全部通過)
GitHub Actions 整合
快速設定
/github-action-setup
這會建立以下 workflow:
- PR 審查
- Issue 分類
- 安全稽核
- 文件檢查
PR 自動審查 Workflow
# .github/workflows/claude-pr-review.yml
name: Claude PR Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- 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/claude-code
- name: Run PR Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude code review \
--pr ${{ github.event.pull_request.number }} \
--output-format github \
--post-comments
- name: Security Audit
if: contains(github.event.pull_request.labels.*.name, 'security-review')
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude code audit \
--security \
--pr ${{ github.event.pull_request.number }} \
--fail-on critical,high
Issue 自動分類 Workflow
# .github/workflows/claude-issue-triage.yml
name: Claude Issue Triage
on:
issues:
types: [opened]
jobs:
triage:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install Claude Code
run: npm install -g @anthropic/claude-code
- name: Triage Issue
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
claude code triage-issue \
--issue ${{ github.event.issue.number }} \
--add-labels \
--estimate-complexity \
--suggest-assignee
Issue 自動實作 Workflow
# .github/workflows/claude-implement-issue.yml
name: Claude Implement Issue
on:
issues:
types: [labeled]
jobs:
implement:
if: contains(github.event.label.name, 'claude-implement')
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install Dependencies
run: npm ci
- name: Install Claude Code
run: npm install -g @anthropic/claude-code
- name: Implement Feature
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
claude code implement-issue \
--issue ${{ github.event.issue.number }} \
--create-pr \
--run-tests \
--request-review
- name: Comment on Issue
if: success()
uses: actions/github-script@v7
with:
script: |
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: ${{ github.event.issue.number }},
body: '🤖 Implementation PR created. Please review.'
})
文件同步檢查
# .github/workflows/claude-doc-check.yml
name: Documentation Sync Check
on:
pull_request:
paths:
- 'src/api/**'
- 'src/lib/**'
jobs:
doc-check:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install Claude Code
run: npm install -g @anthropic/claude-code
- name: Check Documentation
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude code doc-audit \
--changed-files \
--check-api-docs \
--check-readme \
--output-format github
- name: Post Comment
if: failure()
uses: actions/github-script@v7
with:
script: |
github.rest.pulls.createReview({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: ${{ github.event.pull_request.number }},
event: 'REQUEST_CHANGES',
body: '📚 Documentation needs to be updated for API changes. Please update docs before merging.'
})
GitLab CI/CD 整合
快速設定
/gitlab-ci-setup
GitLab CI 配置
# .gitlab-ci.yml
stages:
- review
- security
- implement
- deploy
variables:
CLAUDE_MODEL: "sonnet"
# PR/MR Review
claude-review:
stage: review
image: node:20
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
script:
- npm install -g @anthropic/claude-code
- |
claude code review \
--mr $CI_MERGE_REQUEST_IID \
--output-format gitlab \
--post-comments
variables:
ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY
# Security Audit
claude-security:
stage: security
image: node:20
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
allow_failure: false
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script:
- npm install -g @anthropic/claude-code
- |
claude code audit \
--security \
--fail-on critical,high \
--output-format junit > security-report.xml
artifacts:
reports:
junit: security-report.xml
variables:
ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY
# Issue Implementation
claude-implement:
stage: implement
image: node:20
rules:
- if: $CI_PIPELINE_SOURCE == "issue"
when: manual
script:
- npm install -g @anthropic/claude-code
- npm ci
- |
claude code implement-issue \
--issue $CI_ISSUE_IID \
--create-mr \
--run-tests
variables:
ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY
GITLAB_TOKEN: $GITLAB_TOKEN
GitLab Webhook 整合
用於在 MR 中處理 @claude 提及:
# claude-mention-handler.yml
claude-mention:
stage: review
image: node:20
rules:
- if: $CI_PIPELINE_SOURCE == "chat"
script:
- npm install -g @anthropic/claude-code
- |
claude code respond-mention \
--mr $CI_MERGE_REQUEST_IID \
--comment-id $COMMENT_ID \
--context-depth 10
variables:
ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY
API 供應商選項
Anthropic API(直接)
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
AWS Bedrock
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
AWS_REGION: us-east-1
CLAUDE_PROVIDER: bedrock
CLAUDE_MODEL: anthropic.claude-3-5-sonnet-20241022-v2:0
Google Vertex AI
env:
GOOGLE_APPLICATION_CREDENTIALS: /tmp/gcp-key.json
CLAUDE_PROVIDER: vertex
CLAUDE_PROJECT_ID: ${{ secrets.GCP_PROJECT_ID }}
CLAUDE_REGION: us-east5
steps:
- name: Setup GCP Credentials
run: echo '${{ secrets.GCP_SA_KEY }}' > /tmp/gcp-key.json
Workflow 模式
模式 1:完整 PR 審查
# Complete PR review with multiple checks
jobs:
review:
strategy:
matrix:
check: [quality, security, performance, docs]
steps:
- name: Run Check
run: |
claude code review \
--type ${{ matrix.check }} \
--pr ${{ github.event.pull_request.number }}
模式 2:分階段安全審查
# Different review depth based on changed files
jobs:
security:
steps:
- name: Determine Review Depth
id: depth
run: |
if git diff --name-only ${{ github.event.pull_request.base.sha }} | grep -E 'auth/|payment/|admin/'; then
echo "depth=thorough" >> $GITHUB_OUTPUT
else
echo "depth=standard" >> $GITHUB_OUTPUT
fi
- name: Security Review
run: |
claude code audit \
--security \
--depth ${{ steps.depth.outputs.depth }} \
--fail-on critical
模式 3:Issue 到 PR Pipeline
# Complete issue to implementation pipeline
name: Issue Implementation Pipeline
on:
issues:
types: [labeled]
jobs:
analyze:
if: contains(github.event.label.name, 'auto-implement')
outputs:
complexity: ${{ steps.analyze.outputs.complexity }}
assignee: ${{ steps.analyze.outputs.assignee }}
steps:
- name: Analyze Issue
id: analyze
run: |
claude code analyze-issue \
--issue ${{ github.event.issue.number }} \
--output complexity,assignee
implement:
needs: analyze
if: needs.analyze.outputs.complexity != 'high'
steps:
- name: Implement
run: |
claude code implement-issue \
--issue ${{ github.event.issue.number }} \
--model ${{ needs.analyze.outputs.complexity == 'low' && 'haiku' || 'sonnet' }}
create-pr:
needs: implement
steps:
- name: Create PR
run: |
claude code create-pr \
--issue ${{ github.event.issue.number }} \
--assign ${{ needs.analyze.outputs.assignee }} \
--label auto-generated
安全考量
Secret 管理
# Never expose API keys
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
# Use repository secrets, not hardcoded values
# Configure in: Settings > Secrets > Actions
權限範圍限制
# Minimum required permissions
permissions:
contents: read
pull-requests: write
issues: write
# Don't use: permissions: write-all
速率限制
# Add rate limiting to prevent abuse
steps:
- name: Check Rate Limit
run: |
# Check if we've exceeded daily limit
USAGE=$(cat .claude-usage 2>/dev/null || echo "0")
if [ "$USAGE" -gt 100 ]; then
echo "Rate limit exceeded"
exit 1
fi
稽核日誌
# Log all Claude operations
steps:
- name: Run with Audit
run: |
claude code review \
--pr ${{ github.event.pull_request.number }} \
--audit-log .claude-audit.json
- name: Upload Audit Log
uses: actions/upload-artifact@v4
with:
name: claude-audit
path: .claude-audit.json
成本管理
依任務選擇模型
# Use appropriate model for task
env:
CLAUDE_MODEL: ${{ github.event.label.name == 'security-critical' && 'opus' || 'sonnet' }}
Token 預算
# Set token limits
steps:
- name: Review with Budget
run: |
claude code review \
--pr ${{ github.event.pull_request.number }} \
--max-tokens 10000
快取
# Cache Claude responses for identical inputs
steps:
- name: Setup Cache
uses: actions/cache@v4
with:
path: ~/.claude-cache
key: claude-${{ hashFiles('src/**') }}
- name: Review with Cache
run: |
claude code review \
--cache-dir ~/.claude-cache \
--pr ${{ github.event.pull_request.number }}
輸出格式
GitHub 格式
run: |
claude code review \
--output-format github \
--post-comments
輸出:
- 特定行的行內評論
- PR 上的摘要評論
- 帶有註解的 Check run
JUnit 格式
run: |
claude code audit --output-format junit > report.xml
artifacts:
reports:
junit: report.xml
輸出:
- 用於 CI 整合的 JUnit XML
- 測試套件視覺化
- 失敗追蹤
JSON 格式
run: |
claude code review --output-format json > review.json
# Process in subsequent steps
- name: Process Results
run: |
CRITICAL=$(jq '.issues | map(select(.severity == "critical")) | length' review.json)
if [ "$CRITICAL" -gt 0 ]; then
exit 1
fi
整合範例
範例 1:完整審查 Pipeline
name: Complete PR Pipeline
on:
pull_request:
types: [opened, synchronize]
jobs:
# Stage 1: Quick checks
quick-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run lint
- run: npm run typecheck
# Stage 2: Claude review (only if quick checks pass)
claude-review:
needs: quick-checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Claude Code
run: npm install -g @anthropic/claude-code
- name: Code Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude code review \
--pr ${{ github.event.pull_request.number }} \
--checks quality,patterns,security \
--post-comments
# Stage 3: Security audit (for labeled PRs)
security-audit:
needs: quick-checks
if: contains(github.event.pull_request.labels.*.name, 'needs-security-review')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Claude Code
run: npm install -g @anthropic/claude-code
- name: Security Audit
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude code audit \
--security \
--model opus \
--fail-on critical,high
# Stage 4: Tests (parallel with Claude review)
tests:
needs: quick-checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm test -- --coverage
範例 2:夜間安全掃描
name: Nightly Security Scan
on:
schedule:
- cron: '0 2 * * *' # 2 AM daily
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Claude Code
run: npm install -g @anthropic/claude-code
- name: Full Security Audit
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude code audit \
--security \
--model opus \
--depth thorough \
--output-format json > security-report.json
- name: Create Issue if Findings
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const report = JSON.parse(fs.readFileSync('security-report.json'));
if (report.critical > 0 || report.high > 0) {
github.rest.issues.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: `🚨 Security Issues Found (${report.critical} critical, ${report.high} high)`,
body: '## Security Scan Results\n\n' + report.summary,
labels: ['security', 'urgent']
});
}
疑難排解
API Key 問題
# Verify API key is set
- name: Check API Key
run: |
if [ -z "$ANTHROPIC_API_KEY" ]; then
echo "Error: ANTHROPIC_API_KEY not set"
exit 1
fi
速率限制
# Add retry with backoff
- name: Review with Retry
uses: nick-fields/retry@v2
with:
timeout_minutes: 10
max_attempts: 3
retry_wait_seconds: 60
command: |
claude code review --pr ${{ github.event.pull_request.number }}
大型 PR
# Split review for large PRs
- name: Check PR Size
id: size
run: |
FILES=$(gh pr view ${{ github.event.pull_request.number }} --json files -q '.files | length')
if [ "$FILES" -gt 50 ]; then
echo "large=true" >> $GITHUB_OUTPUT
fi
- name: Review Large PR
if: steps.size.outputs.large == 'true'
run: |
claude code review \
--pr ${{ github.event.pull_request.number }} \
--batch-size 10 \
--summary-only
最佳實踐
1. 從小處開始
# Begin with code review only
- run: claude code review --pr ${{ github.event.pull_request.number }}
# Add more features gradually
# - Security audit
# - Issue implementation
# - Documentation checks
2. 使用適當的模型
# Match model to task
# Quick review: haiku
# Standard review: sonnet
# Security/critical: opus
env:
CLAUDE_MODEL: ${{ contains(github.event.pull_request.labels.*.name, 'security') && 'opus' || 'sonnet' }}
3. 設定期望
<!-- Add to PR template -->
## AI 審查說明
此 PR 將由 Claude Code 進行審查。
審查發現是建議——請自行判斷。
標記為 critical/high 的安全問題會阻止合併。
4. 監控使用量
# Track usage for cost management
- name: Log Usage
run: |
echo "$(date): PR ${{ github.event.pull_request.number }}" >> .claude-usage.log
gh api repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments \
--method POST \
--field body="Claude review completed. Tokens used: $(cat .claude-tokens)"
開始使用
今天:
- 執行
/github-action-setup或/gitlab-ci-setup - 將 API key 新增到 repository secrets
- 在一個 PR 上測試
本週:
- 配置審查設定
- 為敏感路徑新增安全稽核
- 培訓團隊了解審查評論
本月:
- 完整 pipeline 整合
- 新增 Issue 實作
- 衡量審查品質
CI/CD 整合將 Claude Code 帶入你的自動化工作流程。每個 PR 都能獲得一致、徹底的審查。每個 Issue 都可以自動分類。你的團隊可以專注於真正重要的事情。
注意: 本指南描述的是社群開發的整合模式和概念性工作流程。所展示的特定 CLI 指令(例如 claude code review、claude code audit)是說明這種整合如何運作的範例。實際實作可能需要自訂腳本或直接使用 Claude API。
參考資料:
- Claude Code 官方文件 - 官方 Claude Code 功能
- GitHub Actions 文件 - GitHub 的 CI/CD 平台
- GitLab CI/CD 文件 - GitLab 的 CI/CD 平台
- Claude API 文件 - 用於建立自訂整合