DevOps Ready Reckoner: Essential Cheat Sheets

📅 August 4, 2026
⏱️ 18 min read

A single reference page for the tools DevOps engineers reach for daily: Terraform, Kubernetes, kubectl, K3s, Docker, Docker Compose, Helm, Ansible, Git, and CI/CD. Bookmark it, search it, and use it when you need the command or YAML skeleton fast.

Terraform Cheat Sheet

Terraform manages infrastructure through declarative HCL files and a state file that tracks what exists in the real world.

CLI essentials

CommandPurpose
terraform initDownload providers, set up backend
terraform fmtFormat HCL files
terraform validateCheck syntax and internal consistency
terraform planPreview changes before apply
terraform applyCreate or update resources
terraform apply -auto-approveApply without interactive prompt
terraform destroyRemove all managed resources
terraform outputPrint output values
terraform state listList resources in state
terraform state show <addr>Inspect one resource in state
terraform import <addr> <id>Import existing resource into state
terraform workspace listList workspaces (dev/stage/prod)
terraform workspace select <name>Switch workspace

Project structure

project/
├── main.tf           # Primary resources
├── variables.tf      # Input variables
├── outputs.tf        # Exported values
├── providers.tf      # Provider configuration
├── versions.tf       # Terraform & provider version pins
├── terraform.tfvars  # Variable values (do not commit secrets)
└── modules/
    └── vpc/
        ├── main.tf
        ├── variables.tf
        └── outputs.tf

HCL skeleton

terraform {
  required_version = ">= 1.6.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
  backend "s3" {
    bucket = "my-tf-state"
    key    = "prod/terraform.tfstate"
    region = "ap-south-1"
  }
}

provider "aws" {
  region = var.region
}

variable "region" {
  type    = string
  default = "ap-south-1"
}

locals {
  common_tags = {
    Environment = var.environment
    ManagedBy   = "terraform"
  }
}

resource "aws_s3_bucket" "logs" {
  bucket = "${var.project}-logs"
  tags   = local.common_tags
}

output "bucket_name" {
  value = aws_s3_bucket.logs.id
}

Common patterns

PatternExample
Conditional resourcecount = var.enabled ? 1 : 0
For-each mapfor_each = var.subnets
Data sourcedata "aws_ami" "latest" { ... }
Module callmodule "vpc" { source = "./modules/vpc" }
Depends ondepends_on = [aws_iam_role_policy.attach]
Lifecyclelifecycle { prevent_destroy = true }
Production tip: Always run terraform plan in CI before merge. Store state remotely (S3 + DynamoDB lock, Terraform Cloud, or equivalent). Never commit .tfstate or secrets in .tfvars.

kubectl Cheat Sheet

kubectl is the CLI for Kubernetes. Install it separately or use it through K3s (k3s kubectl).

Context and configuration

CommandPurpose
kubectl config get-contextsList available clusters
kubectl config use-context <ctx>Switch cluster
kubectl cluster-infoAPI server and CoreDNS endpoints
kubectl api-resourcesList all resource types
kubectl explain pod.specField documentation

Pods and workloads

CommandPurpose
kubectl get pods -AAll pods in all namespaces
kubectl get pods -o widePods with node and IP
kubectl describe pod <name>Events, conditions, container state
kubectl logs <pod> -fStream container logs
kubectl logs <pod> -c <container>Logs from one container
kubectl logs <pod> --previousLogs from crashed container
kubectl exec -it <pod> -- /bin/shShell into running pod
kubectl port-forward pod/<pod> 8080:80Local access to pod port
kubectl run tmp --image=nginx --rm -it -- /bin/shEphemeral debug pod
kubectl delete pod <name> --grace-period=0 --forceForce delete stuck pod

Deployments, Services, Ingress

CommandPurpose
kubectl get deploy,svc,ingList common workload objects
kubectl rollout status deploy/<name>Watch rollout progress
kubectl rollout history deploy/<name>Revision history
kubectl rollout undo deploy/<name>Rollback to previous revision
kubectl scale deploy/<name> --replicas=5Scale replicas
kubectl set image deploy/<name> app=img:v2Trigger rolling update
kubectl expose deploy <name> --port=80Create ClusterIP Service

Debugging and troubleshooting

CommandPurpose
kubectl get events --sort-by='.lastTimestamp'Recent cluster events
kubectl top nodesNode CPU/memory (needs metrics-server)
kubectl top podsPod resource usage
kubectl auth can-i create podsCheck RBAC permission
kubectl get pod <name> -o yamlFull manifest
kubectl get pods -l app=myappFilter by label
kubectl cordon <node>Mark node unschedulable
kubectl drain <node> --ignore-daemonsetsEvict pods before maintenance

Useful output formats

kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get nodes -o custom-columns=NAME:.metadata.name,STATUS:.status.conditions[-1].type
kubectl get deploy myapp -o jsonpath='{.spec.replicas}'

Kubernetes YAML Quick Reference

Core API objects every DevOps engineer should recognize.

Deployment + Service + Ingress

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
  namespace: production
  labels:
    app: api
spec:
  replicas: 3
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      containers:
        - name: api
          image: myregistry/api:1.2.0
          ports:
            - containerPort: 8080
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 512Mi
          livenessProbe:
            httpGet:
              path: /healthz
              port: 8080
            initialDelaySeconds: 15
          readinessProbe:
            httpGet:
              path: /ready
              port: 8080
          envFrom:
            - configMapRef:
                name: api-config
            - secretRef:
                name: api-secrets
---
apiVersion: v1
kind: Service
metadata:
  name: api
  namespace: production
spec:
  selector:
    app: api
  ports:
    - port: 80
      targetPort: 8080
  type: ClusterIP
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: api
  namespace: production
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  ingressClassName: nginx
  tls:
    - hosts: [api.example.com]
      secretName: api-tls
  rules:
    - host: api.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: api
                port:
                  number: 80

ConfigMap, Secret, HPA, PVC

apiVersion: v1
kind: ConfigMap
metadata:
  name: api-config
data:
  LOG_LEVEL: info
  FEATURE_FLAG_X: "true"
---
apiVersion: v1
kind: Secret
metadata:
  name: api-secrets
type: Opaque
stringData:
  DATABASE_URL: postgres://user:pass@db:5432/app
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: api
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api
  minReplicas: 2
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: data
spec:
  accessModes: [ReadWriteOnce]
  storageClassName: gp3
  resources:
    requests:
      storage: 20Gi

Service types

TypeUse case
ClusterIPInternal only (default)
NodePortExpose on each node IP at a static port
LoadBalancerCloud LB in front of pods
ExternalNameCNAME to external DNS name

K3s Cheat Sheet

K3s is a lightweight, CNCF-certified Kubernetes distribution from Rancher. Ideal for edge, IoT, CI runners, and homelab clusters. It bundles containerd, CoreDNS, Traefik ingress, local-path storage, and a single binary.

Install

# Server (control plane + worker)
curl -sfL https://get.k3s.io | sh -

# Agent (join worker node)
curl -sfL https://get.k3s.io | K3S_URL=https://<server-ip>:6443 \
  K3S_TOKEN=<node-token> sh -

# Node token (on server)
sudo cat /var/lib/rancher/k3s/server/node-token

Service management

CommandPurpose
sudo systemctl status k3sServer status
sudo systemctl restart k3sRestart server
sudo k3s kubectl get nodesRun kubectl without separate install
sudo cat /etc/rancher/k3s/k3s.yamlKubeconfig for remote access
sudo k3s crictl psList containers via CRI
sudo k3s ctr images lsList images in containerd

K3s vs full Kubernetes

TopicK3s defaultNotes
RuntimecontainerdNo Docker daemon required
IngressTraefikDisable with --disable traefik
Storagelocal-path-provisionerHostPath-based dynamic PVs
LoadBalancerServiceLB (Klipper)Binds ports on nodes
DatastoreSQLite (single server)Use etcd or external DB for HA

Common install flags

# /etc/rancher/k3s/config.yaml
write-kubeconfig-mode: "0644"
tls-san:
  - "k3s.example.com"
disable:
  - traefik
cluster-cidr: "10.42.0.0/16"
service-cidr: "10.43.0.0/16"
Tip: Export kubeconfig once: export KUBECONFIG=/etc/rancher/k3s/k3s.yaml then use plain kubectl for all commands below.

Dockerfile Structure

A Dockerfile is a ordered list of instructions that build an OCI image layer by layer.

Instruction reference

InstructionPurpose
FROMBase image (required, first instruction after optional syntax)
WORKDIRSet working directory for subsequent commands
COPYCopy files from build context
ADDLike COPY + auto-extract tar and remote URLs
RUNExecute command during build (creates layer)
ENVSet environment variable
ARGBuild-time variable (not in final image unless referenced)
EXPOSEDocument port (does not publish)
USERRun as non-root user
CMDDefault command at container start (one per Dockerfile)
ENTRYPOINTMain executable; CMD args append to it
HEALTHCHECKContainer health probe

Multi-stage production template

# syntax=docker/dockerfile:1

# --- Build stage ---
FROM golang:1.22-alpine AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o /app .

# --- Runtime stage ---
FROM gcr.io/distroless/static-debian12:nonroot
WORKDIR /
COPY --from=builder /app /app
USER nonroot:nonroot
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s CMD ["/app", "healthcheck"]
ENTRYPOINT ["/app"]

Node.js example

FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev

FROM node:20-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]

.dockerignore essentials

.git
node_modules
dist
*.log
.env
Dockerfile*
docker-compose*
README.md
.terraform

Build and run

docker build -t myapp:1.0.0 .
docker build --target builder -t myapp:build .
docker run -d -p 8080:8080 --name myapp myapp:1.0.0
docker exec -it myapp sh
docker logs -f myapp

Docker Compose YAML Structure

Compose defines multi-container applications in a single YAML file. Compose Specification v2 is the current standard (use docker compose, not legacy docker-compose).

Top-level keys

KeyPurpose
servicesContainer definitions (required)
networksCustom networks
volumesNamed or external volumes
configsSwarm-style configs (Compose supports)
secretsSecret files mounted into services

Full stack template

name: mystack

services:
  api:
    build:
      context: ./api
      dockerfile: Dockerfile
      target: production
    image: myregistry/api:${TAG:-latest}
    restart: unless-stopped
    ports:
      - "8080:8080"
    environment:
      DATABASE_URL: postgres://app:secret@db:5432/app
      REDIS_URL: redis://cache:6379/0
    env_file:
      - .env
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started
    networks:
      - backend
    volumes:
      - api-data:/data
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/healthz"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 20s
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 512M

  db:
    image: postgres:16-alpine
    restart: unless-stopped
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: app
    volumes:
      - pg-data:/var/lib/postgresql/data
    networks:
      - backend
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d app"]
      interval: 10s
      timeout: 5s
      retries: 5

  cache:
    image: redis:7-alpine
    networks:
      - backend

  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - api
    networks:
      - backend
      - frontend
    profiles:
      - proxy

networks:
  backend:
    driver: bridge
  frontend:
    driver: bridge

volumes:
  pg-data:
  api-data:

Compose CLI

CommandPurpose
docker compose up -dStart all services detached
docker compose down -vStop and remove volumes
docker compose psList running services
docker compose logs -f apiFollow service logs
docker compose exec api shShell into service
docker compose configValidate and render merged YAML
docker compose --profile proxy upStart with profile enabled

Helm Cheat Sheet

Helm is the package manager for Kubernetes. Charts are templated YAML bundles versioned and released as units.

CLI

CommandPurpose
helm repo add bitnami https://charts.bitnami.com/bitnamiAdd chart repository
helm search repo nginxSearch charts
helm install myrelease bitnami/nginxInstall chart
helm upgrade myrelease ./chart -f values.yamlUpgrade release
helm rollback myrelease 2Rollback to revision 2
helm list -AAll releases
helm uninstall myreleaseRemove release
helm template myrelease ./chartRender locally without install
helm get values myreleaseShow deployed values

Chart structure

mychart/
├── Chart.yaml
├── values.yaml
├── templates/
│   ├── deployment.yaml
│   ├── service.yaml
│   ├── ingress.yaml
│   └── _helpers.tpl
└── charts/          # Subchart dependencies

values.yaml snippet

replicaCount: 3
image:
  repository: myregistry/api
  tag: "1.2.0"
  pullPolicy: IfNotPresent
service:
  type: ClusterIP
  port: 80
ingress:
  enabled: true
  host: api.example.com
resources:
  limits:
    cpu: 500m
    memory: 512Mi

Ansible Quick Reference

Ansible automates configuration management and ad-hoc tasks over SSH (or WinRM) with YAML playbooks.

CLI

CommandPurpose
ansible all -m pingTest connectivity
ansible web -a "uptime"Ad-hoc command on group
ansible-playbook site.ymlRun playbook
ansible-playbook site.yml --checkDry run
ansible-playbook site.yml -l webserversLimit to host pattern
ansible-vault encrypt secrets.ymlEncrypt sensitive vars

Inventory (INI)

[webservers]
web1 ansible_host=10.0.1.10
web2 ansible_host=10.0.1.11

[webservers:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=~/.ssh/id_ed25519

Playbook skeleton

---
- name: Configure web servers
  hosts: webservers
  become: true
  vars:
    app_port: 8080
  tasks:
    - name: Install nginx
      ansible.builtin.package:
        name: nginx
        state: present

    - name: Deploy config
      ansible.builtin.template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Reload nginx

  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded

Common modules

ModulePurpose
ansible.builtin.copyCopy file to host
ansible.builtin.templateJinja2 template to file
ansible.builtin.serviceManage systemd service
ansible.builtin.userManage users
community.docker.docker_containerManage containers
amazon.aws.ec2_instanceManage EC2 instances

Git & CI/CD Quick Reference

Git essentials

CommandPurpose
git statusWorking tree state
git log --oneline -10Recent commits
git diffUnstaged changes
git stash push -m "wip"Stash changes
git cherry-pick <sha>Apply one commit
git rebase origin/mainRebase on latest main
git revert <sha>Safe undo via new commit

GitHub Actions workflow skeleton

name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: "20"
          cache: npm

      - run: npm ci
      - run: npm test
      - run: npm run build

  terraform:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - run: terraform fmt -check
        working-directory: infra
      - run: terraform init -backend=false
        working-directory: infra
      - run: terraform validate
        working-directory: infra

Pipeline stages (mental model)

StageTypical checks
Lintfmt, eslint, tflint, yamllint
Testunit tests, terraform validate
Builddocker build, compile artifacts
Scantrivy, snyk, checkov, tfsec
Deployhelm upgrade, terraform apply (with approval)

Linux & Shell One-Liners

For deeper Linux coverage, see Linux Fundamentals. These one-liners cover daily DevOps tasks.

TaskCommand
Disk usagedf -h && du -sh /* 2>/dev/null | sort -h
Find large filesfind / -xdev -type f -size +100M 2>/dev/null
Process on portss -tlnp | grep :8080
Follow syslogjournalctl -u nginx -f
HTTP checkcurl -sI https://example.com | head -1
DNS lookupdig +short api.example.com
JSON pretty-printcurl -s url | jq .
Parallel SSHparallel-ssh -i -H hosts.txt "uptime"

Observability Quick Reference

SignalToolsDevOps use
MetricsPrometheus, Grafana, CloudWatchSLOs, alerting, capacity
LogsLoki, ELK, Fluent BitIncident triage, audit
TracesJaeger, Tempo, OpenTelemetryLatency debugging

Prometheus PromQL starters

rate(http_requests_total[5m])
histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))
up{job="kubernetes-pods"} == 0

Incident checklist

  • What changed? (deploy, config, traffic, dependency)
  • Is it global or isolated? (one pod, one AZ, all users)
  • Check: kubectl get pods, events, recent deploys, dashboards, error rate
  • Mitigate first (rollback, scale, feature flag), root-cause second
  • Document timeline and write a blameless postmortem
Keep this page useful: Pin it in your browser, print the sections you use most, and pair it with official docs when you need version-specific behavior. DevOps is a practice of repeatable, observable, automatable systems. These cheat sheets are the shortcuts; understanding the why behind each command is what makes you effective under pressure.
Topics & Tags
DevOps Terraform Kubernetes kubectl K3s Docker Docker Compose Helm Ansible CI/CD Cheat Sheet