Skip to content

Claude Code - Primer

Why This Matters

Claude Code is Anthropic's terminal-native AI agent. Unlike browser-based AI or editor plugins, it runs in your shell with direct access to your filesystem, git history, and CLI tools. For DevOps engineers this means you can debug live infrastructure, write and test scripts, explore unfamiliar codebases, and automate repetitive tasks without context-switching. Learning to drive it well makes you significantly faster.

Installation and Setup

Install

# Install via npm (requires Node.js 18+)
npm install -g @anthropic-ai/claude-code

# Or via Homebrew
brew install claude-code

# Verify
claude --version

First Launch

# Start Claude Code in your project directory
cd ~/projects/my-app
claude

# Start with a specific task
claude "explain how the deploy pipeline works"

# Start in non-interactive (headless) mode
claude -p "list all TODO comments in this repo"

On first run, Claude Code authenticates via your Anthropic account or API key.

Fun fact: Claude Code was publicly released by Anthropic in February 2025. Unlike editor plugins that wrap an AI chat panel, it runs as a first-class terminal application with direct filesystem and shell access -- making it uniquely suited for infrastructure work where the terminal is the primary interface.

Core Concepts

CLAUDE.md - Project Context Files

CLAUDE.md is how you give Claude Code persistent project context. It reads these files automatically when it starts.

# CLAUDE.md — My Project

## Stack
- Python 3.11, FastAPI, PostgreSQL
- Docker, Helm 3, deployed to EKS
- Terraform for infrastructure

## Conventions
- Line length: 100 characters
- Linter: ruff
- Test command: pytest --cov=app --cov-fail-under=90

## Do NOT
- Commit .env files
- Modify protected source files (e.g., resume source in sibling repo)
- Hand-edit generated portal files

Hierarchy: Claude Code merges CLAUDE.md files from parent directories down. More specific files override general ones: - ~/CLAUDE.md — global user preferences - ./CLAUDE.md — project root instructions - ./subdir/CLAUDE.md — subsystem overrides

Tips for effective CLAUDE.md files: - Include your validation commands (make test, ruff check .) - List files that should not be modified - Document naming conventions and commit message style - Keep it concise — Claude Code reads the whole thing every session

Permission Model

Claude Code asks permission before taking actions. You control the trust level:

Mode Behavior
Default Asks before file edits, command execution
Auto-accept edits File reads/writes allowed, commands still ask
YOLO mode Everything auto-approved (use with caution)

Configure via /permissions or settings:

# Allow specific tools without prompting
claude config set allowedTools '["Edit", "Write", "Bash(git *)"]'

# Allow bash commands matching a pattern
claude config set allowedTools '["Bash(npm test)", "Bash(make *)"]'

Best practice: Start restrictive, then allow specific patterns you trust. Never YOLO on production infrastructure.

Gotcha: Allowed tools patterns use glob syntax, not regex. Bash(git *) allows all git commands, but Bash(make test) only allows the exact string make test -- not make test-all or make tests. Be precise with your patterns or you'll get permission prompts you didn't expect.

Tools

Claude Code has built-in tools it uses to interact with your system:

Tool Purpose
Read Read files from disk
Edit Make targeted edits to existing files
Write Create new files or full rewrites
Bash Execute shell commands
Glob Find files by name pattern
Grep Search file contents with regex
Agent Spawn sub-agents for parallel work
TodoWrite Track multi-step task progress
WebFetch Fetch content from URLs
WebSearch Search the web
NotebookEdit Edit Jupyter notebooks

Slash Commands

Slash commands are shortcuts you type in the Claude Code prompt. They trigger specific behaviors or workflows.

Built-in Commands

Command What It Does
/help Show available commands and usage
/clear Clear conversation context
/compact Compress conversation to save context window
/model Switch model (sonnet, opus, haiku)
/cost Show token usage and cost for current session
/permissions View and manage tool permissions
/memory Show and manage memory files
/config View or edit Claude Code configuration
/status Show current session status
/review Review recent changes
/vim Toggle vim keybindings
/terminal-setup Configure terminal integration
/fast Toggle fast mode (same model, faster output)

Custom Slash Commands

Create your own slash commands by adding markdown files to .claude/commands/:

mkdir -p .claude/commands

Example: /deploy-check command

<!-- .claude/commands/deploy-check.md -->
Review the current branch for deployment readiness:

1. Run the test suite: `make test`
2. Check for uncommitted changes
3. Verify the Docker build succeeds
4. List any TODO or FIXME comments
5. Summarize findings with a go/no-go recommendation

Example: /review-pr command

<!-- .claude/commands/review-pr.md -->
Review the pull request at $ARGUMENTS:

1. Fetch the PR diff
2. Check for security issues (hardcoded secrets, SQL injection, XSS)
3. Verify error handling and edge cases
4. Check that tests cover the changes
5. Provide a summary with approve/request-changes recommendation

Usage: /review-pr 42 — the $ARGUMENTS placeholder gets replaced with "42".

Example: /incident command for DevOps

<!-- .claude/commands/incident.md -->
Help investigate an incident. The symptom is: $ARGUMENTS

1. Check pod status: kubectl get pods -A | grep -v Running
2. Check recent events: kubectl get events -A --sort-by=.lastTimestamp | tail -20
3. Check node status: kubectl get nodes
4. Review recent deployments: kubectl rollout history deployment -A
5. Summarize findings and suggest next steps

Usage: /incident "503 errors on /api/orders"

Team-Shared Commands

Put commands in .claude/commands/ in your repo (committed to git) for team-wide slash commands. Put personal commands in ~/.claude/commands/ for commands available across all projects.

MCP Servers (Model Context Protocol)

MCP servers extend Claude Code with external integrations — databases, APIs, internal tools.

Configuration

// .claude/settings.json (project-level)
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://localhost:5432/mydb"
      }
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}

Useful MCP Servers for DevOps

Server What It Does
postgres Query databases directly from Claude Code
github Interact with repos, PRs, issues
filesystem Extended file operations
memory Persistent key-value memory
slack Read/send Slack messages
sentry Query error tracking data
datadog Query metrics and monitors
puppeteer Browser automation

Environment Variables in MCP Config

Use ${VAR_NAME} syntax to reference environment variables — never hardcode secrets in config files.

Hooks

Hooks are shell commands that run automatically in response to Claude Code events. Configure them in settings:

// .claude/settings.json
{
  "hooks": {
    "pre-tool-use": [
      {
        "matcher": "Bash",
        "command": "echo 'Running command: $TOOL_INPUT'"
      }
    ],
    "post-tool-use": [
      {
        "matcher": "Write",
        "command": "ruff check $FILE_PATH 2>/dev/null || true"
      }
    ],
    "notification": [
      {
        "command": "notify-send 'Claude Code' '$MESSAGE'"
      }
    ]
  }
}

Hook events: - pre-tool-use — runs before a tool executes (can block it) - post-tool-use — runs after a tool completes - notification — runs when Claude Code wants to notify you - on-session-start — runs when a session begins

DevOps use cases for hooks: - Auto-lint files after edits - Block destructive commands (e.g., reject rm -rf /) - Send Slack notifications when long tasks complete - Log all bash commands for audit

Memory System

Claude Code can persist information across sessions using memory files:

# View current memories
/memory

# Ask Claude Code to remember something
"Remember that our staging cluster is us-east-1 and prod is us-west-2"

Memory files are stored in ~/.claude/projects/<project>/memory/ and loaded automatically in future sessions. Useful for: - Team conventions not in CLAUDE.md - Recurring debugging patterns - Environment-specific details - User preferences and workflow style

CLI Flags and Modes

# Non-interactive (pipe-friendly)
claude -p "what does this script do?" < deploy.sh

# Continue last conversation
claude --continue

# Resume a specific session
claude --resume <session-id>

# Output as JSON (for scripting)
claude -p --output-format json "list all Python files"

# Use a specific model
claude --model sonnet

# Set max tokens for response
claude --max-turns 5

Headless / CI Integration

# Use in CI pipelines
claude -p "review this diff for security issues" < <(git diff HEAD~1)

# Generate a changelog
claude -p "generate a changelog from the last 10 commits" \
  < <(git log --oneline -10)

# Automated code review in GitHub Actions
claude -p "review this PR for issues" < pr_diff.txt

Model Selection

Model Best For
Opus Complex multi-file refactors, architecture decisions, deep debugging
Sonnet Day-to-day coding, quick fixes, file exploration
Haiku Fast lookups, simple questions, bulk operations

Switch with /model sonnet or claude --model opus.

Context Window Management

Claude Code's context window fills up during long sessions. Manage it:

  • /compact — compress the conversation (keeps key context, drops noise)
  • /clear — full reset (start fresh)
  • Keep CLAUDE.md concise — it's loaded every session
  • Use sub-agents (Agent tool) for research that produces large output — results stay in the sub-agent's context, only the summary comes back
  • Break long tasks into multiple sessions rather than one marathon

Remember: Think of /compact as "garbage collection for context." When you notice Claude Code starting to forget earlier context or repeating itself, run /compact. It preserves the important decisions and findings while reclaiming space for new work.

Keyboard Shortcuts

Shortcut Action
Enter Send message (single-line)
Shift+Enter New line in message
Escape Cancel current generation
Ctrl+C Interrupt / exit
Up/Down Navigate message history
Tab Accept suggestion

One-liner: The most productive Claude Code workflow for DevOps: put your validation commands in CLAUDE.md, allow them in permissions (Bash(make *)), and every edit Claude makes gets auto-validated. It catches its own mistakes before you have to.


Wiki Navigation

  • Claude Code Flashcards (CLI) (flashcard_deck, L1) — Claude Code