⚙️Claude CodeLesson 3.5

Claude Code in CI/CD Pipelines

Non-interactive mode, tool restrictions, and pipeline integration.

25 min

Learning Objectives

  • Run Claude Code with --print for CI usage
  • Restrict tools with --allowedTools
  • Integrate with GitHub Actions and GitLab CI

Claude Code in CI/CD Pipelines

One of Claude Code's most powerful features is its ability to run in non-interactive mode, making it suitable for continuous integration and continuous deployment pipelines. Using the--print flag and related options, you can integrate Claude Code into GitHub Actions, GitLab CI, Jenkins, and other CI/CD systems. The CCA-F exam tests your knowledge of how to configure and secure Claude Code for automated environments.

Non-Interactive Mode: --print

The --print (or -p) flag runs Claude Code in a non-interactive, single-shot mode. Instead of starting an interactive session, it processes the prompt and outputs the result to stdout:

# Basic --print usage
claude --print "Explain the architecture of this project"

# Pipe input to Claude Code
cat src/auth.ts | claude --print "Review this code for security issues"

# Use with output redirection
claude --print "Generate a changelog from recent commits" > CHANGELOG.md

In --print mode, Claude Code:

  • Does not start an interactive session
  • Processes the prompt once and outputs the result
  • Exits after completion
  • Returns a non-zero exit code on failure
  • Can still use tools (reads, edits, bash) if permitted

Output Format Options

The --output-format flag controls how Claude Code formats its response:

# Default text output
claude --print "Summarize recent changes"

# JSON output (useful for programmatic processing)
claude --print --output-format json "List all TODO comments in the codebase"

# Stream output as it is generated
claude --print --output-format stream-json "Review the codebase"

Controlling Tool Access: --allowedTools

In CI/CD environments, you must carefully control which tools Claude Code can use. The--allowedTools flag specifies exactly which tools are permitted:

# Allow only read-only tools (safe for review tasks)
claude --print \
  --allowedTools Read,Glob,Grep \
  "Review the code in src/api/ for security issues"

# Allow reads and bash for running tests
claude --print \
  --allowedTools Read,Glob,Grep,Bash \
  "Run the test suite and report any failures"

# Allow editing for automated fixes
claude --print \
  --allowedTools Read,Glob,Grep,Edit,Write,Bash \
  "Fix all linting errors in the project"
Exam Tip: In CI/CD pipelines, --allowedTools is the primary security mechanism. The exam will test whether you understand the principle of least privilege: give Claude only the tools it needs for the specific task. A code review job needs only read tools; a fix-and-commit job needs read and write tools.

Tool Specification with Arguments

You can restrict tools with argument patterns, just like in settings.json:

# Allow specific bash commands only
claude --print \
  --allowedTools "Read,Glob,Grep,Bash(npm test),Bash(npm run lint)" \
  "Run tests and lint checks, report any issues"

GitHub Actions Integration

The most common CI/CD integration for Claude Code is GitHub Actions. Here are complete, production-ready workflow examples:

Automated Code Review on Pull Requests

# .github/workflows/claude-review.yml
name: Claude Code Review

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    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 Claude Code Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude --print \
            --allowedTools Read,Glob,Grep \
            --output-format text \
            "Review the changes in this pull request. Focus on:
             1. Potential bugs and logic errors
             2. Security vulnerabilities
             3. Performance issues
             4. Code style and best practices
             Provide specific, actionable feedback with file and line references.
             The diff is available via git diff origin/main...HEAD" \
            > review.txt

      - name: Post review comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require("fs");
            const review = fs.readFileSync("review.txt", "utf8");
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: review
            });

Automated Bug Fixes

# .github/workflows/claude-fix.yml
name: Claude Auto-Fix

on:
  issues:
    types: [labeled]

jobs:
  auto-fix:
    if: github.event.label.name == "claude-fix"
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    steps:
      - name: Checkout code
        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-ai/claude-code

      - name: Fix issue with Claude
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude --print \
            --allowedTools Read,Glob,Grep,Edit,Write,Bash \
            "Fix the issue described below. After making changes,
             run the test suite with npm test to verify the fix.
             Issue: ${{ github.event.issue.title }}
             Description: ${{ github.event.issue.body }}"

      - name: Create pull request
        uses: peter-evans/create-pull-request@v6
        with:
          title: "fix: ${{ github.event.issue.title }}"
          body: "Automated fix for #${{ github.event.issue.number }}"
          branch: "claude-fix/${{ github.event.issue.number }}"

GitLab CI Integration

# .gitlab-ci.yml
stages:
  - review
  - fix

claude-review:
  stage: review
  image: node:20
  only:
    - merge_requests
  script:
    - npm install -g @anthropic-ai/claude-code
    - |
      claude --print \
        --allowedTools Read,Glob,Grep \
        "Review the changes in this merge request for bugs,
         security issues, and style violations. Output as markdown." \
        > review.md
  artifacts:
    paths:
      - review.md
  variables:
    ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY

claude-lint-fix:
  stage: fix
  image: node:20
  only:
    - merge_requests
  when: manual
  script:
    - npm install -g @anthropic-ai/claude-code
    - npm ci
    - |
      claude --print \
        --allowedTools Read,Glob,Grep,Edit,Bash \
        "Fix all linting errors. Run npm run lint to check.
         Only fix lint issues, do not change functionality."
    - git add -A
    - git commit -m "fix: auto-fix lint errors via Claude Code"
    - git push
  variables:
    ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY

Security Considerations for CI/CD

Running Claude Code in automated environments requires careful security planning:

API Key Management

  • Never hardcode API keys. Always use CI/CD secret management (GitHub Secrets, GitLab CI Variables, etc.).
  • Use least-privilege API keys. Create dedicated API keys for CI/CD with appropriate rate limits and spending caps.
  • Rotate keys regularly. Treat CI/CD API keys like any other credential.

Tool Access Control

  • Always specify --allowedTools. Never run Claude Code in CI/CD without restricting tool access.
  • Read-only for review jobs. Code review pipelines should only allow Read, Glob, and Grep.
  • Restrict Bash commands. When Bash is needed, restrict it to specific commands: "Bash(npm test)" rather than "Bash".

Output Handling

  • Sanitize outputs. Claude Code's output may contain file contents or code snippets. Be careful about posting raw output in public PR comments.
  • Check exit codes. Use Claude Code's exit code to determine success or failure in your pipeline logic.
Exam Tip: The exam frequently tests CI/CD security practices. Key points: (1) always use --allowedTools, (2) use secret management for API keys, (3) apply least-privilege tool access, (4) read-only tools for review jobs. A common wrong answer on the exam is a CI/CD configuration that gives Claude Code full tool access without restrictions.

The --model Flag

In CI/CD, you may want to specify which model to use for cost or performance reasons:

# Use a specific model
claude --print --model claude-sonnet-4-20250514 \
  "Review this code for issues"

# Use the most capable model for complex tasks
claude --print --model claude-opus-4-20250514 \
  "Perform a thorough security audit of the authentication module"

Combining --print with Piping

Claude Code in --print mode integrates naturally with Unix pipelines:

# Pass file contents as context
cat error.log | claude --print "Analyze this error log and suggest fixes"

# Chain with other tools
git diff main | claude --print "Summarize these changes for a changelog"

# Process multiple files
find src -name "*.test.ts" -exec cat {} + | \
  claude --print "Are there any test files missing error case coverage?"
Key Takeaway: Claude Code runs in CI/CD via the --print flag for non-interactive, single-shot execution. The --allowedTools flag is the primary security mechanism, enforcing least-privilege tool access. API keys must be managed through CI/CD secret systems, never hardcoded. For GitHub Actions, use${{ secrets.ANTHROPIC_API_KEY }}; for GitLab CI, use CI/CD variables. Always match tool access to the task: read-only for reviews, write access for fixes.

Exam-Relevant Concepts Summary

  • --print (or -p) enables non-interactive, single-shot mode.
  • --allowedTools restricts which tools Claude can use (critical for CI/CD security).
  • --output-format supports text, json, and stream-json output.
  • API keys: use CI/CD secrets, never hardcode, rotate regularly.
  • Least privilege: read-only tools for reviews, scoped Bash for specific commands.
  • Exit codes indicate success/failure for pipeline logic.
  • --model selects the Claude model for cost/capability tradeoffs.