Automatisierung & CI/CD
Claude Code Headless-Modus im Detail — vollständige Flag-Referenz, fünf CI/CD-Rezepte, Docker-Isolation, Session-Fortsetzung und ein Codex-Vergleich
Auf dieser Seite
Claude Code unterstützt einen Headless-Modus, den Sie in Skripten, CI/CD-Pipelines und automatisierten Workflows ohne menschliche Interaktion verwenden können. Dieser Artikel behandelt die vollständige Flag-Referenz sowie mehrere praxisnahe Szenarien.
1. Grundlegende Verwendung¶
Einmalige Ausführung (-p-Modus)¶
# Basic run
claude -p "Analyse this project's architecture"
# JSON output
claude -p "List every TODO comment" --output-format json
# Cap the number of turns
claude -p "Write unit tests for UserService" --max-turns 5
# Pick a model (claude-sonnet-5 for everyday work; 4.x is still on sale)
claude -p "Review the code for security issues" --model claude-opus-5
Einschränkung der verfügbaren Tools¶
# Read-only analysis (no writes, no command execution)
claude -p "Analyse code quality" --allowedTools Read,Glob,Grep
# Read and write (no command execution)
claude -p "Refactor this file" --allowedTools Read,Write,Edit,Glob,Grep
# All tools (controlled environment)
claude -p "Fix the lint errors" --allowedTools Read,Write,Edit,Bash,Glob,Grep
Überspringen von Berechtigungsabfragen¶
# Only in a safe, isolated environment!
claude -p "Fix every lint error and commit" --dangerously-skip-permissions
Warnung zur Sicherheit:
--dangerously-skip-permissionsüberspringt jede Berechtigungsbestätigung. Verwenden Sie diese Option nur innerhalb eines Docker-Containers oder einer isolierten CI-Umgebung.
2. Vollständige Flag-Referenz¶
Ausführungssteuerung¶
| Flag | Funktion | Beispiel |
|---|---|---|
-p "prompt" |
Headless-Modus, einzelne Aufgabe ausführen | claude -p "analyse the architecture" |
--bare |
Minimalmodus, überspringt Hooks/LSP/Plugins | claude --bare -p "..." |
--max-turns N |
Maximale Anzahl der Interaktionsrunden begrenzen | --max-turns 5 |
--model MODEL |
Modell auswählen | --model claude-opus-5 |
--dangerously-skip-permissions |
Jede Berechtigungsbestätigung überspringen | Nur isolierte Umgebungen |
Ausgabeformate¶
| Flag | Funktion | Wann verwenden |
|---|---|---|
--output-format text |
Klartext (Standard) | Für Menschen |
--output-format json |
Strukturiertes JSON | Für Skripte |
--output-format stream-json |
Streaming-JSON | Echtzeitverarbeitung |
Tool-Einschränkungen¶
| Flag | Funktion |
|---|---|
--allowedTools Tool1,Tool2 |
Nur die angegebenen Tools zulassen |
Verfügbare Tool-Namen: Read, Write, Edit, Bash, Glob, Grep, WebFetch, WebSearch, Agent, NotebookEdit
Session-Verwaltung¶
| Flag | Funktion |
|---|---|
--session-id ID |
Session-ID festlegen |
--resume |
Vorherige Session fortsetzen |
Umgebungsvariablen¶
| Variable | Funktion |
|---|---|
ANTHROPIC_BASE_URL |
API-Endpunkt (QCode.cc: https://api.qcode.cc/api) |
ANTHROPIC_AUTH_TOKEN |
API-Key (beginnt mit cr_) |
CLAUDE_CODE_MAX_TURNS |
Standardmäßige maximale Rundenzahl |
CLAUDE_CODE_OUTPUT_FORMAT |
Standardmäßiges Ausgabeformat |
CLAUDE_MODEL |
Standardmäßiges Modell |
3. CI/CD-Rezepte¶
Rezept 1: GitHub Actions — KI-Code-Review¶
name: AI Code Review
on: [pull_request]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # full history, needed for the diff
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Install Claude Code
run: npm install -g @anthropic-ai/claude-code
- name: AI Code Review
env:
ANTHROPIC_BASE_URL: "https://api.qcode.cc/api"
ANTHROPIC_AUTH_TOKEN: ${{ secrets.QCODE_API_KEY }}
run: |
# Collect the files changed in this PR
FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD)
claude -p "Review the code changes in the following files, focusing on:
1. Security vulnerabilities (SQL injection, XSS, leaked secrets)
2. Performance problems (N+1 queries, memory leaks)
3. Logic errors
4. Code style issues
Changed files:
$FILES" \
--output-format json \
--max-turns 3 \
--model claude-sonnet-5 \
--allowedTools Read,Glob,Grep \
> review.json
echo "Review completed"
cat review.json | jq -r '.result' || cat review.json
Rezept 2: Tests automatisch generieren¶
name: Auto Generate Tests
on:
push:
paths: ['src/**/*.ts', '!src/**/*.test.ts']
jobs:
generate-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- name: Install dependencies
run: |
npm ci
npm install -g @anthropic-ai/claude-code
- name: Generate missing tests
env:
ANTHROPIC_BASE_URL: "https://api.qcode.cc/api"
ANTHROPIC_AUTH_TOKEN: ${{ secrets.QCODE_API_KEY }}
run: |
claude -p "Look at the .ts files under src/ and write unit tests for the ones that have none.
Use Vitest + Testing Library.
Name test files xxx.test.ts and put them next to the source file.
Target 80%+ coverage." \
--max-turns 10 \
--allowedTools Read,Write,Glob,Grep,Bash \
--dangerously-skip-permissions
- name: Run tests
run: npx vitest --run
- name: Create PR with tests
if: success()
run: |
git config user.name "claude-bot"
git config user.email "bot@qcode.cc"
git checkout -b auto-tests-$(date +%s)
git add '*.test.ts'
git commit -m "test: auto-generated unit tests" || exit 0
git push origin HEAD
Rezept 3: Code-Qualitätsgate¶
name: Code Quality Gate
on: [pull_request]
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- run: npm install -g @anthropic-ai/claude-code
- name: Quality Analysis
env:
ANTHROPIC_BASE_URL: "https://api.qcode.cc/api"
ANTHROPIC_AUTH_TOKEN: ${{ secrets.QCODE_API_KEY }}
run: |
claude -p "Analyse code quality and output JSON:
{
\"score\": 0-100,
\"issues\": [{\"severity\": \"high|medium|low\", \"file\": \"...\", \"description\": \"...\"}],
\"summary\": \"one-line summary\"
}
Scoring:
- Type safety (20 points)
- Error handling (20 points)
- Test coverage (20 points)
- Readability (20 points)
- Security (20 points)" \
--output-format json \
--max-turns 3 \
--model claude-sonnet-5 \
--allowedTools Read,Glob,Grep \
> quality.json
- name: Check score
run: |
SCORE=$(cat quality.json | jq -r '.result' | jq -r '.score // 0')
echo "Quality score: $SCORE"
if [ "$SCORE" -lt 60 ]; then
echo "Quality gate failed: score $SCORE < 60"
exit 1
fi
Rezept 4: Changelog generieren¶
#!/bin/bash
# generate-changelog.sh — build a changelog from git commits
export ANTHROPIC_BASE_URL="https://api.qcode.cc/api"
export ANTHROPIC_AUTH_TOKEN="cr_your_api_key"
# Commits since the last tag
LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
if [ -z "$LAST_TAG" ]; then
COMMITS=$(git log --oneline -20)
else
COMMITS=$(git log --oneline ${LAST_TAG}..HEAD)
fi
claude -p "Produce a structured changelog from these git commits:
$COMMITS
Format:
## [version] - $(date +%Y-%m-%d)
### Added
### Fixed
### Changed
### Breaking changes (if any)
Write in English, concise and professional." \
--output-format text \
--max-turns 2 \
--model claude-sonnet-5 \
--allowedTools Read,Glob,Grep
Rezept 5: Dokumentation aktuell halten¶
#!/bin/bash
# update-docs.sh — refresh the API docs after code changes
export ANTHROPIC_BASE_URL="https://api.qcode.cc/api"
export ANTHROPIC_AUTH_TOKEN="cr_your_api_key"
claude -p "Look at the route files under src/api/ and compare them with the documentation in docs/api.md.
Find API descriptions that are missing or out of date and update docs/api.md.
Keep the existing document format and style." \
--max-turns 8 \
--allowedTools Read,Write,Edit,Glob,Grep
4. Docker-Isolation¶
Wenn Sie --dangerously-skip-permissions in CI/CD verwenden, empfehlen wir dringend, die Ausführung in einem Docker-Container durchzuführen:
FROM node:22-slim
# Install Claude Code
RUN npm install -g @anthropic-ai/claude-code
# Install project dependencies
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
# QCode.cc environment
ENV ANTHROPIC_BASE_URL=https://api.qcode.cc/api
# ANTHROPIC_AUTH_TOKEN is injected at runtime
# Run as a non-root user
RUN useradd -m claude
USER claude
CMD ["claude", "-p", "Run a code review", "--dangerously-skip-permissions", "--max-turns", "5"]
Ausführung:
docker build -t claude-ci .
docker run --rm -e ANTHROPIC_AUTH_TOKEN=cr_your_key claude-ci
5. Sitzungswiederaufnahme und mehrstufige Pipelines¶
Mehrstufige Aufgaben¶
# Step 1: analyse
claude -p "Analyse the project architecture" \
--session-id "pipeline-42" \
--output-format json \
--max-turns 3 \
--allowedTools Read,Glob,Grep
# Step 2: build a plan from that analysis
claude -p "Based on the previous analysis, draft a refactoring plan" \
--resume --session-id "pipeline-42" \
--max-turns 3
# Step 3: execute the plan
claude -p "Carry out the first step of the refactoring plan" \
--resume --session-id "pipeline-42" \
--max-turns 10 \
--allowedTools Read,Write,Edit,Bash,Glob,Grep
6. Kostenkontrolle¶
Strategie 1: Anzahl der Turns begrenzen¶
# Three turns is enough for a simple task
claude -p "Quick analysis" --max-turns 3
# Ten at most for a complex one
claude -p "Full refactor" --max-turns 10
Strategie 2: das passende Modell wählen¶
| Szenario | Empfehlung | Warum |
|---|---|---|
| Code-Review | Sonnet | Gut genug und günstig |
| Sicherheitsscan | Opus | Erfordert tiefgehende Analyse |
| Massenformatierung | Haiku | Am günstigsten |
| Testgenerierung | Sonnet | Bestes Preis-Leistungs-Verhältnis |
claude -p "Format the code" --model claude-haiku-4-5 --max-turns 3
Strategie 3: Tools einschränken, um Token-Nutzung zu reduzieren¶
# Read-only analysis → no repeated write/test cycles to pay for
claude -p "Analyse the code" --allowedTools Read,Glob,Grep --max-turns 3
7. Vergleich mit Codex Headless¶
| Claude Code -p | Codex headless | |
|---|---|---|
| Flag | -p "prompt" |
codex -q "prompt" |
| Sandbox | Erfordert Docker-Isolation | Integrierte Kernel-Level-Sandbox |
| Ausgabeformate | text/json/stream-json | text/json |
| Sitzungswiederaufnahme | --resume --session-id |
Nicht unterstützt |
| Tool-Einschränkung | --allowedTools |
--approval-mode |
| Parallele Ausführung | Nicht unterstützt | codex cloud exec |
Gemeinsame Nutzung: Claude Code für Analyse und Planung (schreibgeschützt), Codex für die Ausführung (vollautomatisch).
Ein QCode.cc-Tarif teilt sich das Kontingent, sodass ein Wechsel zwischen den beiden Tools in CI keine zusätzlichen Kosten verursacht.
8. Best-Practices-Checkliste¶
- Turns immer begrenzen: Verwenden Sie
--max-turnsin CI, um unkontrollierte Ausführung zu verhindern - Tools einschränken: Stellen Sie über
--allowedToolsnur das bereit, was die Aufgabe benötigt - Mit Docker isolieren:
--dangerously-skip-permissionsmuss in einem Container ausgeführt werden - JSON-Ausgabe: Bevorzugen Sie
--output-format jsonin der Automatisierung, damit Ergebnisse leicht parsebar sind - Kosten kontrollieren: Sonnet für Analyse, Haiku für einfache Aufgaben
- Idempotenz: Stellen Sie sicher, dass wiederholte Ausführung keine Seiteneffekte hat
- Timeouts: Legen Sie im Pipeline-Job ein Timeout fest (z. B. 10 Minuten)
- Secret-Verwaltung: Bewahren Sie den API-Key in CI-Secrets auf, niemals hartcodiert
Nächste Schritte¶
- Hooks-System — Aktionen automatisch auslösen
- CLI-Tipps — weitere Befehlszeilennutzung
- Kosteneffizienz — Techniken zur Kostenkontrolle
- Vollständiges Claude-Code-Tutorial — von null zur Meisterschaft