Headless Mode 與 CI/CD 整合:打造 Claude Code 自動化開發流程

當你已經熟悉在終端機中與 Claude Code 互動,下一步自然是思考:「能不能讓 Claude Code 在沒有人的情況下自動執行?」答案是肯定的——透過 Headless Modeclaude -p),你可以將 Claude Code 整合進 CI/CD Pipeline,實現自動化的程式碼審查、Bug 修復、甚至自動產生 Commit Message。

本篇文章將完整介紹 Headless Mode 的概念與使用方式,並示範如何與 GitHub Actions、GitLab CI/CD 等主流平台整合,讓 AI 成為你開發流程中不可或缺的自動化夥伴。

什麼是 Headless Mode?

Headless Mode 是 Claude Code 的非互動式執行模式,透過 -p(或 --print)旗標啟用。在這個模式下,Claude Code 會讀取你提供的 Prompt、執行任務,然後將結果輸出到 stdout,整個過程不需要任何人為介入。

官方文件將這個功能歸類在 Agent SDK 之下,CLI 模式(claude -p)正是 Agent SDK 的一部分。它適用於以下場景:

  • CI/CD Pipeline:在 Pull Request 建立時自動執行程式碼審查
  • 腳本自動化:批次處理檔案分析、程式碼重構等任務
  • 編輯器整合:作為 IDE 外掛的後端引擎
  • 排程任務:定時執行程式碼品質檢查或文件產生

Headless Mode 基本用法

最基本的使用方式非常簡單,只要在 claude 指令後加上 -p 旗標和你的 Prompt:

# 詢問程式碼庫相關問題
claude -p "這個專案的 auth 模組做了什麼?"

# 執行程式碼分析並修復
claude -p "找出 auth.py 中的 Bug 並修復" --allowedTools "Read,Edit,Bash"

所有在互動模式下可用的 CLI 選項都可以搭配 -p 使用,包括 --continue(繼續對話)、--allowedTools(自動授權工具)、--output-format(輸出格式控制)等。

使用 –bare 加速啟動

在 CI/CD 環境中,你通常不需要載入本地的 Hooks、Skills、MCP Server 或 CLAUDE.md 等設定。加上 --bare 旗標可以跳過這些自動探索步驟,大幅縮短啟動時間,並確保每次執行的環境一致:

claude --bare -p "摘要這個檔案" --allowedTools "Read"

在 Bare Mode 下,Claude 預設可使用 Bash、檔案讀取和檔案編輯工具。如果需要額外的設定,可以透過旗標明確指定:

載入項目對應旗標
System Prompt 附加內容--append-system-prompt--append-system-prompt-file
設定檔--settings <file-or-json>
MCP Server--mcp-config <file-or-json>
自訂 Agent--agents <json>
Plugin 目錄--plugin-dir <path>

輸出格式控制

Headless Mode 支援三種輸出格式,透過 --output-format 旗標設定:

格式說明適用場景
text純文字輸出(預設)簡單的文字結果、人類可讀的報告
json結構化 JSON,包含 result、session_id 和 metadataCI/CD 整合、程式化處理結果
stream-json以換行分隔的 JSON,支援即時串流即時顯示進度、長時間任務監控

JSON 輸出範例

# 取得 JSON 格式的專案摘要
claude -p "摘要這個專案" --output-format json

# 搭配 jq 擷取特定欄位
claude -p "摘要這個專案" --output-format json | jq -r '.result'

結構化輸出(JSON Schema)

你還可以搭配 --json-schema 來指定輸出的資料結構,這在需要後續程式處理時特別有用:

claude -p "從 auth.py 中擷取所有函式名稱" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'

串流輸出

使用 stream-json 格式搭配 --verbose--include-partial-messages,可以在 Token 產生的同時即時接收:

claude -p "解釋遞迴" --output-format stream-json \
  --verbose --include-partial-messages | \
  jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'

allowedTools 安全設定

在 CI/CD 環境中,安全性至關重要。--allowedTools 讓你精確控制 Claude 可以使用哪些工具,避免未經授權的操作:

# 只允許讀取和編輯檔案
claude -p "修正所有 TypeScript 型別錯誤" --allowedTools "Read,Edit"

# 允許特定的 Git 指令(使用前綴匹配)
claude -p "檢視暫存區變更並建立 Commit" \
  --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

注意 --allowedTools 使用權限規則語法,其中 Bash(git diff *) 表示允許所有以 git diff 開頭的指令。* 前面的空格很重要——沒有空格的話,Bash(git diff*) 也會匹配到 git diff-index 這類指令。

Permission Mode

除了個別指定工具,你也可以使用 --permission-mode 設定全域權限模式:

模式行為適用場景
dontAsk拒絕所有不在 permissions.allow 規則中的操作嚴格鎖定的 CI 環境
acceptEdits允許檔案編輯,但 Shell 指令和網路請求仍需授權需要自動修改程式碼的場景
# 使用 acceptEdits 模式自動修復 Lint 問題
claude -p "修復所有 lint 錯誤" --permission-mode acceptEdits

環境變數與 API Key 管理

在 CI/CD 環境中,Claude Code 透過環境變數 ANTHROPIC_API_KEY 進行認證,自動略過互動式的 OAuth 流程。這是最安全的做法,因為它能與所有主流 CI/CD 平台的 Secrets 管理系統無縫整合。

各平台的 Secrets 設定方式

平台設定位置參考文件
GitHub ActionsSettings → Secrets and variables → ActionsGitHub Docs – Using secrets
GitLab CI/CDSettings → CI/CD → Variables(勾選 Masked)GitLab Docs – CI/CD Variables
JenkinsManage Jenkins → Credentials → SystemJenkins Credentials Plugin

重要安全提醒:絕對不要將 API Key 直接寫死在程式碼或設定檔中。務必使用各平台提供的 Secrets 機制來管理敏感資訊。

GitHub Actions 整合

GitHub Actions 是目前最主流的 CI/CD 平台之一,Anthropic 官方也提供了 anthropics/claude-code-action 這個 Action,讓整合變得非常簡單。

快速設定

最快的設定方式是在 Claude Code 終端機中執行 /install-github-app,它會引導你完成 GitHub App 安裝和 Secrets 設定。如果你偏好手動設定,步驟如下:

  1. 安裝 Claude GitHub App 到你的 Repository
  2. 在 Repository 的 Settings → Secrets 中新增 ANTHROPIC_API_KEY
  3. 將 Workflow 檔案複製到 .github/workflows/ 目錄

基本 Workflow:@claude 互動

這個 Workflow 讓團隊成員可以在 PR 或 Issue 中透過 @claude 觸發 Claude:

name: Claude Code
on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
jobs:
  claude:
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

自動化 PR Code Review

每當 PR 被建立或更新時,Claude 會自動進行程式碼審查:

name: Code Review
on:
  pull_request:
    types: [opened, synchronize]
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: "Review this pull request for code quality, correctness, and security. Analyze the diff, then post your findings as review comments."
          claude_args: "--max-turns 5"

自動修復與 Commit

結合 Headless Mode 的工具權限控制,你可以讓 Claude 自動檢視暫存區變更並建立 Commit:

claude -p "檢視我的暫存區變更並建立適當的 Commit" \
  --allowedTools "Bash(git diff *),Bash(git log *),Bash(git status *),Bash(git commit *)"

GitLab CI/CD 整合

GitLab CI/CD 的整合方式是在 .gitlab-ci.yml 中新增一個 Claude 任務,目前此功能為 Beta 階段,由 GitLab 官方維護。

基本設定

  1. 在 Settings → CI/CD → Variables 中新增 ANTHROPIC_API_KEY(勾選 Masked)
  2. .gitlab-ci.yml 中加入 Claude 任務
stages:
  - ai

claude:
  stage: ai
  image: node:24-alpine3.21
  rules:
    - if: '$CI_PIPELINE_SOURCE == "web"'
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
  variables:
    GIT_STRATEGY: fetch
  before_script:
    - apk update
    - apk add --no-cache git curl bash
    - curl -fsSL https://claude.ai/install.sh | bash
  script:
    - |
      claude \
        -p "${AI_FLOW_INPUT:-'Review this MR and implement the requested changes'}" \
        --permission-mode acceptEdits \
        --allowedTools "Bash Read Edit Write mcp__gitlab" \
        --debug

設定完成後,你可以在 Merge Request 中使用 @claude 觸發 Claude,或從 CI/CD → Pipelines 手動執行任務。

Jenkins 整合

雖然 Anthropic 官方目前沒有提供 Jenkins 專用的外掛,但你可以透過 Headless Mode 輕鬆整合。核心概念是在 Jenkins Pipeline 中安裝 Claude Code CLI,然後使用 claude -p 執行任務。

pipeline {
  agent any
  environment {
    ANTHROPIC_API_KEY = credentials('anthropic-api-key')
  }
  stages {
    stage('Install Claude Code') {
      steps {
        sh 'curl -fsSL https://claude.ai/install.sh | bash'
      }
    }
    stage('Code Review') {
      steps {
        sh '''
          claude --bare -p "Review the changes in this build and report any issues" \
            --allowedTools "Read,Bash(git diff *),Bash(git log *)" \
            --output-format json > review-report.json
        '''
      }
    }
    stage('Process Results') {
      steps {
        sh 'cat review-report.json | jq -r .result'
      }
    }
  }
}

對話延續與多步驟任務

Headless Mode 支援對話延續功能,讓你可以在多個步驟之間保持上下文。這在複雜的 CI/CD 流程中特別有用:

# 第一步:進行程式碼審查
claude -p "審查這個程式碼庫的效能問題"

# 第二步:延續上一次對話,深入分析
claude -p "現在專注於資料庫查詢的部分" --continue

# 第三步:產生總結報告
claude -p "產生所有發現問題的摘要報告" --continue

如果你同時執行多個對話,可以擷取 Session ID 來指定要延續的對話:

# 擷取 Session ID
session_id=$(claude -p "開始審查" --output-format json | jq -r '.session_id')

# 使用 --resume 延續特定對話
claude -p "繼續剛才的審查" --resume "$session_id"

自訂 System Prompt

使用 --append-system-prompt 可以在保留 Claude Code 預設行為的同時,加入你自己的指令。例如,將 PR Diff 導入 Claude 並指示它以安全工程師的角度進行審查:

gh pr diff "$PR_NUMBER" | claude -p \
  --append-system-prompt "你是一位安全工程師。請審查是否有安全漏洞。" \
  --output-format json

實際 Workflow 範例:完整的 PR 自動化流程

以下是一個結合多種功能的完整 GitHub Actions Workflow,涵蓋了自動 Code Review、問題分類和 @claude 互動回應:

name: Claude Code Complete Workflow
on:
  pull_request:
    types: [opened, synchronize]
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]

jobs:
  # Job 1: PR 開啟時自動進行 Code Review
  auto-review:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Review this PR for:
            1. Code quality and best practices
            2. Potential bugs or edge cases
            3. Security vulnerabilities
            4. Performance concerns
            Post findings as review comments.
          claude_args: "--max-turns 5 --model claude-sonnet-4-6"

  # Job 2: 回應 @claude 互動
  respond:
    if: |
      (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude'))
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}

成本與效能優化建議

在 CI/CD 環境中使用 Claude Code 時,需要注意以下成本和效能相關的事項:

  • 設定 –max-turns:限制對話輪次,避免無限迴圈造成不必要的 API 費用
  • 使用 –bare 模式:跳過不必要的初始化,加速 CI 任務執行
  • 精確指定 @claude 觸發:避免不必要的 API 呼叫
  • 設定 Workflow 層級的 Timeout:防止任務失控
  • 善用 CLAUDE.md:在專案根目錄建立 CLAUDE.md,定義程式碼風格、審查標準和專案規則,讓 Claude 的回應更精準
  • 使用 GitHub 的 Concurrency 控制:限制平行執行的數量

延伸閱讀

總結

Headless Mode 是將 Claude Code 從個人開發工具提升為團隊級自動化基礎設施的關鍵功能。透過 claude -p,你可以在任何 CI/CD 平台上執行 AI 驅動的程式碼審查、自動修復、文件生成等任務,而 --allowedTools--permission-mode 則確保了執行過程的安全性。

無論你使用 GitHub Actions、GitLab CI/CD 還是 Jenkins,整合的核心概念都相同:設定 API Key → 安裝 Claude Code → 使用 claude -p 執行任務。從今天開始,讓 AI 成為你 CI/CD Pipeline 中最可靠的自動化夥伴吧!