Yash Verma / Cloud runbook

Cloud runbook

Commands I reach for across Kubernetes, AWS, GCP, Terraform, Linux and the tools around them, plus short playbooks for common incidents. Fill in a placeholder once and every command uses it.

Kubernetes29

Get all pods across namespaces

Lists all pods across all namespaces in the cluster.

kubectl get pods --all-namespaces

pods, overview

Sort events by timestamp

Get recent events in a namespace sorted by their creation time.

kubectl get events --sort-by='.metadata.creationTimestamp'

events, debugging, cluster

Check node resource usage

Displays CPU and Memory usage for all nodes.

kubectl top nodes

metrics, nodes, performance

Force delete a stuck pod

Bypasses graceful termination to kill a pod.

Caution. Removes the pod from the API without waiting for the kubelet to confirm it stopped. A StatefulSet pod can end up running twice against the same volume. Try a normal delete first.

kubectl delete pod <pod-name> --grace-period=0 --force

pods, stuck, delete

Port forward to a service

Forwards local port to a service port.

kubectl port-forward svc/<service-name> 8080:80

network, debug

Decode a base64 secret

Fetches and decodes a base64 Kubernetes secret.

kubectl get secret <secret-name> -o jsonpath='{.data.<key>}' | base64 --decode

Prints the secret in plain text to your terminal and its scrollback.

security, secrets, base64

Get logs from previously crashed pod

Useful for checking why a pod crashed before it restarted.

kubectl logs <pod-name> --previous

logs, crash, debug

Check RBAC permissions

Check if your current user has permission to perform an action.

kubectl auth can-i create deployments --namespace dev

rbac, auth, permissions

Generate YAML manifest (dry run)

Generates the YAML for a resource without actually creating it.

kubectl create deployment nginx --image=nginx --dry-run=client -o yaml > nginx.yaml

yaml, manifest, generate

Safely drain a node

Cordons the node and evicts its pods before maintenance, respecting PodDisruptionBudgets.

Caution. --delete-emptydir-data deletes the data in emptyDir volumes on that node.

kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data

node, maintenance, drain

Interactive shell in pod

Opens an interactive shell session inside a running pod.

kubectl exec -it <pod-name> -- /bin/sh

exec, shell, interactive

Restart a deployment

Triggers a rolling restart of all pods in a deployment.

kubectl rollout restart deployment/<deployment-name>

rollout, restart, deployment

Scale deployment

Sets the replica count of a deployment.

kubectl scale deployment/<deployment-name> --replicas=5

If a HorizontalPodAutoscaler manages the deployment, it will change the count back.

scale, replicas, capacity

Update image in deployment

Updates the container image of a deployment without editing YAML.

kubectl set image deployment/<deployment-name> <container-name>=<image-name>:<tag>

image, update, deploy

Explain a Kubernetes resource's fields

Shows the documentation and fields for a specific Kubernetes resource.

kubectl explain pod.spec.containers

explain, docs, api

View rollout history

Checks the revision history of a deployment.

kubectl rollout history deployment/<deployment-name>

rollout, history

Get running pod YAML

Exports the live YAML configuration of a running pod.

kubectl get pod <pod-name> -o yaml

yaml, export

Patch resource inline

Updates a field on a resource without an editor.

kubectl patch deployment <deployment-name> -p '{"spec": {"replicas": 3}}'

patch, update

Label a node

Adds or updates a label on a Kubernetes node for scheduling.

kubectl label node <node-name> env=production

label, node, scheduling

Taint a node

Adds a taint to a node to repel pods that don't tolerate it.

kubectl taint nodes <node-name> key=value:NoSchedule

taint, scheduling

Create ConfigMap from file

Creates a ConfigMap from a local file.

kubectl create configmap my-config --from-file=config.properties

configmap, config

Rollback a deployment

Rolls back a deployment to the previous revision.

kubectl rollout undo deployment/<deployment-name>

rollback, undo, deployment

List all kube contexts

Shows all available contexts in your kubeconfig.

kubectl config get-contexts

context, config, cluster

Switch kube context

Changes the active Kubernetes context.

kubectl config use-context <context-name>

context, switch

Top pods by CPU

Shows CPU and memory usage of pods sorted by CPU.

kubectl top pods --sort-by=cpu --all-namespaces

metrics, cpu, pods

Find pods whose last restart was an OOM kill

Lists pods where a container last terminated with OOMKilled.

kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"/"}{.metadata.name}{" "}{.status.containerStatuses[*].lastState.terminated.reason}{"\n"}{end}' | grep OOMKilled

oom, memory, restarts

Describe a pod

Shows a pod's status, container states, restart reasons and recent events.

kubectl describe pod <pod-name> -n <namespace>

pods, events, debugging

Watch a rollout until it finishes

Waits for a deployment rollout and exits non-zero if it fails.

kubectl rollout status deployment/<deployment-name> -n <namespace>

rollout, deploy

Cordon a node

Marks a node unschedulable; running pods stay where they are.

kubectl cordon <node-name>

nodes, maintenance

Helm14

List all releases across namespaces

Lists all Helm deployments in the cluster.

helm ls --all-namespaces

helm, deployments

Rollback a release

Rolls back a Helm deployment to a specific prior revision.

helm rollback <release-name> <revision-number>

helm, rollback, revert

Get deployed values

Fetches the values.yaml that was actually applied to a deployed release.

helm get values <release-name>

helm, config, values

Upgrade or install release

Installs a helm chart, or upgrades it if it already exists.

helm upgrade --install <release-name> <chart-path>

helm, deploy, upgrade

Render Helm templates locally

Renders the chart templates locally without applying them to the cluster.

helm template <release-name> <chart-path>

helm, template, dry-run

Add a Helm chart repository

Adds a chart repository to Helm's local repo list.

helm repo add prometheus-community https://prometheus-community.github.io/helm-charts && helm repo update

helm, repo, add

Show chart default values

Prints the default values.yaml of a chart before installing.

helm show values <chart-name>

helm, values, chart

View release history

Shows the revision history and status of a Helm release.

helm history <release-name>

helm, history, revisions

Uninstall a release

Removes all resources associated with a Helm release.

Caution. Deletes every resource in the release. Add --keep-history to keep the release record for a later rollback.

helm uninstall <release-name> --namespace <namespace>

helm, delete, cleanup

Lint a Helm chart

Validates a chart for possible issues before deploying.

helm lint ./my-chart

helm, lint, validate

Show the manifests of an installed release

Prints the rendered Kubernetes manifests Helm applied for a release.

helm get manifest <release-name> -n <namespace>

manifest, debug

Upgrade and roll back on failure

Upgrades a release, waits for it to become ready and rolls back automatically if it doesn't.

helm upgrade --install <release-name> <chart-path> -n <namespace> --atomic --wait --timeout 5m

Helm 4 renamed --atomic to --rollback-on-failure.

upgrade, rollback, safe

Download a chart to read it

Pulls a chart version and unpacks it locally so you can read its templates and values.

helm pull <helm-repo>/<chart> --version <version> --untar

pull, chart

Preview an upgrade as a diff

Shows what an upgrade would change in the cluster before you run it.

helm diff upgrade <release-name> <chart-path> -n <namespace>

Needs the helm-diff plugin: helm plugin install https://github.com/databus23/helm-diff

diff, upgrade, plugin

Karpenter11

View controller logs

Tails the logs of the Karpenter controller pod.

kubectl logs -f -n kube-system -l app.kubernetes.io/name=karpenter

Current install guides use kube-system; older installs used a karpenter namespace.

logs, debugging

List NodeClaims

Shows all NodeClaims provisioned by Karpenter.

kubectl get nodeclaims

nodes, claims

View disruption logs

Filters Karpenter logs specifically for scale-down and disruption events.

kubectl logs -n kube-system -l app.kubernetes.io/name=karpenter | grep -i disrupt

scaling, disruption, logs

List NodePools

Shows all Karpenter NodePool configurations.

kubectl get nodepools

nodepool, config

Describe a NodeClaim

Shows detailed info about a specific NodeClaim including instance type.

kubectl describe nodeclaim <nodeclaim-name>

describe, instance

List EC2NodeClasses

Shows all EC2NodeClass resources used by Karpenter for AWS configuration.

kubectl get ec2nodeclasses

aws, nodeclass, config

NodePool CPU limits and usage

Shows each NodePool's CPU limit next to the CPU it has provisioned.

kubectl get nodepools -o custom-columns=NAME:.metadata.name,CPU_LIMIT:.spec.limits.cpu,CPU_USED:.status.resources.cpu

nodepools, limits, capacity

Watch nodes being created and removed

Streams NodeClaim changes as Karpenter provisions and consolidates nodes.

kubectl get nodeclaims -w

nodeclaims, watch, consolidation

Why a pending pod got no node

Shows a pod's scheduling events, where Karpenter reports why no NodePool fits it.

kubectl get events -n <namespace> --field-selector involvedObject.name=<pod-name> --sort-by=.lastTimestamp

pending, scheduling, events

Protect a pod from voluntary disruption

Stops Karpenter from consolidating, expiring or replacing the node this pod runs on.

kubectl annotate pod <pod-name> -n <namespace> karpenter.sh/do-not-disrupt=true

Remove it with the same command and a trailing minus: karpenter.sh/do-not-disrupt-

disruption, annotation

Show a NodePool's disruption settings

Prints the consolidation policy and disruption budgets of a NodePool.

kubectl get nodepool <nodepool-name> -o jsonpath='{.spec.disruption}'

disruption, budgets, nodepools

AWS25

Sync local folder to S3

Uploads a local directory to an S3 bucket.

aws s3 sync ./my-folder s3://<bucket>

Add --delete to also remove objects that no longer exist locally. Try --dryrun first.

s3, sync, upload

Delete every object in an S3 bucket

Recursively deletes all objects in an S3 bucket.

Caution. Permanently deletes every object. Run it with --dryrun first. On a versioned bucket it only adds delete markers; the old versions stay and still cost money.

aws s3 rm s3://<bucket> --recursive

s3, delete

List running EC2 instances

Returns the ID, Type, and State of running EC2s.

aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" --query "Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name]" --output table

ec2, inventory

Check current AWS identity

Verifies which AWS IAM user/role you are currently authenticated as.

aws sts get-caller-identity

iam, auth, sts

Update EKS kubeconfig

Generates or updates kubeconfig for EKS.

aws eks update-kubeconfig --region <region> --name <cluster-name>

eks, kubernetes, auth

Log in with AWS SSO

Authenticates via AWS IAM Identity Center (SSO).

aws sso login --profile <profile-name>

sso, auth, login

Docker login to ECR

Gets a token and pipes it to docker login for AWS ECR.

aws ecr get-login-password --region <region> | docker login --username AWS --password-stdin <account_id>.dkr.ecr.<region>.amazonaws.com

ecr, docker, auth

Detect CloudFormation drift

Checks if actual resources have deviated from the CFN template.

aws cloudformation detect-stack-drift --stack-name <stack-name>

Returns a detection ID. Check the result with aws cloudformation describe-stack-drift-detection-status --stack-drift-detection-id <id>.

cloudformation, drift, iac

Generate S3 presigned URL

Creates a temporary URL (valid for 1 hour) to securely share an S3 object.

aws s3 presign s3://<bucket>/<key> --expires-in 3600

Anyone with the URL can download the object until it expires.

s3, presigned, share

Tail CloudWatch logs

Streams real-time logs from an AWS CloudWatch Log Group.

aws logs tail /aws/lambda/<function-name> --follow

cloudwatch, logs, lambda

Get a Secrets Manager value

Fetches the plain text value of a secret from AWS Secrets Manager.

aws secretsmanager get-secret-value --secret-id <secret-name> --query SecretString --output text

Prints the secret in plain text to your terminal.

secretsmanager, security, secrets

List stale IAM access keys

Lists all access keys for a user to identify old keys needing rotation.

aws iam list-access-keys --user-name <username>

iam, keys, security

Copy file to S3

Copies a single local file to an S3 bucket.

aws s3 cp local-file.txt s3://<bucket>/

s3, copy

Invoke Lambda function

Synchronously invokes a Lambda function from the CLI.

aws lambda invoke --function-name <function-name> --cli-binary-format raw-in-base64-out --payload '{}' response.json

AWS CLI v2 expects base64 payloads unless you pass --cli-binary-format raw-in-base64-out.

lambda, invoke

List RDS instances

Gets a list of all RDS database instances.

aws rds describe-db-instances --query 'DBInstances[*].[DBInstanceIdentifier,DBInstanceStatus]' --output table

rds, database

Stop EC2 instance

Stops a running EC2 instance by instance ID.

aws ec2 stop-instances --instance-ids <instance-id>

Data on instance store volumes is lost when the instance stops.

ec2, stop

Start EC2 instance

Starts a stopped EC2 instance.

aws ec2 start-instances --instance-ids <instance-id>

ec2, start

List Route53 hosted zones

Lists all DNS hosted zones in Route53.

aws route53 list-hosted-zones --output table

route53, dns

List load balancers

Lists all Application and Network Load Balancers.

aws elbv2 describe-load-balancers --query 'LoadBalancers[*].[LoadBalancerName,State.Code,DNSName]' --output table

elb, alb, nlb

Start SSM session

Opens a shell session to an EC2 instance via Systems Manager (no SSH key needed).

aws ssm start-session --target <instance-id>

Needs the Session Manager plugin for the AWS CLI and the SSM agent on the instance.

ssm, session, shell

Get monthly cost breakdown

Fetches cost and usage data grouped by service for the current month.

aws ce get-cost-and-usage --time-period Start=$(date +%Y-%m-01),End=$(date -d tomorrow +%Y-%m-%d) --granularity MONTHLY --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE

Each Cost Explorer API request costs $0.01. Uses GNU date; on macOS use gdate.

cost, billing, finops

List ECR images

Lists all images in an ECR repository sorted by push date.

aws ecr describe-images --repository-name <repo-name> --query 'sort_by(imageDetails,& imagePushedAt)[*].[imageTags[0],imagePushedAt]' --output table

ecr, images, docker

Send SQS message

Sends a test message to an SQS queue.

aws sqs send-message --queue-url <queue-url> --message-body '{"test": "hello"}'

sqs, queue, messaging

Scan DynamoDB table

Reads the first 10 items of a DynamoDB table.

aws dynamodb scan --table-name <table-name> --max-items 10

A scan reads the table page by page and consumes read capacity; avoid full scans on large tables.

dynamodb, nosql, scan

List CloudWatch alarms

Shows every CloudWatch alarm currently in the ALARM state.

aws cloudwatch describe-alarms --state-value ALARM --output table

cloudwatch, alarms, monitoring

GCP25

Authenticate with Google Cloud

Authorizes the gcloud CLI to access Google Cloud Platform with your user credentials.

gcloud auth login

auth, login

Set active GCP project

Sets the default project ID for all subsequent gcloud commands.

gcloud config set project <project-id>

project, config

Get GKE cluster credentials

Fetches cluster credentials for Google Kubernetes Engine and updates your local kubeconfig.

gcloud container clusters get-credentials <cluster-name> --region <region>

gke, kubernetes

List GCE VM instances

Lists all Google Compute Engine instances in the active project.

gcloud compute instances list

compute, vms

SSH into GCE instance

Securely connects to a Compute Engine virtual machine via Identity-Aware Proxy (IAP).

gcloud compute ssh <instance-name> --zone <zone> --tunnel-through-iap

ssh, iap, compute

Get project IAM policy

Fetches the complete IAM policy (roles and members) bound to the current project.

gcloud projects get-iam-policy <project-id>

iam, security

Sync local folder to GCS bucket

Synchronizes the contents of a local directory to a Google Cloud Storage bucket.

gcloud storage rsync ./my-folder gs://<bucket> --recursive

gcloud storage replaces gsutil, which Google now treats as legacy.

storage, gcs, sync

Calculate GCS bucket size

Shows the total size of a Cloud Storage bucket.

gcloud storage du gs://<bucket> --summarize --readable-sizes

storage, gcs, size

Run BigQuery SQL

Executes a standard SQL query directly against BigQuery from the command line.

bq query --use_legacy_sql=false 'SELECT * FROM `project.dataset.table` LIMIT 10'

bigquery, sql, data

Deploy to Cloud Run

Deploys a container image to Cloud Run as a fully managed serverless service.

gcloud run deploy <service-name> --image <image> --region <region>

Add --allow-unauthenticated only if the service should be public on the internet.

serverless, deploy, cloud-run

Access Secret Manager value

Retrieves the decoded payload of a secret stored in GCP Secret Manager.

gcloud secrets versions access latest --secret="<secret-name>"

Prints the secret in plain text to your terminal.

secrets, security

Publish Pub/Sub message

Publishes a test message to a Cloud Pub/Sub topic.

gcloud pubsub topics publish <topic-name> --message="Hello World"

pubsub, messaging

List VPC networks

Lists all VPC networks and their subnet modes in the project.

gcloud compute networks list

vpc, network

Set up Application Default Credentials

Authenticates your local environment so code can use GCP APIs natively.

gcloud auth application-default login

auth, adc

List Cloud Run services

Lists all deployed Cloud Run services in the active project.

gcloud run services list

cloud-run, serverless

Connect to Cloud SQL

Connects with the mysql or psql client, allowlisting your IP address for a few minutes.

gcloud sql connect <instance-name> --user=<user>

sql, database, connect

List firewall rules

Shows all firewall rules in the project.

gcloud compute firewall-rules list

firewall, network, security

Read Cloud Logging entries

Fetches the last 20 log entries from Cloud Logging.

gcloud logging read "resource.type=gce_instance" --limit 20 --format json

logging, monitoring

List Artifact Registry repos

Lists container image repositories in Artifact Registry.

gcloud artifacts repositories list --location=<region>

artifact-registry, docker

Deploy Cloud Function

Deploys a Python Cloud Function triggered by HTTP.

gcloud functions deploy <function-name> --gen2 --region=<region> --runtime=python312 --source=. --entry-point=main --trigger-http

Add --allow-unauthenticated only if the function should be public on the internet.

functions, serverless

List service accounts

Lists all service accounts in the project.

gcloud iam service-accounts list

iam, service-account

List persistent disks

Lists all persistent disks in the project.

gcloud compute disks list

compute, storage, disks

List Cloud DNS zones

Lists all managed DNS zones in the project.

gcloud dns managed-zones list

dns, zones

List GKE node pools

Lists node pools for a specific GKE cluster.

gcloud container node-pools list --cluster=<cluster-name> --region=<region>

gke, nodes, cluster

List billing accounts

Lists billing accounts you have access to.

gcloud billing accounts list

billing, cost

Terraform15

Generate and save a plan

Generates an execution plan to a file.

terraform plan -out=tfplan

plan, review

Apply without confirmation

Applies changes automatically.

Caution. Applies without showing a plan for approval. Use it only in CI, ideally on a reviewed saved plan: terraform apply tfplan.

terraform apply -auto-approve

apply, ci-cd

Import existing resource

Brings existing cloud resource under TF state.

terraform import <resource_address> <cloud-resource-id>

Terraform 1.5 and later also support import blocks in configuration, which show up in the plan.

import, state

Remove resource from state

Removes a resource from state tracking without destroying the actual cloud resource.

terraform state rm <resource_address>

Terraform stops managing the resource; it keeps running. Back up the state first.

state, remove

Force unlock state file

Manually removes a lock on the state file if a previous pipeline crashed.

Caution. Only when you are sure no other run holds the lock. Two runs writing the same state can corrupt it.

terraform force-unlock <lock-id>

state, lock, debug

Init and upgrade providers

Initializes terraform and upgrades all providers to their latest allowed versions.

terraform init -upgrade

init, providers

List Terraform workspaces

Shows all available state workspaces.

terraform workspace list

workspace, state

Validate configuration

Validates the syntax and internal consistency of terraform files.

terraform validate

validate, syntax

Format terraform files

Rewrites all .tf files to a canonical format.

terraform fmt -recursive

format, style

Show outputs

Displays the output values from your terraform state.

terraform output -json

output, state

List all resources in state

Shows all resources currently tracked by terraform.

terraform state list

state, inventory

Show resource in state

Displays attributes of a single resource in the state.

terraform state show <resource_address>

state, inspect

Generate dependency graph

Generates a visual dependency graph of resources in DOT format.

terraform graph | dot -Tpng > graph.png

Needs Graphviz for the dot command.

graph, visualization

Force recreation of a resource

Plans the destroy and re-create of one resource. Replaces the deprecated terraform taint.

terraform apply -replace=<resource_address>

replace, taint, recreate

Create new workspace

Creates and switches to a new terraform workspace.

terraform workspace new <workspace-name>

workspace, create

Docker15

Remove all Docker containers, images and volumes

Stops running containers, then removes stopped containers, unused images, networks, build cache and volumes.

Caution. Destructive: deletes every unused volume, database data included. Leave out --volumes to keep volumes.

docker ps -q | xargs -r docker stop && docker system prune -a --volumes -f

cleanup, nuke, prune

Open a shell in a container

Starts an interactive shell inside a running container.

docker exec -it <container-id> /bin/sh

Use /bin/bash if the image has it.

exec, shell

Live container metrics

Shows a live stream of CPU/Memory usage.

docker stats

metrics, performance

Build image without cache

Forces a completely fresh docker build bypassing all cached layers.

docker build --no-cache -t <image-name>:<tag> .

build, cache

Remove dangling images

Removes dangling images: untagged <none> layers left behind by rebuilds.

docker image prune -f

cleanup, images

Start Compose services in the background

Starts all services defined in a docker-compose.yml in the background.

docker compose up -d

compose, daemon

Get container IP

Extracts the internal IP address of a running docker container.

docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container-id>

inspect, ip

Follow container logs

Tails the logs of a docker container continuously.

docker logs -f <container-id>

logs, tail

List volumes

Lists all Docker volumes on the host.

docker volume ls

volume, storage

List networks

Lists all Docker networks.

docker network ls

network, list

Tag an image

Tags a local image with a new name for pushing to a registry.

docker tag <image-id> <registry>/<repo>:<tag>

tag, registry

Push image to registry

Pushes a tagged image to a container registry.

docker push <registry>/<repo>:<tag>

push, registry

Copy files from container

Copies a file from inside a running container to the host.

docker cp <container-id>:/path/in/container /local/path

copy, files

View image layer history

Shows the build history and layer sizes of a Docker image.

docker history <image-name>

history, layers, debug

Save an image to a tar file

Writes an image to a tar file for offline transfer. Load it on the other host with docker load -i image.tar.

docker save -o image.tar <image-name>:<tag>

save, load, offline

Git13

Undo last commit (keep changes)

Undoes the last commit and keeps its changes in the working directory.

git reset HEAD~1

If the commit is already pushed, use git revert instead.

undo, reset

Force overwrite local branch

Discards local changes to match remote.

Caution. Destroys uncommitted changes and local commits that are not on the remote. Stash or branch first if in doubt.

git fetch --all && git reset --hard origin/<branch-name>

force, pull

Delete merged local branches

Deletes branches already merged into main.

git branch --merged main | grep -Ev '^\*|^[[:space:]]*(main|master)$' | xargs -r git branch -d

cleanup, branches

Stash specific files

Interactively choose which changes to stash.

git stash push -p -m "message"

stash, interactive

Interactive rebase (squash)

Starts an interactive rebase for the last N commits.

git rebase -i HEAD~3

rebase, squash, history

Cherry pick a commit

Applies the changes introduced by a specific commit from another branch.

git cherry-pick <commit-hash>

cherry-pick, commits

Fetch and prune remote branches

Fetches updates and removes local tracking branches that were deleted on remote.

git fetch -p

fetch, prune

Rebase onto origin main

Fetches and immediately rebases your current branch onto the latest origin/main.

git pull --rebase origin main

rebase, sync

Create annotated tag

Creates a version tag with a message.

git tag -a v1.0.0 -m 'Release v1.0.0'

tag, release

Binary search for bug (bisect)

Uses binary search to find the commit that introduced a bug.

git bisect start && git bisect bad && git bisect good <known-good-commit>

bisect, debug, history

Pretty git log graph

Shows a compact, colorful branch/merge history.

git log --oneline --graph --decorate --all

log, graph, history

Diff staged changes

Shows the diff of files staged for the next commit.

git diff --staged

diff, staged, review

Blame a file

Shows who last modified each line of a file.

git blame <filename>

blame, history, author

CI/CD17

List recent GitHub Actions runs

Lists the most recent GitHub Actions workflow runs (requires gh cli).

gh run list --limit 5

github, actions, cli

Watch a GitHub Actions run

Follows the logs of a running GitHub Actions workflow.

gh run watch

github, actions, logs

Run GitHub Actions locally

Uses nektos/act to run your github actions locally via docker.

act -l

github-actions, act, local

Create PR via CLI

Creates a pull request from the current branch using GitHub CLI.

gh pr create --title "feat: my feature" --body "Description" --base main

github, pr, cli

Merge PR via CLI

Merges a pull request using squash merge.

gh pr merge --squash --delete-branch

github, pr, merge

Create GitHub release

Creates a new release on GitHub with auto-generated notes.

gh release create v1.0.0 --generate-notes

github, release, tag

Trigger Jenkins build via API

Triggers a Jenkins job build remotely using curl.

curl -X POST "https://jenkins.example.com/job/<job-name>/build" --user "<user>:$JENKINS_TOKEN"

Reads the API token from an environment variable so it stays out of your shell history.

jenkins, trigger, api

Scan image with Docker Scout

Scans a container image for known CVEs.

docker scout cves <image-name>:<tag>

security, cve, scan

Scan image with Trivy

Scans a container image for vulnerabilities using Trivy.

trivy image <image-name>:<tag>

trivy, security, vulnerability

Lint a Dockerfile

Lints a Dockerfile for best practices and common mistakes.

hadolint Dockerfile

dockerfile, lint, best-practices

ArgoCD sync app

Forces a sync of an ArgoCD application.

argocd app sync <app-name>

argocd, gitops, sync

ArgoCD diff

Shows the diff between the live state and desired state in ArgoCD.

argocd app diff <app-name>

argocd, gitops, diff

Manually trigger workflow

Triggers a workflow_dispatch event on a GitHub Actions workflow.

gh workflow run <workflow-name>

github-actions, dispatch, trigger

Semantic version bump

Bumps the version in package.json using npm.

npm version patch -m 'chore: bump version to %s'

semver, version, release

Re-run the failed jobs of a run

Re-runs only the jobs that failed in a GitHub Actions run.

gh run rerun <run-id> --failed

github, actions, retry

Show the logs of failed steps

Prints the logs of only the failed steps of a GitHub Actions run.

gh run view <run-id> --log-failed

github, actions, logs

Lint GitHub Actions workflows

Checks the workflow files in .github/workflows for syntax and expression errors.

actionlint

github, actions, lint

Ansible13

Ping all hosts

Verifies connectivity and python availability on all inventory hosts.

ansible all -m ping -i inventory.ini

ping, connectivity

Playbook dry run

Runs a playbook in check mode to see what would change without actually changing anything.

ansible-playbook playbook.yml --check --diff

playbook, dry-run

Gather facts from host

Collects system information (facts) from a specific host.

ansible <hostname> -m setup

facts, system

Run ad-hoc command

Executes a one-off shell command on all hosts.

ansible all -m shell -a 'uptime' -i inventory.ini

ad-hoc, shell

Encrypt a file with Ansible Vault

Encrypts a sensitive file (like secrets.yml) using Ansible Vault.

ansible-vault encrypt secrets.yml

vault, encrypt, secrets

View an Ansible Vault file

Decrypts and displays the contents of a vault-encrypted file.

ansible-vault view secrets.yml

vault, decrypt, view

Show inventory graph

Displays the host/group structure of your inventory as a tree.

ansible-inventory --graph -i inventory.ini

inventory, graph, hosts

Run playbook with tags

Runs only the tasks tagged with a specific tag.

ansible-playbook playbook.yml --tags deploy

playbook, tags, selective

Install a collection from Ansible Galaxy

Installs a collection of modules and plugins from Ansible Galaxy.

ansible-galaxy collection install community.general

galaxy, collections

Lint playbooks

Checks playbooks for best practices and potential issues.

ansible-lint playbook.yml

lint, best-practices

Run a playbook against one host

Runs a playbook only on the hosts or groups you name.

ansible-playbook playbook.yml -i inventory.ini --limit <host>

limit, playbook

Resume a playbook at a task

Starts a playbook at the named task and asks before running each one.

ansible-playbook playbook.yml -i inventory.ini --start-at-task "<task-name>" --step

playbook, debug

Encrypt a single variable with Vault

Reads a value from stdin (finish with Ctrl+D) and prints an encrypted variable to paste into a vars file.

ansible-vault encrypt_string --stdin-name '<variable-name>'

vault, secrets

Linux26

Largest items in the current directory

Lists the 10 largest files and directories here (dotfiles excluded).

du -hs * | sort -rh | head -10

disk, storage, du

Find files over 100 MB

Finds files over 100 MB on the root filesystem, largest first.

sudo find / -xdev -type f -size +100M -exec du -h {} + 2>/dev/null | sort -rh | head -20

disk, files, find

Tail systemd service logs

Follows journalctl logs for a service in real-time.

journalctl -u <service-name> -f

logs, systemd

Stop the process listening on a port

Sends SIGTERM to the process listening on a TCP port.

Caution. Use kill -9 only if the process ignores SIGTERM: -9 skips its shutdown and cleanup.

kill $(lsof -t -i:<port> -sTCP:LISTEN)

process, port, kill

Find the processes using the most CPU

Lists the top 10 processes consuming the most CPU.

ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -11

cpu, performance, ps

Search string recursively

Searches for a string inside all files in a directory.

grep -rnw '/path/to/somewhere/' -e 'pattern'

search, grep, files

Set permissions on directories only

Recursively changes permissions of directories only (leaving files untouched).

find . -type d -exec chmod 755 {} \;

permissions, chmod, directories

Print specific columns with awk

Prints only the 3rd and 5th columns of a space-separated file.

awk '{print $3, $5}' data.txt

awk, text, processing

Find and replace in a file with sed

Replaces 'old-string' with 'new-string' inline in a file.

sed -i 's/old-string/new-string/g' config.yaml

GNU sed. On macOS, use sed -i '' instead of sed -i.

sed, replace, text

Delete log files older than 30 days

Finds .log files older than 30 days under /var/log and deletes them.

Caution. Deletes files permanently. Run it once without -delete to see the list first.

sudo find /var/log -type f -name "*.log" -mtime +30 -delete

find, cleanup, logs

Sync directories securely

Uses rsync to synchronize two directories over SSH, showing progress.

rsync -avz --progress /local/dir/ user@remote:/remote/dir/

rsync, sync, ssh

Check free memory

Shows total, used and available memory in human-readable units.

free -h

memory, ram

Check disk space

Shows filesystem disk space usage and types.

df -Th

disk, storage

Find and change owner

Finds files owned by root and changes them to another user.

Caution. Changes ownership of everything it matches. Check the path first; run against / it can break the system.

find /path -user root -exec chown user:group {} +

chown, permissions

Create tar.gz archive

Compresses a directory into a tarball.

tar -czvf archive.tar.gz /path/to/dir

tar, compress

Watch a command output

Runs a command repeatedly every 2 seconds, refreshing output.

watch -n 2 'kubectl get pods'

watch, monitoring, repeat

List listening ports and their processes

Shows TCP and UDP sockets in the LISTEN state with the owning process. The modern replacement for netstat -tulnp.

sudo ss -tulpn

ss, ports, netstat

List block devices

Shows all block devices (disks, partitions) in a tree view.

lsblk -f

disk, partitions, lsblk

Enable service on boot

Enables a systemd service to start automatically on boot.

sudo systemctl enable <service-name>

systemd, boot, service

Search command history

Searches your bash history for a specific command.

history | grep <keyword>

history, search, bash

Edit cron jobs

Opens the crontab editor to schedule recurring tasks.

crontab -e

cron, schedule, automation

Create a new user

Creates a new system user with a home directory.

sudo useradd -m -s /bin/bash <username>

user, admin, account

Check system uptime and load

Shows how long the system has been running plus load averages.

uptime

uptime, load, health

View kernel messages

Shows kernel ring buffer messages, useful for hardware/driver debugging.

sudo dmesg --level=err,warn -T | tail -30

kernel, dmesg, hardware

Extract tar.gz archive

Extracts a compressed tarball archive to the current directory.

tar -xzvf archive.tar.gz

tar, unzip, archive

Networking17

Fetch HTTP headers only

Fetches only the HTTP response headers.

curl -I https://example.com

http, curl, headers

Trace DNS resolution path

Follows the DNS delegation path from root servers.

dig +trace <domain>

dns, dig

Test TCP port connectivity

Uses netcat to check if a remote TCP port is reachable.

nc -vz <hostname> <port>

tcp, connectivity, nc

Capture packets on port

Captures and displays raw network traffic on a specific port.

sudo tcpdump -i any port 80 -n -v

tcpdump, packets, sniffing

Check a remote TLS certificate's expiry

Fetches and displays the expiration date of a remote SSL certificate.

echo | openssl s_client -servername example.com -connect example.com:443 2>/dev/null | openssl x509 -noout -dates

ssl, tls, certificate

Format JSON with jq

Fetches a JSON API response and formats it nicely using jq.

curl -s https://api.github.com/users/octocat | jq '.'

curl, jq, json

Test Nginx configuration

Tests the Nginx config files for syntax errors before reloading.

sudo nginx -t

nginx, config, test

Reload Nginx gracefully

Reloads the Nginx configuration without dropping active connections.

sudo nginx -s reload

nginx, reload

Monitor Nginx access logs

Tails the Nginx access logs and uses awk to show only IPs and HTTP status.

tail -f /var/log/nginx/access.log | awk '{print $1, $9}'

nginx, logs, awk

Check IP routing

Determines exactly which interface and route will be used to reach an IP.

ip route get 8.8.8.8

route, ip

Ping via specific interface

Forces ping to use a specific network interface.

ping -I eth1 8.8.8.8

ping, interface

Network path analysis (mtr)

Combines ping and traceroute for real-time network path analysis.

mtr --report <hostname>

mtr, traceroute, latency

List iptables rules

Shows all current iptables firewall rules with line numbers.

sudo iptables -L -n -v --line-numbers

iptables, firewall, rules

DNS lookup

Queries a DNS server to resolve a domain name.

nslookup <domain> 8.8.8.8

dns, nslookup, resolve

Mirror a website with wget

Downloads an entire website for offline browsing.

wget --mirror --convert-links --page-requisites <url>

wget, download, mirror

Send POST request with JSON

Sends a JSON payload to an API endpoint.

curl -X POST -H "Content-Type: application/json" -d '{"key":"value"}' https://api.example.com/endpoint

curl, post, api

WHOIS domain lookup

Fetches domain registration information.

whois example.com

whois, domain, dns

Security16

Generate CSR and private key

Creates a new 2048-bit RSA private key and a Certificate Signing Request.

openssl req -new -newkey rsa:2048 -nodes -keyout mydomain.key -out mydomain.csr

The private key is written unencrypted (-nodes); keep mydomain.key private.

ssl, openssl, csr

Read a local certificate file

Reads an x509 certificate file and outputs its details.

openssl x509 -in certificate.crt -text -noout

ssl, openssl, verify

Scan open ports with Nmap

Performs a fast network scan to find open ports on a target IP.

Caution. Scan only hosts and networks you own or have written permission to test.

nmap -F 192.168.1.1

nmap, scan, ports

Fix SSH key permissions

Secures a private SSH key file so only the owner can read it.

chmod 600 ~/.ssh/id_ed25519

ssh, permissions

Check fail2ban status

Shows the status of fail2ban jails and banned IPs.

sudo fail2ban-client status sshd

fail2ban, brute-force, ssh

Encrypt file with GPG

Encrypts a file using symmetric encryption with GPG.

gpg -c sensitive-file.txt

gpg, encrypt, files

Find SUID binaries

Finds all binaries with the SUID bit set (potential privilege escalation vectors).

find / -perm -4000 -type f 2>/dev/null

suid, audit, privilege

Show recent logins

Displays the last 20 user login records.

last -n 20

login, audit, users

Generate bcrypt password hash

Prompts for a password and prints its bcrypt hash, so the password never lands in your shell history.

python3 -c "import bcrypt, getpass; print(bcrypt.hashpw(getpass.getpass().encode(), bcrypt.gensalt()).decode())"

Needs the bcrypt package: pip install bcrypt.

bcrypt, hash, password

Copy SSH key to server

Installs your public key on a remote server for passwordless login.

ssh-copy-id -i ~/.ssh/id_ed25519.pub user@remote-host

ssh, key, auth

Scan infrastructure code for misconfigurations

Checks Terraform, Kubernetes manifests and Dockerfiles in the current directory against security rules.

trivy config .

trivy, iac, terraform

Scan a repository for leaked secrets

Searches the git history of the current repository for keys, tokens and passwords.

gitleaks git -v .

Versions before 8.19 use gitleaks detect instead.

secrets, git, scan

Download the IAM credential report

Generates and saves a CSV of every IAM user with password, access key and MFA status.

aws iam generate-credential-report && aws iam get-credential-report --query Content --output text | base64 --decode > credential-report.csv

If the report is not ready yet, wait a few seconds and run the second command again.

iam, audit, access-keys

List what a service account can do

Shows every action a Kubernetes service account is allowed to perform in a namespace.

kubectl auth can-i --list -n <namespace> --as=system:serviceaccount:<namespace>:<service-account>

Needs permission to impersonate service accounts.

rbac, kubernetes, audit

Databases15

Back up a PostgreSQL database

Creates a logical backup of a PostgreSQL database.

pg_dump -U <username> -h <host> -d <database_name> > backup.sql

Add -Fc for a compressed custom-format dump that pg_restore can restore selectively.

postgres, backup

Import a MySQL dump

Imports an SQL file into a MySQL database.

Caution. Dumps made by mysqldump include DROP TABLE statements by default, so existing tables are replaced.

mysql -u <username> -p <database_name> < backup.sql

mysql, import, restore

Delete all Redis keys

Connects to redis-cli and deletes all keys in all databases.

Caution. Deletes every key in every database on the server. There is no undo.

redis-cli flushall

redis, cache, flush

Restore a PostgreSQL custom-format dump

Restores a dump made with pg_dump -Fc, in a single transaction.

pg_restore -U <username> -h <host> -d <database_name> -1 backup.dump

pg_restore can't read a plain .sql dump; restore that with psql -d <database_name> -f backup.sql.

postgres, restore

Back up a MySQL database

Dumps a MySQL database to an SQL file; --single-transaction gives a consistent InnoDB dump without locking tables.

mysqldump -u <username> -p --single-transaction <database_name> > backup.sql

mysql, dump, backup

Redis server info

Shows detailed information about the Redis server.

redis-cli info

redis, info, status

Search Redis keys by pattern

Lists keys matching a glob-style pattern without blocking the server.

redis-cli --scan --pattern 'user:*'

Avoid KEYS in production: it blocks Redis while it walks every key.

redis, keys, search

Export MongoDB collection

Exports a MongoDB collection to a JSON file.

mongoexport --db=mydb --collection=users --out=users.json

mongo, export, json

Import MongoDB collection

Imports a JSON file into a MongoDB collection.

mongoimport --db=mydb --collection=users --file=users.json

mongo, import, json

Show active PostgreSQL connections

Shows all active connections and their states in PostgreSQL.

psql -c "SELECT pid, usename, state, query FROM pg_stat_activity WHERE state != 'idle';"

postgres, connections, debug

Check database size (PG)

Shows the size of each database in PostgreSQL.

psql -c "SELECT pg_database.datname, pg_size_pretty(pg_database_size(pg_database.datname)) FROM pg_database;"

postgres, size, storage

Show the MySQL process list

Shows all currently running queries in MySQL.

mysql -e 'SHOW FULL PROCESSLIST;'

mysql, process, debug

Find blocked PostgreSQL queries

Lists sessions waiting on a lock and the PIDs blocking them.

psql -c "SELECT pid, pg_blocking_pids(pid) AS blocked_by, state, wait_event_type, left(query, 60) AS query FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;"

postgres, locks, blocking

End a PostgreSQL session

Terminates a backend by PID, for example the one blocking others.

Caution. Ends the session and rolls back its open transaction. Try pg_cancel_backend(<backend-pid>) first, which cancels only the running query.

psql -c "SELECT pg_terminate_backend(<backend-pid>);"

postgres, kill, sessions

Find the largest Redis keys

Samples the keyspace with SCAN and reports the biggest key of each type.

redis-cli --bigkeys

Uses SCAN, so it doesn't block the server, but it adds load; run it off-peak.

redis, memory

Observability22

Check Elasticsearch health

Fetches the current health status of the ES cluster.

curl -X GET "localhost:9200/_cluster/health?pretty"

elasticsearch, elk, health

List Elasticsearch indices

Shows all indices in the ES cluster with their health, status, and size.

curl -X GET "localhost:9200/_cat/indices?v"

elasticsearch, elk, indices

Delete Elasticsearch index

Deletes one index.

Caution. Permanently deletes the index and its data.

curl -X DELETE "localhost:9200/<index-name>"

elasticsearch, elk, delete

PromQL: Pod CPU usage

CPU cores used per pod, averaged over 5 minutes. container!="" drops the pod-level series that would double-count.

sum by (pod) (rate(container_cpu_usage_seconds_total{namespace="<namespace>", container!=""}[5m]))

prometheus, promql, cpu

PromQL: Pod memory usage

Working-set memory per pod in MiB: the figure kubectl top shows and the kubelet uses for eviction.

sum by (pod) (container_memory_working_set_bytes{namespace="<namespace>", container!=""}) / 1024 / 1024

prometheus, promql, memory

Restart the Grafana server

Restarts the grafana systemd service.

sudo systemctl restart grafana-server

grafana, systemd, restart

Query Prometheus API

Fetches current metric values from the Prometheus HTTP API.

curl -s "http://localhost:9090/api/v1/query?query=up" | jq .

prometheus, api, query

Check Prometheus targets

Lists all scrape targets and their health status.

curl -s "http://localhost:9090/api/v1/targets" | jq '.data.activeTargets[] | {job: .labels.job, health: .health}'

prometheus, targets, health

List Grafana datasources

Lists all configured data sources in Grafana via API.

curl -s -H "Authorization: Bearer <service-account-token>" http://localhost:3000/api/datasources | jq .

Grafana service account tokens replace the old API keys.

grafana, datasource, api

Check Alertmanager status

Shows the current status and active alerts in Alertmanager.

curl -s http://localhost:9093/api/v2/alerts | jq .

alertmanager, alerts, status

Check Node Exporter metrics

Fetches raw metrics from Node Exporter.

curl -s http://localhost:9100/metrics | grep node_cpu_seconds_total | head -5

node-exporter, metrics, cpu

Query Loki logs

Queries Loki for logs matching a label selector.

curl -G -s "http://localhost:3100/loki/api/v1/query_range" --data-urlencode 'query={job="varlogs"}' | jq .

loki, logs, query

PromQL: HTTP error rate

Calculates the percentage of 5xx responses over the last 5 minutes.

sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) * 100

promql, errors, sre

PromQL: P99 latency

Calculates the 99th percentile request latency from a histogram.

histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))

promql, latency, p99

Check Metrics Server

Verifies that the Kubernetes metrics-server is running and healthy.

kubectl get deployment metrics-server -n kube-system

metrics-server, k8s, health

Blackbox Exporter probe

Tests HTTP endpoint availability using Blackbox Exporter.

curl -s "http://localhost:9115/probe?target=https://example.com&module=http_2xx" | grep probe_success

blackbox, probe, uptime

Query Jaeger traces

Fetches recent traces from Jaeger for a specific service.

curl -s "http://localhost:16686/api/traces?service=my-service&limit=5" | jq '.data[].traceID'

jaeger, tracing, distributed

cAdvisor container stats

Fetches container-level resource stats from cAdvisor.

curl -s http://localhost:8080/api/v1.3/containers | jq '.spec.cpu'

cadvisor, containers, metrics

Check Prometheus rule files

Validates the syntax of alerting and recording rules before you load them.

promtool check rules rules.yml

prometheus, rules, validate

Check an Alertmanager config

Validates alertmanager.yml and summarises its receivers and routes.

amtool check-config alertmanager.yml

alertmanager, validate

Silence an alert

Silences an alert by name for two hours, with a comment saying why.

amtool silence add alertname="<alert-name>" --duration=2h --comment="<reason>" --alertmanager.url=http://localhost:9093

alertmanager, silence

Reload the Prometheus configuration

Tells Prometheus to re-read its configuration and rule files without a restart.

curl -X POST http://localhost:9090/-/reload

Works only when Prometheus runs with --web.enable-lifecycle.

prometheus, reload

Debugging11

Trace system calls of a process

Prints out all system calls a PID makes (crucial for deep debugging).

strace -p <pid>

Slows the traced process noticeably; be careful on busy production hosts.

strace, syscalls

List open files by process

Shows all files, sockets, and connections opened by a PID.

lsof -p <pid>

lsof, files, sockets

Live CPU profiling (perf)

Shows a live view of the hottest CPU functions in the system.

sudo perf top

perf, cpu, profiling

Virtual memory stats

Shows system performance statistics (CPU, memory, I/O) every 2 seconds.

vmstat 2 10

vmstat, memory, io

Disk I/O statistics

Shows CPU and disk I/O stats, refreshing every second.

iostat -xz 1

iostat, disk, io

Count connections by state

Groups and counts TCP connections by their state (ESTABLISHED, TIME_WAIT, etc.).

ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c | sort -rn

connections, tcp, debug

Capture a core dump of a running process

Writes a core file and lets the process carry on; it pauses only while the dump is written. gcore ships with gdb.

sudo gcore -o core <pid>

core, gdb, post-mortem

Curl with timing breakdown

Shows detailed timing of DNS, connect, TLS, and transfer phases.

curl -o /dev/null -s -w "DNS: %{time_namelookup}s\nConnect: %{time_connect}s\nTLS: %{time_appconnect}s\nTotal: %{time_total}s\n" https://example.com

curl, timing, latency

Debug a pod with an ephemeral container

Attaches a temporary debug container that shares the target container's processes; useful when the image has no shell.

kubectl debug -it <pod-name> -n <namespace> --image=busybox:1.36 --target=<container-name>

kubernetes, ephemeral, shell

Find deleted files still held open

Lists files that were deleted but are still open. Their space is not freed until the process closes them, so a disk can be full while du looks fine.

sudo lsof +L1

disk, lsof, space

Find out-of-memory kills

Searches the kernel log for processes the OOM killer ended.

sudo journalctl -k | grep -iE 'out of memory|killed process'

oom, memory, kernel