devops cheatsheet
1661 commands · click to copy
1661 shown
tool
tag
List all pods across namespaces
kubectl
All pods with node placement and IPs
kubectl get pods -A -o wide
Describe a pod
kubectl
Full details: events, conditions, volume mounts
kubectl describe pod <name> -n <ns>
Follow pod logs
kubectl
Stream logs in real time; add -c <container> for multi-container pods
kubectl logs -f <pod> -n <ns>
Logs from previous container
kubectl
Logs from the last crashed/restarted container instance
kubectl logs <pod> --previous -n <ns>
Exec into pod
kubectl
Interactive shell inside a running container
kubectl exec -it <pod> -n <ns> -- bash
Port-forward a service
kubectl
Tunnel a cluster service port to localhost
kubectl port-forward svc/<name> 8080:80 -n <ns>
Watch rollout status
kubectl
Block until rollout completes or times out (use in CI)
kubectl rollout status deployment/<name> -n <ns>
Rollback deployment
kubectl
Revert to the previous revision
kubectl rollout undo deployment/<name> -n <ns>
Scale deployment
kubectl
Immediately change replica count
kubectl scale deployment/<name> --replicas=3 -n <ns>
Get events sorted by time
kubectl
Recent cluster events, oldest first — great for post-incident review
kubectl get events -A --sort-by='.lastTimestamp'
Server-side dry-run
kubectl
Validate manifest against live API without applying changes
kubectl apply --server-side --dry-run=server -f file.yaml
Export live resource as YAML
kubectl
Current live state with managed fields stripped; useful as a base
kubectl get deployment/<name> -n <ns> -o yaml
Force delete stuck pod
kubectl
Remove a Terminating pod immediately (use with caution)
kubectl delete pod <name> -n <ns> --grace-period=0 --force
Copy file from pod
kubectl
Extract a file from a running container
kubectl cp <ns>/<pod>:/remote/path ./local-path
Drain a node
kubectl
Gracefully evict all pods before maintenance
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data
Edit a live resource
kubectl
Open resource in $EDITOR; changes applied on save
kubectl edit deployment/<name> -n <ns>
Verify RBAC permissions
kubectl
Check what a ServiceAccount is allowed to do
kubectl auth can-i list pods --as=system:serviceaccount:<ns>:<sa> -n <ns>
Deploy a chart; creates namespace if it doesn't exist
helm install <release> <chart> -f values.yaml -n <ns> --create-namespace
Safe in CI — installs if absent, upgrades if present
helm upgrade --install <release> <chart> -f values.yaml -n <ns>
Diff before upgrade
helm
Show exactly what will change (requires helm-diff plugin)
helm diff upgrade <release> <chart> -f values.yaml -n <ns>
Output rendered YAML to stdout without deploying
helm template <release> <chart> -f values.yaml --debug
Show release values
helm
All computed values for a deployed release
helm get values <release> -n <ns> --all
Revert to a specific historical revision
helm rollback <release> <revision> -n <ns>
Lint a chart
helm
Validate chart structure and values; fails on warnings in --strict mode
helm lint <chart-dir> -f values.yaml --strict
Summary table: Kustomizations, HelmReleases, Sources — with sync status
flux get all -A
Trigger immediate git pull + apply
flux reconcile kustomization <name> --with-source -n <ns>
Re-run Helm install/upgrade cycle immediately
flux reconcile helmrelease <name> --with-source -n <ns>
Trace a resource
flux
Show which Flux objects own and manage this resource
flux trace <kind>/<name> -n <ns>
Pause sync — useful while doing manual hotfixes
flux suspend kustomization <name> -n <ns>
Re-enable a suspended Kustomization or HelmRelease
flux resume kustomization <name> -n <ns>
Backup current Flux config as plain YAML for bootstrapping another cluster
flux export kustomization --all > clusters/cluster.yaml
Cross-compile and push directly to registry with BuildKit
docker buildx build --platform linux/amd64,linux/arm64 -t reg/img:tag --push .
Run container with env file
docker
Local run with env vars from file; --rm auto-removes on exit
docker run --rm -it --env-file .env -p 8000:8000 img:tag
Inspect image layers
docker
See each layer, its command, and size; identify bloat
docker history --no-trunc img:tag
Prune everything unused
docker
Remove stopped containers, unused images, networks, volumes
docker system prune -af --volumes
Re-tag and push to another registry
docker pull src-reg/img:tag && docker tag src-reg/img:tag dst-reg/img:tag && docker push dst-reg/img:tag
Save image to tarball
docker
Export an image for air-gapped transfer
docker save img:tag | gzip > img.tar.gz
Plan with var file
terraform
Show changes; save plan artifact for CI gating
terraform plan -var-file=prod.tfvars -out=plan.tfplan
Apply a saved plan
terraform
Apply exactly the previously generated plan — no interactive prompts
terraform apply plan.tfplan
Import existing resource
terraform
Bring an already-existing resource under Terraform control
terraform import module.path.resource_type.name <remote-id>
Show state for a resource
terraform
Inspect Terraform state attributes for a single resource
terraform state show module.path.resource_type.name
Move resource in state
terraform
Rename/reorganize resource without destroying and recreating it
terraform state mv old.address new.address
Ephemeral debug container
k8s-debug
Attach a debug container (netshoot) to a running pod — shares PID/net namespaces
kubectl debug -it <pod> --image=nicolaka/netshoot -n <ns>
Pod resource usage sorted
k8s-debug
Memory-sorted pod usage across all namespaces — find the hungry ones
kubectl top pods -A --sort-by=memory
Check what's in a ConfigMap
k8s-debug
Print just the data field; pipe to python -m json.tool for formatting
kubectl get cm <name> -n <ns> -o jsonpath='{.data}'
Decode a Secret
k8s-debug
Dump and base64-decode all fields in a k8s Secret
kubectl get secret <name> -n <ns> -o jsonpath='{.data}' | python3 -c "import sys,json,base64; [print(k,'=',base64.b64decode(v).decode()) for k,v in json.load(sys.stdin).items()]"
List all resources in namespace
k8s-debug
Enumerate every resource type in a namespace — useful for auditing
kubectl api-resources --verbs=list --namespaced -o name | xargs -I{} kubectl get {} -n <ns> --ignore-not-found
JSONPath on any resource
k8s-debug
Extract specific fields from k8s API objects without jq
kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}\t{.metadata.name}\t{.status.phase}\n{end}'
Get resource with custom columns
kubectl
Print only the fields you care about without jq
kubectl get pods -n <ns> -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,STATUS:.status.phase'
Patch resource field
kubectl
Inline JSON patch without editing the whole manifest
kubectl patch deployment <name> -n <ns> -p '{"spec":{"replicas":2}}'
Annotate resource
kubectl
Set or update an annotation; --overwrite replaces existing value
kubectl annotate pod <pod> -n <ns> key=value --overwrite
Label resource
kubectl
Add or change a label on any resource
kubectl label node <node> role=worker --overwrite
Add taint to node
kubectl
Prevent pods without matching toleration from scheduling on node
kubectl taint nodes <node> key=value:NoSchedule
Remove taint from node
kubectl
Remove a taint by appending a dash at the end
kubectl taint nodes <node> key=value:NoSchedule-
Set image on deployment
kubectl
Rolling-update the container image without editing YAML
kubectl set image deployment/<name> <container>=image:tag -n <ns>
List rollout history
kubectl
Show all revisions with change cause (requires --record or annotations)
kubectl rollout history deployment/<name> -n <ns>
Restart deployment (rolling)
kubectl
Trigger zero-downtime pod rotation without changing spec
kubectl rollout restart deployment/<name> -n <ns>
Create namespace
kubectl
Create a new namespace; idempotent with --dry-run=client | apply
kubectl create namespace <ns>
Set resource requests/limits
kubectl
Update resource requests and limits on a running deployment
kubectl set resources deployment/<name> -c <container> --requests=cpu=100m,memory=128Mi --limits=cpu=500m,memory=512Mi -n <ns>
Run one-off pod
kubectl
Ephemeral pod for debugging; deleted on exit
kubectl run tmp --image=nicolaka/netshoot -it --rm --restart=Never -n <ns> -- bash
Get HPA status
kubectl
Horizontal Pod Autoscaler current/desired replicas and metrics
kubectl get hpa -A
View resource quotas
kubectl
Used vs hard limits for CPU, memory, object counts in namespace
kubectl describe resourcequota -n <ns>
Get PodDisruptionBudget
kubectl
Show min-available and current healthy pod counts
kubectl get pdb -A
View LimitRange
kubectl
Default and max resource limits applied to pods in namespace
kubectl describe limitrange -n <ns>
Get all CRDs
kubectl
List all Custom Resource Definitions sorted by creation time
kubectl get crds --sort-by='.metadata.creationTimestamp'
Get service endpoints
kubectl
Show pod IPs backing a Service — diagnose selector mismatch
kubectl get endpoints <svc> -n <ns>
See cert-manager Certificate ready status and expiry dates
kubectl get certificate -A -o wide
View pod topology spread
kubectl
Inspect topology spread constraints on a pod
kubectl get pod <pod> -n <ns> -o jsonpath='{.spec.topologySpreadConstraints}'
Apply with prune
kubectl
Apply manifests and remove stale objects matching the label selector
kubectl apply -f ./dir/ --prune -l app=<label> -n <ns>
Diff live vs local
kubectl
Show what would change if you applied this manifest now
kubectl diff -f file.yaml
Exec command in all pods
kubectl
Run a command in every pod matching a label selector
kubectl get pods -n <ns> -l app=<label> -o name | xargs -I{} kubectl exec {} -n <ns> -- <cmd>
Watch pod status changes
kubectl
Live-refresh pod list as statuses change
kubectl get pods -n <ns> -w
Top pods by CPU
kubectl
CPU-sorted pod usage across all namespaces
kubectl top pods -A --sort-by=cpu
Create ServiceAccount token
kubectl
Generate a short-lived bound service account token
kubectl create token <sa-name> -n <ns> --duration=1h
Check who can do what (audit)
kubectl
Show all permissions the current user has in a namespace
kubectl auth can-i --list -n <ns>
Delete all pods in namespace
kubectl
Force recreation of all pods — useful after ConfigMap changes
kubectl delete pods --all -n <ns>
Dump all pod YAML to file
kubectl
Backup/inspect entire pod state in a namespace
kubectl get pods -n <ns> -o yaml > pods-dump.yaml
Jsonpath — all container images
kubectl
Enumerate every container image running in the cluster
kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{range .spec.containers[*]}{.image}{"\n"}{end}{end}'
List all available versions of a chart in added repositories
helm search repo <chart> --versions
Add OCI registry
helm
Authenticate to an OCI-based Helm registry
helm registry login registry.example.com -u user -p pass
Upload a packaged chart to an OCI registry
helm push mychart-0.1.0.tgz oci://registry.example.com/charts
Package a chart
helm
Create a .tgz archive from a chart directory
helm package ./my-chart --destination ./dist
Show chart values
helm
Dump default values to a file for customization
helm show values <chart> > values.yaml
Plugin install
helm
Install a Helm plugin from URL (e.g. helm-diff, helm-secrets)
helm plugin install https://github.com/databus23/helm-diff
All Kubernetes manifests generated by this Helm release
helm get manifest <release> -n <ns>
Helm secrets decrypt
helm
Decrypt a SOPS/age-encrypted values file (requires helm-secrets plugin)
helm secrets view secrets.yaml
Get release notes
helm
Print post-install notes for a deployed release
helm get notes <release> -n <ns>
Install Flux and push initial config to GitHub repo
flux bootstrap github --owner=<org> --repository=<repo> --branch=main --path=clusters/production --personal
Register a git repo as a Flux source
flux create source git <name> --url=https://github.com/org/repo --branch=main -n flux-system
Register a Helm chart repository as a Flux source
flux create source helm <name> --url=https://charts.example.com -n flux-system
Create HelmRelease
flux
Deploy a chart via Flux HelmRelease resource
flux create helmrelease <name> --source=HelmRepository/<repo> --chart=<chart> --chart-version='>=1.0.0' -n <ns>
Get Flux events
flux
Recent events from the flux-system namespace
kubectl get events -n flux-system --sort-by='.lastTimestamp' | tail -20
Delete Flux resource
flux
Remove a Kustomization or HelmRelease from the cluster
flux delete kustomization <name> -n <ns>
Auto-update image tags in git when new images are pushed
flux create image update <name> --git-repo-ref=<repo> --git-repo-path=./deploy --checkout-branch=main --push-branch=main -n flux-system
Follow logs from a specific Flux controller
flux logs --kind=kustomize-controller -n flux-system --tail=50
Push image policy
flux
Define which image tags Flux should track for automation
flux create image policy <name> --image-ref=<image-repo> --select-semver='>=1.0.0' -n flux-system
Build kustomization
kustomize
Render all manifests for an overlay to stdout
kustomize build ./overlays/prod
Apply kustomization
kustomize
Build and apply kustomization in one step via kubectl
kubectl apply -k ./overlays/prod
Add resource to kustomization
kustomize
Append a resource file to kustomization.yaml
kustomize edit add resource ./deployment.yaml
Set image in kustomization
kustomize
Update image tag in kustomization.yaml
kustomize edit set image myapp=registry/myapp:v2.0.0
Set namespace
kustomize
Override namespace for all resources in the overlay
kustomize edit set namespace production
Add label to all resources
kustomize
Inject a common label into all generated resources
kustomize edit add label env:production
Add patch
kustomize
Register a strategic merge patch in kustomization.yaml
kustomize edit add patch --path patch.yaml --kind Deployment --name <name>
Build with build args
docker
Pass build-time variables into Dockerfile ARG instructions
docker build --build-arg VERSION=1.2.3 --build-arg ENV=prod -t img:tag .
Scan image with Trivy
docker
Fail pipeline if HIGH or CRITICAL CVEs found
trivy image --exit-code 1 --severity HIGH,CRITICAL img:tag
Check image SBOM
docker
Generate Software Bill of Materials for an image (Docker Desktop)
docker sbom img:tag
Inspect running container
docker
Drill into network settings of a running container
docker inspect <container> | jq '.[0].NetworkSettings.Networks'
Docker compose up detached
docker
Build and start all services in background
docker compose up -d --build
Docker compose logs follow
docker
Stream last 100 lines and follow a compose service
docker compose logs -f --tail=100 <service>
Stop and remove containers, networks, and volumes
docker compose down -v
List container disk usage
docker
Detailed breakdown of disk usage per image, container, volume
docker system df -v
Docker exec as root
docker
Enter container as root even if default user is non-root
docker exec -it -u root <container> bash
Inject a file into a running container without rebuild
docker cp ./local-file.conf <container>:/etc/app/config.conf
Free disk space in a self-hosted Docker Registry
docker exec -it registry bin/registry garbage-collect /etc/docker/registry/config.yml
Multi-stage build target
docker
Build only up to a specific stage in a multi-stage Dockerfile
docker build --target builder -t img:builder .
Create and switch workspace
terraform
Create a new workspace and switch to it
terraform workspace new staging && terraform workspace select staging
Validate configuration
terraform
Check Terraform configuration for syntax and consistency errors
terraform validate
Show output values
terraform
Print all outputs as JSON; useful for pipeline scripting
terraform output -json
Destroy specific resource
terraform
Destroy a single resource without touching everything else
terraform destroy -target=module.vpc.aws_vpc.main
Taint resource (force replace)
terraform
Mark resource for replacement on next apply
terraform taint module.eks.aws_instance.node
Remove resource from state
terraform
Forget a resource from state without destroying it in cloud
terraform state rm module.path.resource_type.name
Refresh state
terraform
Update state file to match real infrastructure
terraform refresh -var-file=prod.tfvars
Graph dependency tree
terraform
Visualize resource dependency graph (requires Graphviz)
terraform graph | dot -Tsvg > graph.svg
List state resources
terraform
Filter state resources by pattern
terraform state list | grep <pattern>
Plan all modules
terragrunt
Plan all dependent Terragrunt modules in order
terragrunt run-all plan --terragrunt-non-interactive
Apply all modules
terragrunt
Apply all modules in dependency order, non-interactive
terragrunt run-all apply --terragrunt-non-interactive
Destroy all modules
terragrunt
Destroy all modules in reverse dependency order
terragrunt run-all destroy --terragrunt-non-interactive
Output all module outputs
terragrunt
Print outputs from all modules as JSON
terragrunt run-all output -json
Validate all configs
terragrunt
Run terraform validate across all modules
terragrunt run-all validate
Run a playbook
ansible
Run playbook with diff output to see what changes
ansible-playbook -i inventory/prod playbook.yml --diff
Limit to specific host
ansible
Run only against specific hosts from inventory
ansible-playbook -i inventory playbook.yml --limit host1,host2
Run specific tag
ansible
Execute only tasks matching these tags
ansible-playbook -i inventory playbook.yml --tags install,configure
Skip specific tags
ansible
Skip tasks with the specified tags
ansible-playbook -i inventory playbook.yml --skip-tags cleanup
Dry run (check mode)
ansible
Simulate execution without making changes
ansible-playbook -i inventory playbook.yml --check --diff
Ad-hoc ping all hosts
ansible
Check connectivity to all hosts in inventory
ansible all -i inventory -m ping
Ad-hoc run shell command
ansible
Run a one-liner shell command on all hosts
ansible all -i inventory -m shell -a 'uptime'
Ad-hoc copy file
ansible
Copy a file to all hosts
ansible all -i inventory -m copy -a 'src=./file dest=/tmp/file'
Gather facts from host
ansible
Collect all Ansible facts (OS, CPU, network) from a host
ansible <host> -i inventory -m setup | jq '._ansible_facts'
Encrypt variable with vault
ansible
Inline-encrypt a string for use in playbooks
ansible-vault encrypt_string 'secret_value' --name 'db_password'
Encrypt file with vault
ansible
Encrypt an entire variable file with Ansible Vault
ansible-vault encrypt vars/secrets.yml
Decrypt vault file
ansible
Decrypt an Ansible Vault-encrypted file in place
ansible-vault decrypt vars/secrets.yml
View encrypted file
ansible
View contents of vault-encrypted file without decrypting on disk
ansible-vault view vars/secrets.yml
Install role from Galaxy
ansible
Download roles listed in requirements.yml to local roles dir
ansible-galaxy install -r requirements.yml -p roles/
Install collection
ansible
Install an Ansible collection from Ansible Galaxy
ansible-galaxy collection install community.kubernetes
List inventory hosts
ansible
Show all hosts and groups parsed from inventory
ansible-inventory -i inventory --list | jq 'keys'
Run with extra vars
ansible
Pass extra variables at runtime overriding playbook defaults
ansible-playbook playbook.yml -e 'env=prod version=2.0'
Verbose output
ansible
Maximum verbosity — shows every task, connection, output
ansible-playbook playbook.yml -vvv
Syntax check playbook
ansible
Validate YAML syntax without executing any tasks
ansible-playbook playbook.yml --syntax-check
Login with AppRole
vault
Authenticate via AppRole auth method
vault write auth/approle/login role_id=<role> secret_id=<secret>
KV get secret
vault
Read a KV v2 secret; add -format=json for scripting
vault kv get -mount=secret path/to/secret
KV put secret
vault
Write or update a KV v2 secret
vault kv put -mount=secret path/to/secret key=value
KV delete secret
vault
Soft-delete the latest version of a KV secret
vault kv delete -mount=secret path/to/secret
See all versions, creation dates, deletion status
vault kv metadata get -mount=secret path/to/secret
Create token with policy
vault
Issue a short-lived token limited to a specific policy
vault token create -policy=read-only -ttl=1h
Enable Kubernetes auth
vault
Enable and configure Kubernetes auth method
vault auth enable kubernetes && vault write auth/kubernetes/config kubernetes_host=https://$KUBERNETES_PORT_443_TCP_ADDR:443
Create Kubernetes role
vault
Bind a k8s ServiceAccount to a Vault policy
vault write auth/kubernetes/role/my-role bound_service_account_names=<sa> bound_service_account_namespaces=<ns> policies=<policy> ttl=1h
Enable secrets engine
vault
Mount a new secrets engine at a given path
vault secrets enable -path=myapp kv-v2
Transit encrypt
vault
Encrypt data using Vault's transit encryption engine
vault write transit/encrypt/my-key plaintext=$(echo -n 'secret' | base64)
Transit decrypt
vault
Decrypt a ciphertext with transit engine
vault write transit/decrypt/my-key ciphertext=vault:v1:... | base64 -d
Describe ExternalSecret
external-secrets
Show sync status, last sync time, and error message if failed
kubectl describe externalsecret <name> -n <ns>
List all ExternalSecrets
external-secrets
See all ESO ExternalSecrets and their Ready status
kubectl get externalsecret -A
Force sync ExternalSecret
external-secrets
Trigger immediate re-sync by updating annotation
kubectl annotate externalsecret <name> -n <ns> force-sync=$(date +%s) --overwrite
List ClusterSecretStores
external-secrets
Show all cluster-scoped secret stores and their status
kubectl get clustersecretstore
Seal a secret
sealed-secrets
Create and seal a k8s secret in one pipeline
kubectl create secret generic mysecret --dry-run=client -n <ns> --from-literal=key=value -o yaml | kubeseal -o yaml > sealed.yaml
Fetch public cert
sealed-secrets
Download the sealing certificate for offline operations
kubeseal --fetch-cert --controller-name=sealed-secrets > pub-cert.pem
Seal with offline cert
sealed-secrets
Seal without cluster access using pre-fetched certificate
kubeseal --cert pub-cert.pem -o yaml < secret.yaml > sealed.yaml
List SealedSecrets
sealed-secrets
Show all SealedSecrets and their sync status
kubectl get sealedsecret -A
List Cilium endpoints
cilium
Show all Cilium-managed endpoints with security identity
cilium endpoint list
Hubble observe flows
cilium
Live-stream network flows for a specific pod
hubble observe --pod <ns>/<pod> -f
Hubble dropped flows
cilium
Show only dropped/denied flows cluster-wide
hubble observe --verdict DROPPED -f
Hubble observe namespace
cilium
Show flows for all pods in a namespace over last 5 minutes
hubble observe --namespace <ns> --since 5m
List network policies
cilium
All Cilium and standard NetworkPolicy resources
kubectl get ciliumnetworkpolicies,networkpolicies -A
Query Prometheus via curl
prometheus
Ad-hoc PromQL query from CLI
curl -sG 'http://prometheus:9090/api/v1/query' --data-urlencode 'query=up' | jq .
Instant query via promtool
prometheus
Run an instant PromQL query using promtool
promtool query instant http://prometheus:9090 'up{job="kubelet"}'
Range query via curl
prometheus
Query Prometheus for a time range via HTTP API
curl -sG 'http://prometheus:9090/api/v1/query_range' --data-urlencode 'query=rate(http_requests_total[5m])' --data-urlencode 'start=2024-01-01T00:00:00Z' --data-urlencode 'end=2024-01-01T01:00:00Z' --data-urlencode 'step=60s' | jq .
Check alert rules
prometheus
Validate Prometheus alert/recording rule files for syntax
promtool check rules rules.yml
Silence active alert
prometheus
Create a silence to mute alert notifications during maintenance
amtool silence add --alertmanager.url=http://alertmanager:9093 alertname=<name> --duration=2h --comment='Maintenance'
List silences
prometheus
Show all active silences in Alertmanager
amtool silence query --alertmanager.url=http://alertmanager:9093
Expire silence
prometheus
Immediately end an active silence
amtool silence expire <id> --alertmanager.url=http://alertmanager:9093
Check alertmanager config
prometheus
Validate Alertmanager configuration file
amtool check-config alertmanager.yml
List active alerts
prometheus
Show all firing alerts in Alertmanager
amtool alert query --alertmanager.url=http://alertmanager:9093
Reload Prometheus config
prometheus
Hot-reload Prometheus configuration without restart
curl -X POST http://prometheus:9090/-/reload
Cluster health
elasticsearch
Show cluster status: green/yellow/red, shards, nodes
curl -s http://localhost:9200/_cluster/health | jq .
List indices
elasticsearch
Tabular index listing sorted by size
curl -s 'http://localhost:9200/_cat/indices?v&h=index,health,pri,rep,docs.count,store.size&s=store.size:desc'
Delete index
elasticsearch
Remove an index and all its data
curl -X DELETE http://localhost:9200/<index>
Get index settings
elasticsearch
Inspect number of shards, replicas, refresh interval
curl -s http://localhost:9200/<index>/_settings | jq .
Reindex
elasticsearch
Copy documents from one index to another
curl -X POST http://localhost:9200/_reindex -H 'Content-Type: application/json' -d '{"source":{"index":"old"},"dest":{"index":"new"}}'
Force merge index
elasticsearch
Reduce segment count; useful before making index read-only
curl -X POST 'http://localhost:9200/<index>/_forcemerge?max_num_segments=1'
Node stats
elasticsearch
Show all ES nodes with JVM heap, load, roles
curl -s http://localhost:9200/_cat/nodes?v
Search query
elasticsearch
Full-text search for documents matching a term
curl -s -X POST http://localhost:9200/<index>/_search -H 'Content-Type: application/json' -d '{"query":{"match":{"message":"error"}}}'
Snapshot create
elasticsearch
Create a snapshot to the registered repository
curl -X PUT http://localhost:9200/_snapshot/<repo>/<snapshot>
ILM explain index
elasticsearch
Show current ILM lifecycle phase and action for an index
curl -s 'http://localhost:9200/<index>/_ilm/explain' | jq '.indices | to_entries[] | {index:.key, phase:.value.phase, action:.value.action}'
Export dashboard
kibana
Export a Kibana dashboard with all dependencies
curl -s 'http://kibana:5601/api/saved_objects/_export' -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d '{"type":"dashboard","includeReferencesDeep":true}' -o dashboard.ndjson
Import dashboard
kibana
Import a previously exported dashboard
curl -X POST 'http://kibana:5601/api/saved_objects/_import' -H 'kbn-xsrf: true' --form file=@dashboard.ndjson
List topics
kafka
List all Kafka topics in the cluster
kafka-topics.sh --bootstrap-server kafka:9092 --list
Create topic
kafka
Create topic with specific partition and replication settings
kafka-topics.sh --bootstrap-server kafka:9092 --create --topic <name> --partitions 3 --replication-factor 2
Describe topic
kafka
Show partition count, replication, leaders and ISR
kafka-topics.sh --bootstrap-server kafka:9092 --describe --topic <name>
Delete topic
kafka
Permanently delete a Kafka topic
kafka-topics.sh --bootstrap-server kafka:9092 --delete --topic <name>
Consume from beginning
kafka
Read all messages from a topic starting from offset 0
kafka-console-consumer.sh --bootstrap-server kafka:9092 --topic <name> --from-beginning
Produce messages
kafka
Send messages to a topic interactively from stdin
kafka-console-producer.sh --bootstrap-server kafka:9092 --topic <name>
List consumer groups
kafka
Show all consumer groups
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --list
Consumer group lag
kafka
Show lag per partition for a consumer group
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --describe --group <group>
Reset a consumer group to the beginning of the topic
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --group <group> --topic <topic> --reset-offsets --to-earliest --execute
Alter topic partitions
kafka
Increase (only) the number of partitions for a topic
kafka-topics.sh --bootstrap-server kafka:9092 --alter --topic <name> --partitions 6
Get topic offsets
kafka
Show earliest and latest offsets per partition
kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list kafka:9092 --topic <name>
Connect to Redis CLI
redis
Open interactive Redis CLI session
redis-cli -h redis -p 6379 -a <password>
Redis info all
redis
Full server information: memory, CPU, clients, persistence
redis-cli -h redis INFO all
Stream all commands executed on the Redis server
redis-cli -h redis MONITOR
Memory usage of key
redis
Show bytes consumed by a specific key
redis-cli -h redis MEMORY USAGE <key>
Check replication info
redis
Show master/replica role, replication offset, connected replicas
redis-cli -h redis INFO replication
Scan keys by pattern
redis
Non-blocking key scan by pattern (prefer over KEYS in production)
redis-cli -h redis --scan --pattern 'session:*' | head -20
TTL of a key
redis
Remaining TTL in seconds; -1 = no expiry, -2 = not found
redis-cli -h redis TTL <key>
Connect with mongosh
mongodb
Open interactive shell to a MongoDB instance
mongosh 'mongodb://user:pass@mongo:27017/dbname'
Replica set status
mongodb
Show replica set members, lag, and election status
mongosh --eval 'rs.status()' mongodb://mongo:27017
Database stats
mongodb
Data size, storage size, collection count for a database
mongosh --eval 'db.stats()' mongodb://mongo:27017/mydb
Collection stats
mongodb
Document count, index sizes, storage for a collection
mongosh --eval 'db.myCollection.stats()' mongodb://mongo:27017/mydb
Current operations
mongodb
Show operations running longer than 5 seconds
mongosh --eval 'db.currentOp({active:true,secs_running:{$gt:5}})' mongodb://mongo:27017
Create dump
mongodb
Export database to BSON files
mongodump --uri='mongodb://user:pass@mongo:27017' --db=mydb --out=/backups/
Restore dump
mongodb
Import BSON backup into MongoDB
mongorestore --uri='mongodb://user:pass@mongo:27017' --db=mydb /backups/mydb/
List indexes
mongodb
Show all indexes on a collection
mongosh --eval 'db.myCollection.getIndexes()' mongodb://mongo:27017/mydb
Configure mc alias
minio
Register a MinIO server in the mc client
mc alias set myminio https://minio.example.com ACCESSKEY SECRETKEY
Copy file to bucket
minio
Upload a local file to MinIO
mc cp ./file.tar.gz myminio/my-bucket/backups/
Continuously sync a local directory to a bucket
mc mirror --watch ./data myminio/my-bucket/data
Set lifecycle policy
minio
Apply object expiry/transition lifecycle rules to a bucket
mc ilm import myminio/my-bucket < lifecycle.json
Connect to clickhouse-client
clickhouse
Open interactive ClickHouse CLI session
clickhouse-client -h clickhouse -u default --password <pass> --database mydb
Table size
clickhouse
Show disk usage per table in a database
clickhouse-client -q "SELECT table, formatReadableSize(sum(bytes)) AS size FROM system.parts WHERE active AND database='mydb' GROUP BY table ORDER BY sum(bytes) DESC"
Running queries
clickhouse
List all currently running queries with elapsed time
clickhouse-client -q 'SELECT query_id, user, elapsed, query FROM system.processes ORDER BY elapsed DESC'
Kill query
clickhouse
Terminate a long-running or stuck query
clickhouse-client -q "KILL QUERY WHERE query_id='<id>'"
Drop caches
clickhouse
Flush ClickHouse caches to free memory
clickhouse-client -q 'SYSTEM DROP MARK CACHE; SYSTEM DROP UNCOMPRESSED CACHE'
Sync replica
clickhouse
Force replica to sync with ZooKeeper state
clickhouse-client -q 'SYSTEM SYNC REPLICA mydb.myTable'
Repair keyspace
cassandra
Run incremental repair on the primary range (use in maintenance)
nodetool repair -pr <keyspace>
Compaction stats
cassandra
Show ongoing compaction operations and queue length
nodetool compactionstats
Describe table
cassandra
Show CREATE TABLE statement with all settings
cqlsh -e 'DESCRIBE TABLE <keyspace>.<table>'
List queues
rabbitmq
Show queues with message count and consumer count
rabbitmqctl list_queues name messages consumers durable
List exchanges
rabbitmq
Show all exchanges and their types
rabbitmqctl list_exchanges name type durable
List connections
rabbitmq
Show all active AMQP connections
rabbitmqctl list_connections name peer_host port user
Purge a queue
rabbitmq
Delete all messages from a queue without removing it
rabbitmqctl purge_queue <queue>
Enable management plugin
rabbitmq
Enable the HTTP management API and web UI on port 15672
rabbitmq-plugins enable rabbitmq_management
Export definitions
rabbitmq
Export all exchanges, queues, bindings, users, policies
rabbitmqctl export_definitions /tmp/rabbitmq-definitions.json
Squash, reorder, or edit the last 5 commits
git rebase -i HEAD~5
Show recent HEAD movements including rebases and resets
git reflog show --date=relative | head -20
Save uncommitted work (including untracked files) with a label
git stash push -m 'WIP: feature-x' -u
Binary search through history to find a regression
git bisect start && git bisect bad HEAD && git bisect good <good-sha>
Check out a branch in a parallel directory without stashing
git worktree add ../feature-branch feature/my-feature
Submodule update
git
Initialize and update all submodules recursively
git submodule update --init --recursive
Print the content of a file at a historical commit
git show <sha>:path/to/file
Log with graph
git
Compact visual branch graph of the entire repo
git log --oneline --graph --decorate --all | head -40
Find all commits that added or removed the string 'password'
git log -S 'password' --oneline --all
Include staged changes in last commit without changing message
git commit --amend --no-edit
Remove a branch from the remote repository
git push origin --delete feature/old-branch
Update all remotes and delete stale tracking branches
git fetch --all --prune --tags
Select objects where a field equals a value
cat data.json | jq '.items[] | select(.status == "Running")'
Project only specific fields into a new array
cat data.json | jq '[.items[] | {name:.metadata.name, ns:.metadata.namespace}]'
Aggregate items by a field value
cat data.json | jq 'group_by(.namespace) | map({ns: .[0].namespace, count: length})'
Raw output (-r) for scripting; one value per line
cat data.json | jq -r '.items[].metadata.name'
Deep-merge two JSON files (override wins)
jq -s '.[0] * .[1]' base.json override.json
Deep-merge a base YAML with an override file
yq '. *= load("override.yaml")' base.yaml
Split a multi-document YAML into a JSON array
yq -s '.' multi.yaml | yq -o=json
Find large files
linux
Find files larger than 100MB sorted by size
find / -type f -size +100M -exec ls -lh {} \; 2>/dev/null | sort -k5 -rh | head -20
Disk usage per directory
linux
Top 15 largest directories at root level
du -sh /* 2>/dev/null | sort -rh | head -15
Memory usage per process
linux
Top 15 processes by memory consumption
ps aux --sort=-%mem | head -15
Stream logs for a systemd unit from the last 10 minutes
journalctl -u <service> -f --since '10 minutes ago'
Service status, recent log lines, and active timers
systemctl status <service> --no-pager -l
Capture specific traffic to a pcap file
tcpdump -i eth0 -nn host <ip> and port 80 -w /tmp/capture.pcap
Check inode usage
linux
Show inode usage per filesystem; can cause 'no space' without disk full
df -i | sort -k5 -rn
Show all files, sockets, and connections opened by a process
lsof -p <pid>
Watch command output
linux
Re-run a command every 2 seconds with diff highlighting
watch -n 2 'kubectl get pods -n <ns>'
Run a script immune to SIGHUP; redirect output to file
nohup ./script.sh > /tmp/out.log 2>&1 &
Create SSH tunnel
linux
Forward local port 8080 to an internal host via bastion
ssh -L 8080:internal-service:80 user@bastion -N -f
Extract tar.gz
linux
Extract a gzipped tar archive to a specific directory
tar -xzf archive.tar.gz -C /target/dir/
Generate random password
linux
Cryptographically secure random 32-byte password
openssl rand -base64 32
Show cert expiry and subject for a live TLS endpoint
openssl s_client -connect example.com:443 </dev/null 2>/dev/null | openssl x509 -noout -dates -subject
Awk — sum a column
linux
Sum the 3rd column of a space-delimited text file
awk '{sum += $3} END {print sum}' file.txt
Sed — replace in file
linux
In-place global string replacement
sed -i 's/old-string/new-string/g' file.txt
Sort and deduplicate
linux
Count and rank duplicate lines in a file
sort file.txt | uniq -c | sort -rn | head -20
Scan filesystem
trivy
Scan a local directory for vulnerabilities and misconfigs
trivy fs --severity HIGH,CRITICAL .
Scan k8s cluster
trivy
Security audit of the whole cluster: images, configs, RBAC
trivy k8s --report summary cluster
Scan specific namespace
trivy
Scan workloads only in a specific namespace
trivy k8s --namespace production --report summary all
Scan Helm chart
trivy
Check Helm chart templates for security misconfigurations
trivy config ./my-chart
Scan with JSON output
trivy
Machine-readable vulnerability scan results
trivy image --format json -o results.json img:tag
Scan IaC directory
trivy
Find misconfigurations in Terraform/Kubernetes/Helm code
trivy config --severity MEDIUM,HIGH,CRITICAL ./terraform
Ignore unfixed CVEs
trivy
Skip vulnerabilities that have no fix available yet
trivy image --ignore-unfixed --severity HIGH,CRITICAL img:tag
Update vulnerability DB
trivy
Pre-download the latest vulnerability database
trivy image --download-db-only
List routes via Admin API
apisix
List all APISIX routes with URI and upstream
curl -s http://apisix:9180/apisix/admin/routes -H 'X-API-KEY: <key>' | jq '.list[].value | {id:.id, uri:.uri, upstream:.upstream.nodes}'
Get specific route
apisix
Inspect a single APISIX route configuration
curl -s http://apisix:9180/apisix/admin/routes/<id> -H 'X-API-KEY: <key>' | jq .
List upstreams
apisix
All APISIX upstream definitions with nodes
curl -s http://apisix:9180/apisix/admin/upstreams -H 'X-API-KEY: <key>' | jq '.list[].value | {id:.id, nodes:.nodes}'
List plugins
apisix
All available APISIX plugins
curl -s http://apisix:9180/apisix/admin/plugins/list -H 'X-API-KEY: <key>' | jq .
Reload APISIX config
apisix
Hot-reload APISIX configuration from etcd
curl -X PUT http://apisix:9180/apisix/admin/configs/reload -H 'X-API-KEY: <key>'
Check APISIX health
apisix
APISIX process health via control plane API
curl -s http://apisix:9080/apisix/status | jq .
POST JSON payload
curl
Send a JSON POST request with Bearer auth
curl -s -X POST https://api.example.com/v1/resource -H 'Content-Type: application/json' -H 'Authorization: Bearer <token>' -d '{"key":"value"}' | jq .
Show full request/response headers including redirects
curl -sLv https://example.com 2>&1 | grep -E '^[<>*]'
Time a request
curl
Measure DNS, connect, and TTFB timing
curl -so /dev/null -w 'DNS: %{time_namelookup}s\nConnect: %{time_connect}s\nTTFB: %{time_starttransfer}s\nTotal: %{time_total}s\n' https://example.com
Download a file showing a clean progress bar
curl -L --progress-bar -o output.file https://example.com/file.tar.gz
Basic auth request
curl
HTTP request with Basic Authentication
curl -s -u user:password https://api.example.com/endpoint | jq .
Get just the response status code — useful in scripts
curl -so /dev/null -w '%{http_code}' https://example.com
Switch resource view: :pods, :svc, :helmreleases, :ns
# In k9s press ':' then type 'helmreleases' or 'kustomizations'
Type / and a pattern to filter the displayed resources
# In k9s press '/' to filter by name pattern
Show kubectl describe output for highlighted resource
# In k9s press 'd' on selected resource
Delete the selected resource with confirmation
# In k9s press Ctrl+D on selected resource
Switch kubeconfig context
kubectl
Switch the active cluster context
kubectl config use-context <context>
List kubeconfig contexts
kubectl
Show all contexts in current kubeconfig
kubectl config get-contexts
Merge kubeconfigs
kubectl
Combine multiple kubeconfig files into one
KUBECONFIG=~/.kube/config:~/.kube/cluster2.yaml kubectl config view --flatten > ~/.kube/merged.yaml
Avoid typing -n on every command for this context
kubectl config set-context --current --namespace=<ns>
Get node conditions
kubectl
Show all conditions per node (Ready, MemoryPressure, DiskPressure)
kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{": "}{range .status.conditions[*]}{.type}={.status},{" "}{end}{"\n"}{end}'
Trigger CronJob manually
kubectl
Immediately run a CronJob as a one-off Job
kubectl create job --from=cronjob/<name> manual-run -n <ns>
Wait for pod ready
kubectl
Block until matching pods are Ready or timeout
kubectl wait pod -l app=<label> -n <ns> --for=condition=Ready --timeout=120s
List block devices
linux
Tree of disks, partitions, loop devices with filesystem info
lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINT,UUID
Remount the root filesystem as read-write (e.g. after rescue boot)
mount -o remount,rw /
Dry-run fsck check (no changes); unmount first for a live fix
fsck -n /dev/sdb1
Resize ext4 filesystem
linux
Grow ext4 to fill the partition (after partition resize)
resize2fs /dev/sdb1
Show filesystem info
linux
Show ext2/3/4 metadata: block size, mount count, last mount time
tune2fs -l /dev/sda1 | grep -E 'Block (count|size)|Mount count|Last mount'
Disk usage with depth
linux
Disk usage of /var up to 2 directory levels deep
du -h --max-depth=2 /var | sort -rh | head -20
Free disk space summary
linux
Show free space only for real filesystems (skip tmpfs/overlay)
df -hT --type=ext4 --type=xfs --type=btrfs
Create a single GPT partition using the full disk
parted /dev/sdb -- mklabel gpt mkpart primary ext4 1MiB 100%
Extend LV and resize FS
linux
Extend LVM logical volume by 10G and grow ext4 filesystem online
lvextend -L +10G /dev/vg0/lv_data && resize2fs /dev/vg0/lv_data
Create swap file
linux
Allocate 2G swap file, set permissions, format and enable
fallocate -l 2G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile
Show swap usage
linux
List active swap spaces and overall memory/swap stats
swapon --show && free -h
Add static route
linux
Add a persistent-until-reboot static route
ip route add 10.0.0.0/8 via 192.168.1.1 dev eth0
Trace DNS delegation
linux
Follow full DNS resolution chain from root nameservers
dig +trace example.com
All established TCP connections with process info
ss -tnp state established
How many connections are in ESTABLISHED, TIME_WAIT, etc.
ss -tan | awk 'NR>1{print $1}' | sort | uniq -c | sort -rn
Combine traceroute and ping; TCP mode to bypass ICMP blocks
mtr --report --tcp --port 443 example.com
Test MTU path
linux
Send DF-bit ping of 1500-byte frames to detect MTU issues
ping -M do -s 1472 -c 3 8.8.8.8
Show iptables rules
linux
All filter table rules with packet counters and line numbers
iptables -L -n -v --line-numbers
Check network bandwidth
linux
Measure TCP throughput with 4 parallel streams for 10 seconds
iperf3 -c <server_ip> -t 10 -P 4
Real-time bandwidth per connection on an interface
iftop -i eth0 -n
Kernel ring buffer
linux
Last 50 kernel errors/warnings with human-readable timestamps
dmesg -T --level=err,warn | tail -50
Load a kernel module
linux
Load a module with dependencies and verify
modprobe <module> && lsmod | grep <module>
List all kernel parameters; filter by name
sysctl -a | grep vm.swappiness
Apply sysctl parameter
linux
Enable IP forwarding at runtime (also add to /etc/sysctl.d/)
sysctl -w net.ipv4.ip_forward=1
Allocated FDs, free FDs, and system-wide max (file-max)
cat /proc/sys/fs/file-nr
IO wait and throughput
linux
Extended disk IO stats every 2s, 5 iterations; look for %iowait, await
iostat -xz 2 5
System activity report
linux
CPU, memory, and disk stats via sysstat (5 samples, 1s interval)
sar -u -r -d 1 5
Trace network and file syscalls of a running process
strace -f -e trace=network,file -p <pid>
CPU performance counters
linux
Hardware CPU counters during a 5-second window
perf stat -e cycles,instructions,cache-misses -- sleep 5
Show CPU info
linux
CPU model, socket/core/thread topology, and clock speed
lscpu | grep -E 'Model|Socket|Core|Thread|MHz'
Show memory slots (DIMM)
linux
Physical DIMM slots: size, speed, type (requires root)
dmidecode -t memory | grep -E 'Size|Speed|Locator|Type:'
List PCI devices
linux
Network cards, GPUs, NVMe controllers with driver info
lspci -v | grep -A5 'VGA\|Ethernet\|NVMe'
Prevent any user (incl. root) from modifying the file
chattr +i /etc/resolv.conf && lsattr /etc/resolv.conf
List non-default extended attrs in /etc/
lsattr -R /etc/ 2>/dev/null | grep -v '^\-\-\-\-'
ACL: show permissions
linux
Show POSIX ACL entries including owner, group, and extra users
getfacl /srv/shared
ACL: grant user access
linux
Grant alice full access without changing group ownership
setfacl -m u:alice:rwx /srv/shared
Find SUID/SGID binaries
linux
Locate setuid/setgid executables (security audit)
find / -perm /6000 -type f -ls 2>/dev/null
Run a command in a transient systemd scope with resource limits
systemd-run --scope -p MemoryMax=512M -p CPUQuota=50% -- ./heavy.sh
Logs for nginx between two timestamps
journalctl --since '2024-01-15 10:00' --until '2024-01-15 10:30' -u nginx
Export journald to JSON
linux
Structured log export for ingestion into log aggregators
journalctl -u <service> -o json | jq '{ts: .REALTIME_TIMESTAMP, msg: .MESSAGE}'
Show NTP sync status
linux
Clock sync state, offset, and NTP source details
timedatectl status && chronyc tracking
Check systemd timers
linux
All timers with last/next trigger times
systemctl list-timers --all --no-pager
Copy SSH public key
linux
Append public key to remote authorized_keys
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host
Rsync with progress
linux
Mirror directory to remote with deletion of extra files
rsync -avz --progress --delete src/ user@host:/dest/
Securely wipe a disk
linux
One-pass overwrite with zeros + verify (use hdparm ATA for NVMe)
shred -vzn 1 /dev/sdb
Check SMART disk health
linux
SMART overall health and key failure indicators
smartctl -a /dev/sda | grep -E 'SMART overall|Reallocated|Pending|Uncorrectable'
Write 1GB with forced sync to measure raw write speed
dd if=/dev/zero of=/tmp/testfile bs=1M count=1024 conv=fdatasync
List Linux namespaces for network, PID, and mount isolation
lsns -t net,pid,mnt
Inspect cgroup hierarchy
linux
Tree view of systemd cgroup hierarchy and resource assignments
systemd-cgls
Count lines in all logs
linux
Find the biggest log files by line count
find /var/log -name '*.log' -exec wc -l {} + | sort -rn | head -20
Stream multiple log files interleaved in one terminal
tail -f /var/log/syslog /var/log/auth.log
Search compressed logs
linux
grep inside .gz files without manual decompression
zgrep -i 'error' /var/log/syslog.*.gz
Rotate logs manually
linux
Force log rotation regardless of schedule
logrotate -f /etc/logrotate.conf
Print active cron lines for every user
for u in $(cut -f1 -d: /etc/passwd); do crontab -l -u $u 2>/dev/null | grep -v '^#' | sed "s|^|$u: |"; done
Cron expression tester
linux
Parse and show next 5 trigger times for a cron expression
systemd-analyze calendar '*/5 * * * *'
Redirect stderr to file
linux
Split stdout and stderr into separate files
command > /tmp/out.log 2> /tmp/err.log
Capture both streams
linux
Redirect stdout+stderr to file and screen simultaneously
command 2>&1 | tee /tmp/all.log
Find files containing text, then replace in-place
grep -rl 'old_string' /etc/ | xargs sed -i 's/old_string/new_string/g'
Print 1st and 3rd fields of a space-delimited file
awk '{print $1, $3}' /etc/passwd
Sum a column with awk
linux
Sum values in column 2 of a text file
awk '{sum += $2} END {print sum}' file.txt
Remove all comment lines starting with #
sed -i '/^#/d' config.conf
Print block of text between START and END markers
sed -n '/START/,/END/p' file.txt
Failed login attempts
linux
Top source IPs of failed SSH logins in last 24h
journalctl -u ssh --since '24h ago' | grep 'Failed password' | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -10
Add user to group
linux
Append user to multiple groups without removing existing ones
usermod -aG docker,sudo alice
Show /proc memory maps
linux
Total virtual memory size of a process from smaps
cat /proc/<pid>/smaps | awk '/^Size/{sum+=$2} END{print sum/1024" MB"}'
Check if THP / hugepages are used and configured
grep -E 'HugePages|AnonHugePages|Transparent' /proc/meminfo
Disable THP at runtime (fix for Redis, MongoDB latency spikes)
echo never > /sys/kernel/mm/transparent_hugepage/enabled
Increase socket listen backlog for high-connection services
sysctl -w net.core.somaxconn=65535 net.ipv4.tcp_max_syn_backlog=65535
TCP tuning: enable BBR
linux
Enable Google BBR congestion control for better throughput
sysctl -w net.core.default_qdisc=fq net.ipv4.tcp_congestion_control=bbr
Show hardware interrupts
linux
Per-CPU interrupt counts, updated every second
watch -n1 'cat /proc/interrupts | head -30'
Show process limits
linux
Hard and soft resource limits for a running process
cat /proc/<pid>/limits
Set high FD limit for current session and persist it
ulimit -n 1048576 && echo '* soft nofile 1048576
* hard nofile 1048576' >> /etc/security/limits.conf
Rewrite the most recent commit message (local only)
git commit --amend -m 'new message'
Stash only src/ with a descriptive name
git stash push -m 'wip: feature-x' -- src/
List stashes and apply a specific one by index
git stash list && git stash apply stash@{2}
Apply commits from A to B (inclusive) onto current branch
git cherry-pick A^..B
Annotate lines 10–25 with author and date
git blame -L 10,25 --date=short src/main.py
Binary search through history to find the breaking commit
git bisect start && git bisect bad HEAD && git bisect good v1.0
List files added, modified, deleted between two branches
git diff --name-status main..feature/x
ASCII branch graph of the full commit history
git log --oneline --graph --decorate --all
Move HEAD back one commit; staged changes return to working tree
git reset HEAD~1
Reset tracked files and remove untracked files/directories
git restore . && git clean -fd
Remove local refs to remote branches that no longer exist
git fetch --prune
Clone only the latest commit of one branch (fast CI checkout)
git clone --depth=1 --single-branch --branch main <url>
Ranked list of authors by total commit count
git shortlog -sn --all
Find all commits whose message contains a pattern
git log --all --grep='fix:' --oneline
Find when a string was added or removed across all branches
git log -S 'functionName' --patch --all
Download commits and trees; blobs fetched on-demand (fast)
git clone --filter=blob:none <url>
Check out a branch in a separate directory without switching
git worktree add ../hotfix-branch hotfix/urgent
Build with build args
docker
Pass build-time variables to Dockerfile ARG instructions
docker build --build-arg APP_VERSION=1.2.3 --build-arg ENV=prod -t myapp:1.2.3 .
Multi-platform build
docker
Build and push multi-arch image using BuildKit
docker buildx build --platform linux/amd64,linux/arm64 -t myapp:latest --push .
Inspect image layers
docker
Show all layers with full commands and sizes
docker history --no-trunc <image>
Export container filesystem
docker
Inspect a container's merged filesystem as a tar stream
docker export <container> | tar -tvf - | head -30
Diff container from image
docker
Files added (A), changed (C), or deleted (D) in a running container
docker diff <container>
Commit container to image
docker
Snapshot a running container's filesystem as an image
docker commit -m 'debug snapshot' <container> debug-snapshot:$(date +%s)
Run with resource limits
docker
Limit container to 512MB RAM and half a CPU core
docker run --memory=512m --cpus=0.5 --oom-kill-disable=false myapp
One-shot CPU and memory snapshot for all containers
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}'
Remove everything unused
docker
Remove stopped containers, unused images, networks, volumes
docker system prune -a --volumes -f
Copy file from container
docker
Extract a single file from a running or stopped container
docker cp <container>:/app/config.yaml ./local-config.yaml
Docker compose up detached
docker
Rebuild and start services, remove containers not in compose file
docker compose up -d --build --remove-orphans
Scale a compose service
docker
Run 5 replicas of the worker service
docker compose up -d --scale worker=5
Print compose service logs
docker
Stream last 100 lines of a specific compose service
docker compose logs -f --tail=100 worker
Inspect network
docker
Show IPs of all containers in the bridge network
docker network inspect bridge | jq '.[0].Containers | to_entries[] | .value | {Name, IPv4Address}'
Create custom network
docker
Create a bridge network with a custom subnet
docker network create --driver bridge --subnet 172.30.0.0/24 mynet
Save and load image
docker
Export image to archive and reimport on another host
docker save myapp:1.0 | gzip > myapp.tar.gz && docker load < myapp.tar.gz
Healthcheck in Dockerfile
docker
Native Docker healthcheck with curl (add to Dockerfile)
HEALTHCHECK --interval=10s --timeout=3s --retries=3 CMD curl -sf http://localhost:8080/health || exit 1
Docker scout vulnerabilities
docker
Show only CVEs that already have a fix available
docker scout cves --only-fixed myapp:latest
Full-featured network debug container sharing host PID and network
docker run --rm -it --pid=host --network=host --privileged nicolaka/netshoot
POST JSON body
curl
Send JSON payload via POST
curl -X POST https://api.example.com/v1/items -H 'Content-Type: application/json' -d '{"name":"foo"}'
Bearer token auth
curl
Attach JWT/Bearer token in Authorization header
curl -H 'Authorization: Bearer $TOKEN' https://api.example.com/me
Follow up to 5 redirects and show full request/response
curl -Lv --max-redirs 5 https://example.com
Download silently, fail on error, follow redirects
curl -sSL -o /tmp/result.json https://api.example.com/data
Benchmark TTFB and total request time
curl -o /dev/null -sS -w 'ttfb: %{time_starttransfer}s\ntotal: %{time_total}s\n' https://example.com
Print HTTP response headers without body
curl -sI https://example.com
Multipart form-data upload with extra fields
curl -F 'file=@./report.pdf' -F 'user=alice' https://upload.example.com/api
HTTP/2 request
curl
Force HTTP/2 and check protocol in response
curl --http2 -sI https://example.com | grep -i 'http\|alt-svc'
Override DNS for a host:port pair (test behind CDN/LB)
curl --resolve example.com:443:1.2.3.4 https://example.com
Retry on failure
curl
Retry up to 5 times with 2s delay on any error
curl --retry 5 --retry-delay 2 --retry-all-errors https://api.example.com/healthz
POST form data
curl
Send URL-encoded form data
curl -d 'user=alice&pass=secret' -X POST https://auth.example.com/login
mTLS request with client cert and custom CA
curl --cert client.crt --key client.key --cacert ca.crt https://secure.example.com
Download 5 URLs in parallel and print status codes
cat urls.txt | xargs -P 5 -I{} curl -sSL -o /dev/null -w '%{url_effective} %{http_code}\n' {}
Verify WebSocket upgrade handshake responds with 101
curl -i -N -H 'Upgrade: websocket' -H 'Connection: Upgrade' -H 'Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==' -H 'Sec-WebSocket-Version: 13' http://localhost:8080/ws
Limit download bandwidth to 1 MB/s
curl --limit-rate 1M -O https://example.com/bigfile.iso
Stream every command sent to Redis (exclude health pings)
redis-cli MONITOR | grep -v PING
Show slow query log
redis
Last 20 slow commands with execution time in microseconds
redis-cli SLOWLOG GET 20
Total memory consumed by keys matching a pattern
redis-cli --scan --pattern 'session:*' | xargs -n1 redis-cli MEMORY USAGE | awk '{sum+=$1} END{print sum/1024/1024" MB"}'
Delete keys by pattern
redis
Safely scan-delete matching keys without KEYS command
redis-cli --scan --pattern 'cache:*' | xargs -r redis-cli DEL
Set key with TTL
redis
Set key with 1-hour expiry (EX = seconds)
redis-cli SET mykey 'value' EX 3600
Pub/Sub publish
redis
Publish a message to a Redis pub/sub channel
redis-cli PUBLISH events '{"type":"login","user":"alice"}'
Trigger background RDB save and check its timestamp
redis-cli BGSAVE && redis-cli LASTSAVE
Sorted set top-N
redis
Top 10 entries from a sorted set with scores
redis-cli ZREVRANGEBYSCORE leaderboard +inf -inf WITHSCORES LIMIT 0 10
Stream add message
redis
Append a message to a Redis Stream with auto-ID
redis-cli XADD mystream '*' event login user alice
Cluster info
redis
Cluster health and node list with slot ranges
redis-cli -c CLUSTER INFO && redis-cli -c CLUSTER NODES
Benchmark throughput
redis
100k requests, 50 clients, 10 pipeline depth (quiet output)
redis-benchmark -q -n 100000 -c 50 -P 10
Ad-hoc ping all hosts
ansible
Check SSH connectivity and Python for all hosts
ansible all -m ping -i inventory.ini
Run shell command on group
ansible
Run a shell command on all hosts in the webservers group
ansible webservers -m shell -a 'uptime && free -h' -i inventory.ini
Gather facts for a host
ansible
Collect and filter Ansible facts for a single host
ansible <host> -m setup -i inventory.ini | jq '.ansible_facts | {os: .ansible_distribution, mem: .ansible_memtotal_mb}'
Check mode (dry run)
ansible
Show what would change without making any modifications
ansible-playbook site.yml --check --diff -i inventory.ini
Run with extra variables
ansible
Override variables from the command line
ansible-playbook deploy.yml -e 'env=prod version=2.1.0' -i inventory.ini
Limit to specific hosts
ansible
Run playbook only on specified hosts
ansible-playbook site.yml --limit 'web-01,web-02' -i inventory.ini
Run specific tags
ansible
Execute only tasks marked with specified tags
ansible-playbook site.yml --tags 'config,restart' -i inventory.ini
Skip specific tags
ansible
Skip tasks with specified tags
ansible-playbook site.yml --skip-tags 'slow,optional' -i inventory.ini
Increase verbosity
ansible
Maximum verbosity for debugging; save to log
ansible-playbook site.yml -vvv -i inventory.ini 2>&1 | tee /tmp/ansible.log
Encrypt a variable with Vault
ansible
Inline-encrypt a value for use in playbook vars
ansible-vault encrypt_string 'supersecret' --name 'db_password'
Decrypt vault file
ansible
Display decrypted content of a vault-encrypted file
ansible-vault view group_vars/all/vault.yml
Copy file to remote
ansible
Push a local file to all hosts with specific permissions
ansible all -m copy -a 'src=./nginx.conf dest=/etc/nginx/nginx.conf owner=root mode=0644' -i inventory.ini
Restart service on all hosts
ansible
Ad-hoc service restart with privilege escalation (-b)
ansible webservers -m service -a 'name=nginx state=restarted' -b -i inventory.ini
Show inventory graph
ansible
Display inventory group hierarchy as a tree
ansible-inventory -i inventory.ini --graph
Test role locally with Molecule
ansible
Run full Molecule test suite: create, converge, verify, destroy
molecule test -s default
Show computed values
helm
Display all values (user + chart defaults) for a release
helm get values <release> -n <ns> --all
Render and validate manifests without installing
helm template myrelease ./mychart -f values-prod.yaml | kubectl apply --dry-run=client -f -
Show YAML diff between current and new release (requires helm-diff plugin)
helm diff upgrade <release> ./mychart -f values.yaml -n <ns>
Roll back automatically if upgrade does not succeed in 5m
helm upgrade <release> ./mychart -n <ns> -f values.yaml --atomic --timeout 5m
Override specific chart values from command line
helm upgrade <release> ./mychart --set image.tag=v1.5.0 --set replicaCount=3
Print the Kubernetes YAML applied by the current release
helm get manifest <release> -n <ns>
Show history and roll back to previous revision (0 = latest-1)
helm history <release> -n <ns> && helm rollback <release> 0 -n <ns>
List all available versions of a chart in configured repos
helm search repo <chart> --versions | head -20
Print default values.yaml for a chart version
helm show values <repo>/<chart> --version <ver>
Package chart
helm
Create a versioned .tgz chart archive
helm package ./mychart --destination ./dist
Upload chart package to an OCI-compliant container registry
helm push mychart-1.0.0.tgz oci://registry.example.com/charts
Install from OCI
helm
Install a chart directly from an OCI registry
helm install myrelease oci://registry.example.com/charts/mychart --version 1.0.0
Lint chart
helm
Validate chart structure and templates with strict mode
helm lint ./mychart -f values-prod.yaml --strict
Force replace resources that can't be patched (delete+create)
helm upgrade <release> ./mychart -n <ns> --force
Install plugins
helm
Install helm-diff plugin for release comparison
helm plugin install https://github.com/databus23/helm-diff
Format all files
terraform
Recursively format all .tf files in subdirectories
terraform fmt -recursive
Validate configuration
terraform
Check configuration syntax without accessing remote state
terraform validate
Plan with var file
terraform
Generate plan with prod variables, save to file
terraform plan -var-file=prod.tfvars -out=prod.tfplan
Apply saved plan
terraform
Apply exactly the plan generated earlier (no re-prompts)
terraform apply prod.tfplan
Show resource in state
terraform
Display all attributes of a specific resource in state
terraform state show 'aws_instance.web[0]'
Move resource in state
terraform
Rename or move a resource without destroying it
terraform state mv 'aws_instance.web' 'module.app.aws_instance.web'
Import existing resource
terraform
Bring an existing resource under Terraform management
terraform import 'aws_s3_bucket.mybucket' my-existing-bucket
Taint resource for recreation
terraform
Mark resource to be destroyed and recreated on next apply
terraform taint 'aws_instance.web[0]'
Remove resource from state
terraform
Remove a resource from state without destroying it in the cloud
terraform state rm 'aws_instance.legacy'
Show outputs
terraform
Print all outputs as compact JSON
terraform output -json | jq 'to_entries[] | {(.key): .value.value}'
Destroy specific resource
terraform
Destroy a single resource without full plan
terraform destroy -target='aws_instance.web' -auto-approve
Unlock stuck state
terraform
Release a stuck state lock after a failed apply
terraform force-unlock <lock-id>
Workspace create and switch
terraform
Create and activate a Terraform workspace
terraform workspace new staging && terraform workspace select staging
Show dependency graph
terraform
Render resource dependency graph as SVG (requires graphviz)
terraform graph | dot -Tsvg > graph.svg && open graph.svg
List providers with versions
terraform
Lock provider versions for multiple platforms in .terraform.lock.hcl
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64
Filter array elements where value is not null
jq '[.[] | select(.value != null)]' data.json
Count records grouped by status field
jq 'group_by(.status) | map({status: .[0].status, count: length})' data.json
Build an object keyed by the id field
jq 'INDEX(.[]; .id)' items.json
Deep merge two JSON objects (right wins on conflicts)
jq -s '.[0] * .[1]' base.json override.json
Optional chaining with fallback default value
jq '.config?.database?.host // "localhost"' config.json
Get 5 most recent events sorted by timestamp descending
jq 'sort_by(.timestamp) | reverse | .[0:5]' events.json
Output selected fields as comma-separated values
jq -r '.[] | [.id, .name, .status] | @csv' data.json
Inject a new key-value pair into every array element
jq '[.[] | . + {"env": "prod"}]' items.json
Recursively lowercase all string values in a JSON document
jq 'walk(if type == "string" then ascii_downcase else . end)' data.json
Query instant vector
prometheus
Run an instant PromQL query via HTTP API
curl -sG 'http://prometheus:9090/api/v1/query' --data-urlencode 'query=up' | jq '.data.result'
Range query for graph data
prometheus
Fetch time-series data over a range for a rate metric
curl -sG 'http://prometheus:9090/api/v1/query_range' --data-urlencode 'query=rate(http_requests_total[5m])' --data-urlencode 'start=1h' --data-urlencode 'end=now' --data-urlencode 'step=60'
Top N series by value
prometheus
PromQL: top 10 pods by CPU usage rate
topk(10, sum by (pod) (rate(container_cpu_usage_seconds_total[5m])))
Disk usage alert rule
prometheus
PromQL expression: fire when root disk > 85% used
100 - (node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"} * 100) > 85
Reload Prometheus config
prometheus
Hot reload Prometheus config and rules without restart
curl -X POST http://prometheus:9090/-/reload
List active alerts
prometheus
Show only firing alerts with name and severity
curl -s http://prometheus:9090/api/v1/alerts | jq '.data.alerts[] | select(.state=="firing") | {name: .labels.alertname, severity: .labels.severity}'
List all metric names
prometheus
Count total metric names and preview first 20
curl -s http://prometheus:9090/api/v1/label/__name__/values | jq '.data | length, .[0:20]'
Series cardinality per job
prometheus
PromQL: count active time series grouped by job label
count by (job) ({__name__=~".+"})
Silence an alert
prometheus
Create an Alertmanager silence for 2 hours
amtool silence add alertname=HighMemory --duration=2h --comment='Investigating'
Check TSDB status
prometheus
View TSDB head stats: chunks and active series
curl -s http://prometheus:9090/api/v1/status/tsdb | jq '{head_chunks: .data.headStats.numChunks, series: .data.headStats.numSeries}'
Connect to database
postgres
Interactive psql session to a database
psql -h localhost -U myuser -d mydb
List tables in schema
postgres
List all tables in the public schema
psql -U myuser -d mydb -c '\dt public.*'
EXPLAIN ANALYZE a query
postgres
Show query plan with actual timings and buffer usage
psql -U myuser -d mydb -c 'EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) SELECT * FROM orders WHERE status = $1;'
Top 10 slowest queries by total execution time
psql -U postgres -d mydb -c "SELECT round(total_exec_time::numeric,2) ms, calls, round((total_exec_time/calls)::numeric,2) avg_ms, query FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;"
Show active queries
postgres
Running queries with duration and truncated SQL
psql -U postgres -c "SELECT pid, now()-query_start AS duration, state, left(query,80) FROM pg_stat_activity WHERE state <> 'idle' ORDER BY duration DESC;"
Kill long-running query
postgres
Terminate all queries running longer than 5 minutes
psql -U postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE now()-query_start > interval '5 min' AND state = 'active';"
Show table sizes
postgres
Top 20 tables by total size including indexes and TOAST
psql -U myuser -d mydb -c "SELECT schemaname, tablename, pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) size FROM pg_tables ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC LIMIT 20;"
Show index usage
postgres
Which indexes are actually being used and how often
psql -U myuser -d mydb -c "SELECT relname, indexrelname, idx_scan, idx_tup_read FROM pg_stat_user_indexes ORDER BY idx_scan DESC LIMIT 20;"
Find unused indexes
postgres
Indexes that have never been scanned — safe to drop candidates
psql -U myuser -d mydb -c "SELECT schemaname, tablename, indexname, idx_scan FROM pg_stat_user_indexes WHERE idx_scan = 0 AND NOT indisprimary ORDER BY pg_relation_size(indexrelid) DESC;"
Dump database
postgres
Custom-format dump (fastest, supports parallel restore)
pg_dump -U myuser -d mydb -F c -f mydb.dump
Restore database
postgres
Parallel restore with 4 workers, drop existing objects first
pg_restore -U myuser -d mydb -j 4 --clean mydb.dump
Vacuum and analyze table
postgres
Reclaim dead tuples and update statistics for query planner
psql -U myuser -d mydb -c 'VACUUM (VERBOSE, ANALYZE) orders;'
Check replication lag
postgres
Replication state and byte lag per replica
psql -U postgres -c "SELECT client_addr, state, sent_lsn, replay_lsn, (sent_lsn - replay_lsn) AS lag_bytes FROM pg_stat_replication;"
Show locks
postgres
Active locks with blocking/blocked status and query
psql -U postgres -d mydb -c "SELECT pid, relation::regclass, mode, granted, left(query,60) FROM pg_locks l JOIN pg_stat_activity a USING(pid) WHERE relation IS NOT NULL ORDER BY granted;"
Show compiled modules
nginx
List all built-in and dynamic modules in the binary
nginx -V 2>&1 | tr ' ' '\n' | grep module
Stream IP, path, status code, and response size
tail -f /var/log/nginx/access.log | awk '{print $1, $7, $9, $10}'
Frequency of each HTTP status code in access log
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
Top 10 requested URLs
nginx
Most popular request paths from access log
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10
Top IPs by request count
nginx
Top 10 client IPs hitting the server
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10
Limit to 10 req/s per IP with burst of 20 (add to http/server block)
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req zone=api burst=20 nodelay;
Round-robin upstream with backup and keepalive connections
upstream backend {
server 10.0.0.1:8080;
server 10.0.0.2:8080 backup;
keepalive 32;
}
Enable gzip compression
nginx
Compress text responses ≥1KB at level 6
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1024;
gzip_comp_level 6;
Custom JSON body for rate-limit or error responses
error_page 429 /429.json;
location = /429.json {
default_type application/json;
return 429 '{"error":"rate_limited"}';
}
Force HTTPS redirect
nginx
Permanent redirect all HTTP traffic to HTTPS
server {
listen 80;
return 301 https://$host$request_uri;
}
Show active connections
nginx
Built-in nginx status page: active, reading, writing, waiting
curl -s http://localhost/stub_status
Block IP range
nginx
Block a subnet and specific IP in nginx location/server block
deny 192.168.1.0/24;
deny 10.0.0.1;
allow all;
Proxy WebSocket
nginx
WebSocket proxy with required Upgrade headers
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
}
Generate RSA private key
openssl
Generate a 4096-bit RSA private key
openssl genrsa -out private.key 4096
Generate Ed25519 key pair
openssl
Modern Ed25519 key (smaller, faster than RSA)
openssl genpkey -algorithm ed25519 -out private.key && openssl pkey -in private.key -pubout -out public.key
Create CSR
openssl
Certificate Signing Request for CA submission
openssl req -new -key private.key -out request.csr -subj '/CN=example.com/O=MyOrg/C=RU'
Self-signed certificate
openssl
Generate self-signed cert + key in one command
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes -subj '/CN=localhost'
View certificate details
openssl
Show subject, issuer, validity dates, SANs
openssl x509 -in cert.pem -noout -text | grep -E 'Subject:|Issuer:|Not (Before|After)|DNS:'
Check cert expiry
openssl
Print notBefore and notAfter dates
openssl x509 -in cert.pem -noout -dates
Verify cert against CA
openssl
Check certificate chain against a CA bundle
openssl verify -CAfile ca.pem cert.pem
Check cert matches key
openssl
Confirm the cert and private key are a pair
diff <(openssl x509 -pubkey -noout -in cert.pem) <(openssl pkey -pubout -in key.pem) && echo 'MATCH'
Convert PEM to PKCS#12
openssl
Package cert + key + CA into a .p12 file
openssl pkcs12 -export -in cert.pem -inkey key.pem -certfile ca.pem -out bundle.p12 -name myalias
Extract cert from PKCS#12
openssl
Split .p12 into separate cert and key PEM files
openssl pkcs12 -in bundle.p12 -nokeys -out cert.pem && openssl pkcs12 -in bundle.p12 -nocerts -nodes -out key.pem
Check live TLS cert
openssl
Show expiry and issuer of a live TLS certificate
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -dates -subject -issuer
Check full cert chain
openssl
Display full chain: leaf → intermediate → root
openssl s_client -connect example.com:443 -showcerts 2>/dev/null | openssl crl2pkcs7 -nocrl | openssl pkcs7 -print_certs -noout -text | grep -E 'Subject:|Issuer:'
Encrypt file with AES-256
openssl
Password-encrypt a file with AES-256-CBC + PBKDF2
openssl enc -aes-256-cbc -pbkdf2 -in secret.txt -out secret.enc
Decrypt AES-256 file
openssl
Decrypt a file encrypted with the enc command above
openssl enc -d -aes-256-cbc -pbkdf2 -in secret.enc -out secret.txt
Generate random hex token
openssl
Generate a 64-char hex random string (e.g. for API keys)
openssl rand -hex 32
Synchronize panes
tmux
Send keystrokes to all panes simultaneously (multi-server ops)
tmux setw synchronize-panes on
Run a command in every pane of the current session
tmux list-panes -s -F '#{session_name}:#{window_index}.#{pane_index}' | xargs -I{} tmux send-keys -t {} 'uptime' Enter
Search all files under /var/log for 'error' (any case)
grep -ri 'error' /var/log/
Show context lines
grep
Print 3 lines before and 5 lines after each match
grep -B3 -A5 'FATAL' app.log
Count matches
grep
Print only the number of matching lines
grep -c 'POST /api' /var/log/nginx/access.log
Extract IP addresses from log using Perl regex
grep -oP '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' access.log | sort -u
Invert match
grep
Remove comment and blank lines from a config file
grep -v '^#' /etc/nginx/nginx.conf | grep -v '^\s*$'
Limit recursive search to .py files only
grep -r --include='*.py' 'import os' /srv/app/
Exclude directories
grep
Search recursively skipping vcs and dependency dirs
grep -r --exclude-dir='.git' --exclude-dir='node_modules' 'TODO' .
Show file and line number for each match
grep -rn 'panic:' /var/log/app/
ripgrep fast search
grep
List files containing TODO/FIXME/HACK in Python files
rg 'TODO|FIXME|HACK' --type py -l
ripgrep with context
grep
3 lines of context around matches in Go files
rg 'panic' -C3 --glob '*.go'
Search hidden and .gitignore'd files
rg 'secret_key' --hidden --no-ignore
Preview how a replacement would look without writing
rg 'old_value' --replace 'new_value' --passthru config.yaml
ripgrep stats
grep
Show total matches, files searched, elapsed time
rg 'error' /var/log/ --stats 2>&1 | tail -5
Search binary files
grep
Treat binary as text (-a) to search process memory
grep -a 'password' /proc/<pid>/mem 2>/dev/null | strings | head -20
Match lines containing ERROR, WARN, or CRIT
grep -E '(ERROR|WARN|CRIT)' app.log | tail -50
Enable and start service
systemd
Enable at boot and start immediately in one command
systemctl enable --now myapp.service
Show failed units
systemd
List all units that are in a failed state
systemctl list-units --state=failed
Reload unit file after edit
systemd
Reload unit definitions and restart the service
systemctl daemon-reload && systemctl restart myapp.service
Override unit with drop-in
systemd
Create /etc/systemd/system/myapp.service.d/override.conf with partial overrides
systemctl edit myapp.service
Show unit file content
systemd
Print the full unit file including drop-ins
systemctl cat myapp.service
Draw boot dependency graph
systemd
Render full boot dependency graph as SVG
systemd-analyze dot --require | dot -Tsvg > boot.svg && open boot.svg
Create a simple service unit
systemd
Minimal systemd service unit template
cat > /etc/systemd/system/myapp.service <<EOF
[Unit]
Description=My App
After=network.target
[Service]
ExecStart=/usr/bin/myapp
Restart=always
RestartSec=5
User=appuser
[Install]
WantedBy=multi-user.target
EOF
Run one-shot as another user
systemd
Run a transient one-shot unit under a specific user
systemd-run --uid=1000 --gid=1000 --wait /usr/bin/myapp --task
Create systemd timer
systemd
Replacement for cron with Persistent=true for missed runs
cat > /etc/systemd/system/backup.timer <<EOF
[Unit]
Description=Daily backup
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
EOF
Set memory limit on service
systemd
Apply cgroup limits without editing unit file
systemctl set-property myapp.service MemoryMax=512M CPUQuota=50%
Show service resource usage
systemd
Current memory, CPU, and task counts from cgroup
systemctl status myapp.service | grep -E 'Memory:|CPU:|Tasks:'
List all socket units
systemd
All socket-activated units and their state
systemctl list-units --type=socket --all
Mask a service
systemd
Prevent a service from being started by anything
systemctl mask snapd.service
Show environment of service
systemd
Print environment variables injected into the service
systemctl show myapp.service -p Environment
Create virtual environment
python
Create and activate an isolated Python environment
python3 -m venv .venv && source .venv/bin/activate
Install from requirements
python
Install dependencies without using pip cache
pip install -r requirements.txt --no-cache-dir
Freeze installed packages
python
Save exact versions of all installed packages
pip freeze > requirements.txt
Show outdated packages
python
List packages with newer versions available
pip list --outdated --format=columns
Run module as script
python
Serve current directory over HTTP on port 8080
python3 -m http.server 8080
One-liner JSON pretty print
python
Pretty-print a JSON file using stdlib
python3 -m json.tool < input.json
Profile script
python
CPU profiling sorted by cumulative time
python3 -m cProfile -s cumulative script.py | head -30
Set breakpoint in code
python
Built-in breakpoint() is equivalent to import pdb; pdb.set_trace()
breakpoint() # Python 3.7+ — drops into pdb at this line
Run tests with pytest
python
Stop at first failure, verbose, short traceback
pytest -x -v --tb=short tests/
Check syntax without running
python
Compile to bytecode only to catch syntax errors
python3 -m py_compile script.py && echo OK
Format code with black
python
Preview changes then apply Black formatting
black --check --diff . && black .
Type check with mypy
python
Strict static type checking for a package
mypy --strict --ignore-missing-imports src/
Inspect object attributes
python
List public attributes of any Python object
python3 -c "import json; print([x for x in dir(json) if not x.startswith('_')])"
Specify an identity file explicitly
ssh -i ~/.ssh/id_ed25519 user@host
Single-hop jump through bastion host
ssh -J bastion.example.com user@internal-host
Chain multiple jump hosts in one command
ssh -J user@bastion1,user@bastion2 user@target
Forward localhost:5432 to db.internal:5432 via bastion
ssh -L 5432:db.internal:5432 user@bastion -N
Expose local port 3000 as port 8080 on VPS
ssh -R 8080:localhost:3000 user@vps -N
Create a local SOCKS5 proxy tunnelled through VPS
ssh -D 1080 user@vps -N -f
Reuse existing connection for subsequent SSH commands
ssh -o ControlMaster=auto -o ControlPath=~/.ssh/mux-%r@%h:%p -o ControlPersist=10m user@host
Execute a command over SSH without interactive shell
ssh user@host 'sudo systemctl status nginx'
Recursive copy on non-standard port
scp -r -P 2222 ./dist/ user@host:/var/www/app/
Agent forwarding
ssh
Forward local SSH agent to the remote host (use with caution)
ssh -A user@bastion
Add key to agent
ssh
Start agent and load a key for the session
eval $(ssh-agent) && ssh-add ~/.ssh/id_ed25519
Shorthand alias: 'ssh dev' triggers all options
cat >> ~/.ssh/config <<'EOF'
Host dev
HostName 10.0.0.5
User ubuntu
IdentityFile ~/.ssh/dev_key
ProxyJump bastion
EOF
Fetch and fingerprint server host keys without connecting
ssh-keyscan -t ed25519,rsa host 2>/dev/null | ssh-keygen -lf -
Force-command and restrict source IP in authorized_keys
echo 'from="10.0.0.0/8",no-agent-forwarding,no-port-forwarding,command="/usr/bin/backup.sh" <pubkey>' >> ~/.ssh/authorized_keys
KQL: filter by field value
kibana
Kibana Query Language — filter logs by field values
status: 404 AND method: GET
KQL: range query
kibana
Filter events in the last hour with slow responses
response_time > 500 AND @timestamp > now-1h
KQL: nested field filter
kibana
Filter by nested Kubernetes metadata fields
kubernetes.pod.name: web-* AND kubernetes.namespace: prod
Create index pattern via API
kibana
Register a new index pattern via Kibana REST API
curl -X POST http://kibana:5601/api/saved_objects/index-pattern -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d '{"attributes":{"title":"logs-*","timeFieldName":"@timestamp"}}'
Export saved objects
kibana
Export dashboards and visualizations to NDJSON
curl -X POST http://kibana:5601/api/saved_objects/_export -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d '{"type":["dashboard","visualization"],"includeReferencesDeep":true}' -o export.ndjson
Import saved objects
kibana
Import dashboards/visualizations from NDJSON
curl -X POST http://kibana:5601/api/saved_objects/_import?overwrite=true -H 'kbn-xsrf: true' -F file=@export.ndjson
Check Kibana health
kibana
Overall health status and Kibana version
curl -s http://kibana:5601/api/status | jq '{status: .status.overall.level, version: .version.number}'
List all index patterns
kibana
Show all registered index patterns
curl -s http://kibana:5601/api/saved_objects/_find?type=index-pattern | jq '.saved_objects[].attributes.title'
Dev Tools console query
kibana
Run Elasticsearch queries directly in Kibana Dev Tools
GET logs-*/_search
{
"query": {"match": {"level": "error"}},
"size": 10
}
Flush Kibana cache
kibana
Reset Kibana config object (triggers re-init on reload)
curl -X DELETE http://kibana:5601/api/saved_objects/config/7.17.0 -H 'kbn-xsrf: true'
Get space info
kibana
List all Kibana Spaces by ID
curl -s http://kibana:5601/api/spaces/space | jq '.[].id'
Copy objects between spaces
kibana
Copy a dashboard to another Kibana Space
curl -X POST http://kibana:5601/api/spaces/_copy_saved_objects -H 'kbn-xsrf: true' -H 'Content-Type: application/json' -d '{"spaces":["staging"],"objects":[{"type":"dashboard","id":"my-dash"}],"overwrite":true}'
Seal a secret from file
sealed-secrets
Encrypt a Kubernetes Secret YAML into a SealedSecret
kubeseal --format=yaml < secret.yaml > sealed-secret.yaml
Seal from stdin with scope
sealed-secrets
Create and seal a secret in cluster-wide scope
kubectl create secret generic mysecret --dry-run=client --from-literal=token=abc123 -o yaml | kubeseal --scope cluster-wide -o yaml
Fetch public certificate
sealed-secrets
Save the sealing certificate for offline encryption
kubeseal --fetch-cert --controller-name=sealed-secrets --controller-namespace=kube-system > pub.pem
Seal offline with cert
sealed-secrets
Encrypt without cluster access using saved cert
kubeseal --cert pub.pem --format yaml < secret.yaml > sealed.yaml
Check sealed-secrets controller logs
sealed-secrets
Stream controller logs to debug sealing issues
kubectl logs -n kube-system -l app.kubernetes.io/name=sealed-secrets -f
List all SealedSecrets
sealed-secrets
Show all SealedSecrets across namespaces
kubectl get sealedsecrets -A
Re-seal with new key
sealed-secrets
Fetch decrypted secret and re-encrypt with current key
kubectl get secret mysecret -o yaml | kubeseal --format yaml > sealed-new.yaml
Check SecretStore status
external-secrets
Show all SecretStores and their sync status
kubectl get secretstore,clustersecretstore -A -o wide
Force ExternalSecret refresh
external-secrets
Trigger immediate re-sync by updating annotation
kubectl annotate externalsecret mysecret force-sync=$(date +%s) --overwrite
Check ExternalSecret sync status
external-secrets
View sync conditions: Ready, SecretSynced
kubectl get externalsecret mysecret -o jsonpath='{.status.conditions[*]}'
ExternalSecret with templating
external-secrets
Inspect value templating in ExternalSecret spec
kubectl get externalsecret mysecret -o yaml | grep -A10 'template:'
List all ExternalSecrets
external-secrets
Compact table of all ExternalSecrets with sync state
kubectl get externalsecrets -A -o custom-columns='NS:.metadata.namespace,NAME:.metadata.name,STORE:.spec.secretStoreRef.name,READY:.status.conditions[0].status'
Modify YAML file in-place with yq v4
yq -i '.spec.replicas = 3' deployment.yaml
Append an env var to the first container
yq -i '.spec.containers[0].env += {"name":"DEBUG","value":"true"}' deployment.yaml
Delete a key
yq
Remove a specific annotation from YAML
yq -i 'del(.metadata.annotations."kubectl.kubernetes.io/last-applied-configuration")' resource.yaml
Deep-merge two YAML documents
yq eval-all 'select(fileIndex==0) * select(fileIndex==1)' base.yaml override.yaml
Select only Running pods from a list
yq '.items[] | select(.status.phase == "Running")' pods.yaml
Targeted image update for a named container
yq -i '(.spec.template.spec.containers[] | select(.name == "app") | .image) = "myapp:v2.0.0"' deployment.yaml
Extract metadata.name from all YAML files in a directory
yq '.metadata.name' manifests/*.yaml
Apply across all modules
terragrunt
Apply all modules in the stack in dependency order
terragrunt run-all apply
Destroy all modules
terragrunt
Destroy all stack modules non-interactively
terragrunt run-all destroy --terragrunt-non-interactive
Validate all configs
terragrunt
Run terraform validate across all modules
terragrunt run-all validate
Output remote state values
terragrunt
Show all Terragrunt outputs as JSON
terragrunt output -json | jq '.'
Render final config
terragrunt
Dump the resolved terragrunt.hcl as JSON (debug)
terragrunt render-json
Graph module dependencies
terragrunt
Visualise Terragrunt module dependency graph
terragrunt graph-dependencies | dot -Tsvg > deps.svg
Exclude a module from run-all
terragrunt
Skip a specific module during stack-wide operations
terragrunt run-all plan --terragrunt-exclude-dir ./module-to-skip
Auto-retry on lock errors
terragrunt
Fetch dependency outputs from state to avoid ordering issues
terragrunt apply --terragrunt-no-auto-approve --terragrunt-fetch-dependency-output-from-state
Debug pod with ephemeral container
k8s-debug
Attach an ephemeral debug container to a running pod
kubectl debug -it mypod --image=busybox --target=app
Run debug pod on node
k8s-debug
Get privileged shell on a cluster node via debug pod
kubectl debug node/my-node -it --image=ubuntu
Exec into sidecar container
k8s-debug
Open shell in a specific container of a multi-container pod
kubectl exec -it mypod -c sidecar-name -- /bin/sh
Check resource requests/limits
k8s-debug
Show resource requests and limits for each container
kubectl get pod mypod -o jsonpath='{range .spec.containers[*]}{.name}{"\t"}{.resources}{"\n"}{end}'
Describe node conditions
k8s-debug
Check node conditions: Ready, MemoryPressure, DiskPressure
kubectl describe node my-node | grep -A5 'Conditions:'
Find pods by resource usage
k8s-debug
Top 20 pods sorted by memory consumption
kubectl top pods -A --sort-by=memory | head -20
Watch pod events
k8s-debug
Stream events for a specific pod
kubectl get events -n mynamespace --field-selector involvedObject.name=mypod --watch
Copy file from pod
k8s-debug
Download a file from a running container
kubectl cp mynamespace/mypod:/var/log/app.log ./app.log
Create a topic
kafka
Create a new Kafka topic with 6 partitions and RF=3
kafka-topics.sh --bootstrap-server kafka:9092 --create --topic my-topic --partitions 6 --replication-factor 3
List consumer group lag
kafka
Show per-partition lag for a consumer group
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --describe --group my-group
Reset consumer offsets to earliest
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --group my-group --reset-offsets --to-earliest --topic my-topic --execute
Produce key:value messages interactively
kafka-console-producer.sh --bootstrap-server kafka:9092 --topic my-topic --property 'key.separator=:' --property 'parse.key=true'
Consume from beginning
kafka
Read first 10 messages from a topic
kafka-console-consumer.sh --bootstrap-server kafka:9092 --topic my-topic --from-beginning --max-messages 10
Alter topic partitions
kafka
Increase partition count (cannot decrease)
kafka-topics.sh --bootstrap-server kafka:9092 --alter --topic my-topic --partitions 12
Describe topic config
kafka
Show all overridden config values for a topic
kafka-configs.sh --bootstrap-server kafka:9092 --describe --entity-type topics --entity-name my-topic
Set topic retention
kafka
Set 7-day retention on a topic
kafka-configs.sh --bootstrap-server kafka:9092 --alter --entity-type topics --entity-name my-topic --add-config retention.ms=604800000
Check broker metadata
kafka
List all API versions supported by the broker
kafka-broker-api-versions.sh --bootstrap-server kafka:9092
List queues with message counts
rabbitmq
Show queue names, message depth and consumer count
rabbitmqctl list_queues name messages consumers
Check cluster status
rabbitmq
Show cluster nodes, disk nodes and partitions
rabbitmqctl cluster_status
Purge a queue
rabbitmq
Remove all messages from a queue without deleting it
rabbitmqctl purge_queue my_queue -p my_vhost
List exchanges
rabbitmq
Show all exchanges with type and durability
rabbitmqctl list_exchanges name type durable
List bindings
rabbitmq
Show exchange-to-queue bindings for a vhost
rabbitmqctl list_bindings -p my_vhost
Enable management plugin
rabbitmq
Enable web UI on port 15672
rabbitmq-plugins enable rabbitmq_management && rabbitmqctl restart
Export definitions (backup)
rabbitmq
Export all vhosts, exchanges and policies via management API
curl -s -u guest:guest http://localhost:15672/api/definitions | jq '.' > rabbitmq-defs.json
Connect with URI
mongodb
Connect to Atlas or any MongoDB URI with mongosh
mongosh 'mongodb+srv://user:pass@cluster.example.com/mydb'
Explain query plan
mongodb
Show execution stats including index usage
db.orders.find({status:'new'}).explain('executionStats')
Create compound index
mongodb
Ascending userId + descending createdAt index
db.orders.createIndex({userId: 1, createdAt: -1}, {background: true})
Aggregation pipeline example
mongodb
Top 10 users by paid order amount
db.orders.aggregate([{$match:{status:'paid'}},{$group:{_id:'$userId',total:{$sum:'$amount'}}},{$sort:{total:-1}},{$limit:10}])
Check replication lag
mongodb
Show secondary lag and oplog window
rs.printSecondaryReplicationInfo()
List operations running longer than 5 seconds
db.currentOp({active:true, secs_running:{$gt:5}})
Dump a database
mongodb
Dump all collections in a database to BSON files
mongodump --uri='mongodb://localhost:27017' --db=mydb --out=/backup/$(date +%F)
Connect and run a query
clickhouse
Execute a one-shot query via clickhouse-client
clickhouse-client --host ch.example.com --user default --password secret -q 'SELECT version()'
Check running queries
clickhouse
List longest running queries in the system
clickhouse-client -q 'SELECT query_id, elapsed, query FROM system.processes ORDER BY elapsed DESC LIMIT 10'
Kill a running query
clickhouse
Force-stop a specific query by its query_id
clickhouse-client -q "KILL QUERY WHERE query_id = 'abc-123'"
Table disk usage
clickhouse
Top 20 tables by on-disk size
clickhouse-client -q 'SELECT database, table, formatReadableSize(sum(bytes_on_disk)) AS size FROM system.parts GROUP BY database, table ORDER BY sum(bytes_on_disk) DESC LIMIT 20'
Optimize table (force merge)
clickhouse
Force merging of all parts (use with caution on large tables)
clickhouse-client -q 'OPTIMIZE TABLE mydb.mytable FINAL'
Ingest CSV from file
clickhouse
Bulk-load a CSV file into a ClickHouse table
clickhouse-client --query 'INSERT INTO mydb.events FORMAT CSVWithNames' < events.csv
Check replication status
clickhouse
Show replication lag on delayed replicas
clickhouse-client -q 'SELECT database, table, is_leader, queue_size, absolute_delay FROM system.replicas WHERE absolute_delay > 0'
Run CQL from cqlsh
cassandra
Execute a CQL statement non-interactively
cqlsh -u cassandra -p cassandra -e 'DESCRIBE KEYSPACES;'
Check table stats
cassandra
Show read/write latencies and SSTable count for a table
nodetool tablestats mykeyspace.mytable
Repair a keyspace
cassandra
Full repair to sync all replicas for a keyspace
nodetool repair -full mykeyspace
Check cluster health
elasticsearch
Show cluster status: green/yellow/red with shard counts
curl -s http://es:9200/_cluster/health?pretty
List indices with size
elasticsearch
All indices sorted by store size (largest first)
curl -s 'http://es:9200/_cat/indices?v&s=store.size:desc'
Delete old index
elasticsearch
Remove a specific index (irreversible)
curl -X DELETE http://es:9200/logs-2024.01.01
Search with query DSL
elasticsearch
Find last 5 error log entries
curl -X GET 'http://es:9200/logs-*/_search?pretty' -H 'Content-Type: application/json' -d '{"query":{"match":{"level":"error"}},"size":5}'
Show shards allocation
elasticsearch
Show all shards with their state and unassigned reason
curl -s 'http://es:9200/_cat/shards?v&h=index,shard,prirep,state,node,unassigned.reason'
Force shard re-allocation
elasticsearch
Retry allocation of all failed/unassigned shards
curl -X POST http://es:9200/_cluster/reroute?retry_failed=true
Update index settings
elasticsearch
Change replica count on a live index
curl -X PUT 'http://es:9200/my-index/_settings' -H 'Content-Type: application/json' -d '{"index":{"number_of_replicas":1}}'
Create index template
elasticsearch
Auto-configure new indices matching logs-*
curl -X PUT 'http://es:9200/_index_template/logs-tpl' -H 'Content-Type: application/json' -d '{"index_patterns":["logs-*"],"template":{"settings":{"number_of_shards":2}}}'
Snapshot to repository
elasticsearch
Create a cluster snapshot synchronously
curl -X PUT 'http://es:9200/_snapshot/my_repo/snap1?wait_for_completion=true'
Use colon as field separator, print user and UID
awk -F: '{print $1, $3}' /etc/passwd
Print line number and content for lines matching ERROR
awk '/ERROR/ {print NR": "$0}' app.log
Sum a column
awk
Accumulate a numeric column and print total
awk '{sum += $4} END {print sum}' access.log
Range pattern: include lines from START to END inclusive
awk '/START/,/END/' file.txt
Frequency count of the first field (e.g. IP addresses)
awk '{count[$1]++} END {for (k in count) print count[k], k}' access.log | sort -rn
Print last field
awk
NF holds the number of fields; $NF is the last field
awk '{print $NF}' file.txt
Print lines where field 2 > 500 AND field 5 is POST
awk '$2 > 500 && $5 == "POST"' access.log
Reformat output
awk
Aligned printf formatting with fixed column widths
awk '{printf "%-20s %5d\n", $1, $2}' data.txt
Load awk program from an external script file
awk -f transform.awk input.txt
Global substitution and write back to same file
awk '{gsub(/foo/, "bar"); print}' input.txt > tmp && mv tmp input.txt
Parse quoted CSV fields correctly with FPAT in gawk
gawk -v FPAT='([^,]+)|("[^"]+")' '{print $2}' data.csv
BEGIN/END blocks
awk
Run code before and after processing all lines
awk 'BEGIN{print "Start"} {lines++} END{print lines" lines processed"}' file.txt
Left-join data.txt with lookup.txt on first field
awk 'NR==FNR{a[$1]=$2; next} $1 in a {print $0, a[$1]}' lookup.txt data.txt
Replace the first occurrence of 'foo' with 'bar' per line
sed 's/foo/bar/' file.txt
Replace every occurrence per line with the /g flag
sed 's/foo/bar/g' file.txt
In-place edit
sed
Modify file in-place (no backup); on macOS add empty string: -i ''
sed -i 's/old/new/g' config.cfg
Edit in-place and save original as file.txt.bak
sed -i.bak 's/old/new/g' file.txt
Print lines 10 through 20 only (suppress default output with -n)
sed -n '10,20p' file.txt
Insert a comment line before every server_name directive
sed '/^server_name/i # Added by deploy script' nginx.conf
Append a setting line after the [defaults] header
sed '/^\[defaults\]/a ansible_python_interpreter=/usr/bin/python3' ansible.cfg
GNU sed /I flag for case-insensitive match
sed 's/error/ERROR/gI' file.txt
Apply multiple substitutions in one command
sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt
Trim leading and trailing whitespace from each line
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' file.txt
Apply substitution only to lines 5 through 15
sed '5,15s/DEBUG/INFO/g' app.log
Print the value of DB_HOST from a .env file
sed -n 's/^DB_HOST=//p' .env
/ searches forward, ? searches backward; n/N cycle results
/pattern (n/N next/prev)
?pattern (backward)
Macros automate repetitive edits in vim
qa (record into a)
q (stop)
@a (play)
10@a (play 10 times)
Vertical split; use Ctrl-w + arrow to navigate panes
:vsplit other.txt
Override Makefile variables at call time
make IMAGE=myapp:v2 TAG=latest push
Convention: annotate targets with ## comments for self-documenting Makefiles
grep -E '^[a-zA-Z_-]+:.*?##' Makefile | awk -F':.*##' '{printf "%-20s %s\n", $1, $2}'
Unconditionally remake all targets (-B / --always-make)
make -B build
Use a Makefile in a different directory or with a different name
make -f infra/Makefile plan
Prevent make from confusing targets with files of the same name
.PHONY: build test deploy clean
$@ expands to the current target name in a recipe
build:
docker build -t $(IMAGE) . && echo 'Built $@'
Run container rootless
podman
Start a detached nginx container without root privileges
podman run -d --name web -p 8080:80 nginx:alpine
Build image
podman
Build from a Containerfile (Dockerfile-compatible)
podman build -t myapp:latest -f Containerfile .
Generate systemd unit
podman
Create a systemd unit to manage the container lifecycle
podman generate systemd --new --name web > ~/.config/systemd/user/web.service
Play Kubernetes YAML
podman
Run a pod from a Kubernetes manifest (local testing)
podman play kube deployment.yaml
Generate a Kubernetes-compatible manifest from a running pod
podman generate kube mypod > pod.yaml
Create and use a pod
podman
Group containers into a pod sharing network namespace
podman pod create --name mypod -p 8080:80 && podman run -d --pod mypod nginx:alpine
Inspect image layers
podman
List filesystem layers of an image
podman image inspect myapp:latest | jq '.[0].RootFS.Layers'
Show all containers with name, status and image
podman ps -a --format '{{.Names}}\t{{.Status}}\t{{.Image}}'
Non-interactively delete all exited containers
podman container prune -f
Login to registry
podman
Authenticate with a container registry
podman login registry.example.com -u myuser
Login to ArgoCD
argocd
Authenticate argocd CLI using the initial admin secret
argocd login argocd.example.com --username admin --password $(kubectl get secret argocd-initial-admin-secret -n argocd -o jsonpath='{.data.password}' | base64 -d)
Force refresh (bypass cache)
argocd
Force ArgoCD to re-fetch manifests from Git
argocd app get myapp --refresh
Show app diff vs cluster
argocd
Show what would change if the app were synced now
argocd app diff myapp
Rollback to previous version
argocd
Rollback to revision 3 of the application history
argocd app rollback myapp 3
Create application from CLI
argocd
Declaratively create an ArgoCD app with auto-sync
argocd app create myapp --repo https://github.com/org/repo --path k8s/prod --dest-server https://kubernetes.default.svc --dest-namespace default --sync-policy automated
Remove ArgoCD app object without deleting Kubernetes resources
argocd app delete myapp --cascade=false
Add cluster to ArgoCD
argocd
Register an external cluster using a kubeconfig context
argocd cluster add my-k8s-context
Set image override
argocd
Override container image for a Kustomize app without changing Git
argocd app set myapp --kustomize-image myapp=myregistry/myapp:v1.2.3
Pause auto-sync
argocd
Disable automated sync for manual control
argocd app set myapp --sync-policy none
View application resources
argocd
List all Kubernetes resources managed by an app
argocd app resources myapp
Watch sync status
argocd
Block until app is synced and healthy (CI use case)
argocd app wait myapp --sync --health --timeout 120
Create project with RBAC
argocd
Isolate apps in a project with source/destination restrictions
argocd proj create myproject --description 'Production apps' --dest 'https://kubernetes.default.svc,prod' --src 'https://github.com/org/*'
Cross-compile a Go binary for Linux/amd64
GOOS=linux GOARCH=amd64 go build -o bin/app ./cmd/app
Run all tests with race condition detection enabled
go test -race -count=1 ./...
Generate HTML coverage report and open in browser
go test -coverprofile=cov.out ./... && go tool cover -html=cov.out
Download a specific module version and update go.mod
go get github.com/some/pkg@v1.2.3
Run benchmarks, collect CPU profile, open pprof interactive UI
go test -cpuprofile=cpu.prof -bench=. ./... && go tool pprof cpu.prof
Trace a new process
strace
Run a command under strace and save output to file
strace -o trace.log ls /tmp
Attach to running process
strace
Trace syscalls of an already-running process by PID
strace -p $(pgrep nginx | head -1) -o /tmp/nginx.trace
Trace only specific syscalls
strace
Filter to file-related syscalls only
strace -e trace=openat,read,write curl https://example.com
Count syscall statistics
strace
Summary table of syscall counts and time spent
strace -c -e trace=all python3 app.py
Follow child processes
strace
Trace syscalls in all forked children (-f)
strace -f -e trace=process nginx -t
Show timestamps
strace
-tt adds absolute time; -T shows time spent in each call
strace -tt -T curl https://example.com 2>&1 | head -40
Trace file access
strace
Find files the process tries to open but cannot find
strace -e trace=openat -e trace=file myapp 2>&1 | grep 'ENOENT'
Trace network syscalls
strace
Capture all network-related syscalls
strace -e trace=network,socket curl https://example.com 2>&1 | grep -v '^---'
Capture to file
tcpdump
Save raw packets to PCAP file for Wireshark analysis
tcpdump -i eth0 -w /tmp/capture.pcap
Read PCAP file
tcpdump
Replay and display packets from a saved PCAP file
tcpdump -r /tmp/capture.pcap -n | head -50
Show HTTP GET requests
tcpdump
Capture and print HTTP GET request lines
tcpdump -i any -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)' | grep 'GET /'
Capture between two hosts
tcpdump
BPF filter: traffic between exactly two endpoints
tcpdump -i eth0 'host 10.0.0.1 and host 10.0.0.2'
Verbose with packet content
tcpdump
Full verbose output with ASCII packet content for PostgreSQL
tcpdump -i eth0 -vvv -A -s 0 port 5432
List rules with line numbers
iptables
Show INPUT chain rules with packet/byte counters
iptables -L INPUT --line-numbers -n -v
Allow incoming port
iptables
Append a rule to accept inbound HTTPS traffic
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
Block IP address
iptables
Insert DROP rule at position 1 for a specific source IP
iptables -I INPUT 1 -s 203.0.113.5 -j DROP
NAT: masquerade outbound
iptables
Enable IP masquerading for outbound traffic (router/NAT)
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
Save and restore rules
iptables
Persist rules across reboots
iptables-save > /etc/iptables/rules.v4
iptables-restore < /etc/iptables/rules.v4
Rate-limit connections
iptables
Allow max 3 new SSH connections per minute
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m limit --limit 3/min --limit-burst 5 -j ACCEPT
nftables: add accept rule
iptables
Accept inbound TCP traffic on port 8080 in nftables
nft add rule inet filter input tcp dport 8080 accept
nftables: flush all rules
iptables
Delete all nftables rules (caution: drops all firewall rules)
nft flush ruleset
Show all files (sockets, regular, pipes) opened by nginx
lsof -p $(pgrep nginx) | head -30
Show all open network connections without DNS resolution
lsof -i -n -P
Show all processes with open files under /var/log
lsof +D /var/log
Find files deleted but still held open by processes (disk bloat)
lsof | grep '(deleted)'
Filter established TCP connections with process info
ss -tanp | grep ESTAB
Dev mode (hot-reload)
skaffold
Build, deploy and watch for changes; auto-rebuild on save
skaffold dev --port-forward
One-shot build and deploy
skaffold
Build images, push to registry and deploy to cluster
skaffold run --tail
Build only (no deploy)
skaffold
Build images and export artifact metadata to file
skaffold build --file-output=artifacts.json
Deploy pre-built artifacts
skaffold
Deploy using previously built image digests from CI
skaffold deploy --build-artifacts=artifacts.json
Render manifests only
skaffold
Produce final Kubernetes YAML without applying it
skaffold render --output=manifests.yaml
Diagnose config issues
skaffold
Validate skaffold.yaml and print resolved configuration
skaffold diagnose
Clean up deployed resources
skaffold
Delete all Kubernetes resources created by skaffold run
skaffold delete
Test connectivity (ping)
ansible
Verify SSH connectivity to all hosts in inventory
ansible all -i inventory.ini -m ping
Run ad-hoc shell command
ansible
Execute a shell command on all webservers with sudo (-b)
ansible webservers -i inventory.ini -m shell -a 'df -h' -b
Gather facts for a host
ansible
Collect and inspect Ansible facts for one host
ansible myhost -i inventory.ini -m setup | jq '.ansible_facts.ansible_distribution'
Run playbook with tags
ansible
Execute only tasks tagged nginx or ssl
ansible-playbook site.yml -i inventory.ini --tags 'nginx,ssl'
Skip specific tags
ansible
Skip tasks tagged slow or optional
ansible-playbook site.yml -i inventory.ini --skip-tags 'slow,optional'
Encrypt variable with Vault
ansible
Inline-encrypt a single string value for use in vars
ansible-vault encrypt_string 'mysecretpassword' --name 'db_password'
Limit to specific hosts
ansible
Run playbook only on web01 and web02
ansible-playbook deploy.yml -i inventory.ini --limit 'web01,web02'
Step through tasks interactively
ansible
Confirm each task before execution (debug mode)
ansible-playbook site.yml -i inventory.ini --step
Mount a KV version 2 secrets engine at 'secret/'
vault secrets enable -path=secret kv-v2
Write a secret
vault
Store multiple key-value pairs at a path
vault kv put secret/myapp/config db_password=s3cr3t api_key=abc123
Read a secret
vault
Read a KV v2 secret and extract the data payload
vault kv get -format=json secret/myapp/config | jq '.data.data'
Create periodic token
vault
Issue a renewable token with a 24h TTL for CI
vault token create -policy=read-only -period=24h -display-name=ci-pipeline
Allow pods to authenticate with Vault via ServiceAccount JWT
vault auth enable kubernetes && vault write auth/kubernetes/config kubernetes_host=https://kubernetes.default.svc
Obtain short-lived Postgres credentials from the database secrets engine
vault read database/creds/readonly-role
Seal / unseal Vault
vault
Manually seal or unseal Vault with an unseal key shard
vault operator seal
vault operator unseal $UNSEAL_KEY
Diff before upgrade
helm
Show what would change in the cluster (requires helm-diff plugin)
helm diff upgrade myrelease ./chart -f values.yaml
Show computed values
helm
Print the user-supplied values for a deployed release
helm get values myrelease -n mynamespace
Show all values including chart defaults (-a / --all)
helm get values myrelease -a -n mynamespace
Roll back a release to revision number 2
helm rollback myrelease 2 -n mynamespace
Show release history
helm
List all revisions of a Helm release with status
helm history myrelease -n mynamespace
Create a versioned .tgz package from a chart directory
helm package ./mychart --version 1.2.3 --app-version 1.2.3
Publish a chart to an OCI-compatible registry (Helm 3.8+)
helm push mychart-1.2.3.tgz oci://registry.example.com/charts
Lint a chart
helm
Validate chart structure and catch template errors
helm lint ./mychart -f values.yaml --strict
Probe open ports to determine service/version info
nmap -sV 192.168.1.1
Aggressive scan
nmap
Enables OS detection, version detection, script scanning, and traceroute
nmap -A 192.168.1.1
Run a named Nmap scripting engine script
nmap --script http-title 192.168.1.1
Transfer file (receiver)
netcat
Receive a file from a netcat sender
nc 192.168.1.1 4444 > file.tar.gz
Simple HTTP request
netcat
Send a raw HTTP GET request with netcat
echo -e "GET / HTTP/1.0
" | nc example.com 80
Collect data suitable for flamegraph generation
perf record -F 99 -ag -- sleep 30 && perf script > out.perf
Profile an already-running process for 5 seconds
perf record -p 1234 sleep 5
Create API key (CLI)
grafana
Reset admin password via Grafana CLI
grafana-cli admin reset-admin-password newpassword
List plugins
grafana
List all available plugins from Grafana marketplace
grafana-cli plugins list-remote
Install plugin
grafana
Install a Grafana plugin by name
grafana-cli plugins install grafana-piechart-panel
Export dashboard via API
grafana
Export dashboard JSON via Grafana HTTP API
curl -s http://admin:admin@localhost:3000/api/dashboards/uid/MY_UID | jq .dashboard
Import dashboard via API
grafana
Import a dashboard JSON via Grafana HTTP API
curl -X POST -H "Content-Type: application/json" -d @dashboard.json http://admin:admin@localhost:3000/api/dashboards/import
List datasources via API
grafana
List all configured datasources
curl -s http://admin:admin@localhost:3000/api/datasources | jq .[].name
Create datasource via API
grafana
Add a new datasource via Grafana API
curl -X POST -H "Content-Type: application/json" -d @ds.json http://admin:admin@localhost:3000/api/datasources
Provision dashboards folder
grafana
Grafana auto-loads dashboards from provisioning directory on startup
# Place YAML in /etc/grafana/provisioning/dashboards/
Install Istio with the demo configuration profile
istioctl install --set profile=demo -y
Enable sidecar injection
istio
Enable automatic Envoy sidecar injection for a namespace
kubectl label namespace default istio-injection=enabled
View Envoy config
istio
Show complete Envoy proxy config for a deployment
istioctl proxy-config all deploy/myapp
Apply a VirtualService to define traffic routing rules
kubectl apply -f virtualservice.yaml
Apply a DestinationRule to define load balancing and circuit breaker policies
kubectl apply -f destinationrule.yaml
Enable mTLS (strict)
istio
Enforce strict mutual TLS for all workloads in namespace
kubectl apply -f - <<EOF
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
name: default
namespace: default
spec:
mtls:
mode: STRICT
EOF
Inject sidecar manually
istio
Manually inject Istio sidecar into a deployment manifest
istioctl kube-inject -f deployment.yaml | kubectl apply -f -
View access logs
istio
View Envoy access logs from the sidecar container
kubectl logs -l app=myapp -c istio-proxy | head -50
Fault injection — delay
istio
Inject artificial delay to test resilience (in VirtualService)
# In VirtualService spec.http[].fault.delay
Traffic mirroring
istio
Mirror traffic to a shadow service for testing
# In VirtualService spec.http[].mirror
Install cert-manager via Helm
cert-manager
Install cert-manager with CRDs into its own namespace
helm install cert-manager jetstack/cert-manager --namespace cert-manager --create-namespace --set installCRDs=true
Check cert-manager pods
cert-manager
Verify all cert-manager components are running
kubectl get pods -n cert-manager
List certificates
cert-manager
List all Certificate resources across namespaces
kubectl get certificates -A
Describe certificate
cert-manager
Show status and events for a Certificate resource
kubectl describe certificate my-cert -n default
List certificate requests
cert-manager
List all CertificateRequest objects
kubectl get certificaterequests -A
Create ClusterIssuer (Let's Encrypt)
cert-manager
Apply a ClusterIssuer manifest for Let's Encrypt ACME
kubectl apply -f clusterissuer-letsencrypt.yaml
Check ClusterIssuers
cert-manager
List all ClusterIssuer resources and their ready status
kubectl get clusterissuers
Manually trigger renewal
cert-manager
Force cert-manager to renew a certificate immediately
kubectl annotate certificate my-cert cert-manager.io/issueTime="$(date -u +%Y-%m-%dT%H:%M:%SZ)" --overwrite
View cert-manager logs
cert-manager
Stream logs from the main cert-manager controller
kubectl logs -n cert-manager deploy/cert-manager -f
Install Crossplane via Helm
crossplane
Install Crossplane into its own namespace
helm install crossplane crossplane-stable/crossplane --namespace crossplane-system --create-namespace
Install AWS provider
crossplane
Apply a Crossplane Provider manifest for AWS
kubectl apply -f provider-aws.yaml
List managed resources
crossplane
List all Crossplane managed resources across all kinds
kubectl get managed
List composite resources
crossplane
List all Crossplane composite resource instances
kubectl get composite
Describe managed resource
crossplane
Show status and conditions of a managed resource
kubectl describe rdsinstance my-db
List XRDs
crossplane
List all CompositeResourceDefinitions (XRDs)
kubectl get compositeresourcedefinitions
Check provider health
crossplane
Show provider readiness and installed packages
kubectl describe provider provider-aws
Crossplane trace resource
crossplane
Trace a composite resource and all its children
crossplane beta trace xr my-xr
Install Linkerd CLI
linkerd
Download and install the Linkerd CLI
curl --proto =https --tlsv1.2 -sSfL https://run.linkerd.io/install | sh
Pre-install check
linkerd
Validate cluster meets requirements before installing Linkerd
linkerd check --pre
Install Linkerd CRDs
linkerd
Install Linkerd CRDs into the cluster
linkerd install --crds | kubectl apply -f -
Install Linkerd control plane
linkerd
Install Linkerd control plane components
linkerd install | kubectl apply -f -
Inject sidecar into deployment
linkerd
Inject Linkerd proxy sidecar into existing deployment
kubectl get deploy my-app -o yaml | linkerd inject - | kubectl apply -f -
Live traffic stats
linkerd
Show real-time golden metrics for all deployments
linkerd viz stat deploy
Top live requests
linkerd
Show a top-like view of live requests to a deployment
linkerd viz top deploy/my-app
Tap live traffic
linkerd
Watch live HTTP request/response stream for a deployment
linkerd viz tap deploy/my-app
Scan Kubernetes cluster
trivy
Scan the entire Kubernetes cluster for vulnerabilities and misconfigs
trivy k8s --report summary cluster
Scan with SARIF output
trivy
Output scan results in SARIF format for CI/IDE integration
trivy image --format sarif --output results.sarif myimage:tag
Filter by severity
trivy
Show only HIGH and CRITICAL vulnerabilities
trivy image --severity HIGH,CRITICAL myimage:tag
Ignore unfixed vulns
trivy
Skip vulnerabilities that have no fix available
trivy image --ignore-unfixed myimage:tag
Show full kubectl describe output for selected resource
d (on selected resource)
Build and apply
kustomize
Build kustomize overlay and apply directly to cluster
kubectl apply -k ./overlays/prod
Preview output
kustomize
Render kustomize output without applying
kubectl kustomize ./overlays/prod | head -100
Set image tag
kustomize
Update image tag in kustomization.yaml
kustomize edit set image myapp=myapp:v1.2.3
Add configMapGenerator
kustomize
Add a ConfigMap generator entry to kustomization.yaml
kustomize edit add configmap my-config --from-literal=key=value
List resources in overlay
kustomize
Quickly list all resource kinds in a kustomize build
kustomize build ./overlays/prod | grep "^kind:"
Apply strategic merge patch
kustomize
Use patchesStrategicMerge to partially override base resources
# Add patchesStrategicMerge in kustomization.yaml
Check APISIX status
apisix
Check APISIX pods are running in Kubernetes
kubectl get pods -n ingress-apisix
List routes via Admin API
apisix
List all configured APISIX routes
curl http://apisix-admin:9180/apisix/admin/routes -H "X-API-KEY: $ADMIN_KEY"
Create route
apisix
Create a simple route with roundrobin upstream
curl -X PUT http://apisix-admin:9180/apisix/admin/routes/1 -H "X-API-KEY: $ADMIN_KEY" -d '{"uri":"/api/*","upstream":{"nodes":{"backend:8080":1},"type":"roundrobin"}}'
Enable plugin on route
apisix
Add rate-limiting plugin to an existing route
curl -X PATCH http://apisix-admin:9180/apisix/admin/routes/1 -H "X-API-KEY: $ADMIN_KEY" -d '{"plugins":{"limit-req":{"rate":100,"burst":50,"key":"remote_addr"}}}'
List upstreams
apisix
List all configured APISIX upstreams
curl http://apisix-admin:9180/apisix/admin/upstreams -H "X-API-KEY: $ADMIN_KEY"
Create consumer
apisix
Create an APISIX consumer with key authentication
curl -X PUT http://apisix-admin:9180/apisix/admin/consumers/myuser -H "X-API-KEY: $ADMIN_KEY" -d '{"plugins":{"key-auth":{"key":"user-api-key"}}}'
Enable JWT auth plugin
apisix
Enable JWT authentication on a route via plugin config
# Add jwt-auth to plugins in route or consumer config
List plugins
apisix
List all available APISIX plugins
curl http://apisix-admin:9180/apisix/admin/plugins/list -H "X-API-KEY: $ADMIN_KEY"
Find large files
linux
Find files larger than 100MB on the entire filesystem
find / -type f -size +100M 2>/dev/null | sort
Count open file descriptors for a running process
cat /proc/$(pgrep myapp)/fd | wc -l
List cron jobs (system)
linux
List all system and user cron job locations
ls /etc/cron.* /var/spool/cron/crontabs/
Display all environment variables sorted alphabetically
printenv | sort
TCP/IP tuning — backlog
linux
Increase the maximum connection backlog for sockets
sysctl -w net.core.somaxconn=65535
Interactively reorder, squash, or edit last 5 commits
git rebase -i HEAD~5
Save working changes with a descriptive stash message
git stash push -m "WIP: feature X"
Start binary search for the commit that introduced a bug
git bisect start && git bisect bad && git bisect good v1.0
Show full diff history of a file including renames
git log --follow -p -- path/to/file.py
Move HEAD back one commit, keeping staged changes
git reset --soft HEAD~1
List local branches already merged into main
git branch --merged main
Navigate to a resource type by pressing ':' then typing the resource name
:pod
# or :svc :deployment :helmreleases :kustomizations
Filter listed resources by name pattern (press '/' to activate)
/pattern
# Press '/' then type filter string, Esc to clear
Describe selected resource (equivalent to kubectl describe)
d
# Press 'd' on selected resource to view describe output
View pod logs (press 'l' on pod, '0' for all containers)
l
# Press 'l' on a pod; '0' for all containers, 'w' to wrap
Open shell in pod container (press 's' on pod)
s
# Press 's' on a pod to open a shell (uses first container)
Delete selected resource (press Ctrl+D, confirm with Enter)
ctrl-d
# Press Ctrl+D on selected resource, confirm with Enter
Provision dashboards folder
grafana
Create Grafana dashboard provisioning config (restart Grafana after)
cat > /etc/grafana/provisioning/dashboards/default.yaml <<EOF
apiVersion: 1
providers:
- name: default
type: file
folder: ''
options:
path: /var/lib/grafana/dashboards
EOF
Route 80% traffic to v1, 20% to v2 (canary split)
kubectl apply -f - <<EOF
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: myapp
spec:
hosts:
- myapp
http:
- route:
- destination:
host: myapp
subset: v1
weight: 80
- destination:
host: myapp
subset: v2
weight: 20
EOF
Define subsets and circuit breaker (outlier detection)
kubectl apply -f - <<EOF
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
name: myapp
spec:
host: myapp
trafficPolicy:
outlierDetection:
consecutive5xxErrors: 5
interval: 10s
baseEjectionTime: 30s
subsets:
- name: v1
labels:
version: v1
- name: v2
labels:
version: v2
EOF
Fault injection — delay
istio
Inject 5s delay for 100% of requests to test resilience
kubectl apply -f - <<EOF
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: myapp
spec:
hosts:
- myapp
http:
- fault:
delay:
percentage:
value: 100
fixedDelay: 5s
route:
- destination:
host: myapp
EOF
Traffic mirroring
istio
Mirror 100% of traffic to v2 shadow service
kubectl apply -f - <<EOF
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: myapp
spec:
hosts:
- myapp
http:
- route:
- destination:
host: myapp
subset: v1
weight: 100
mirror:
host: myapp
subset: v2
mirrorPercentage:
value: 100
EOF
Create ClusterIssuer (Let's Encrypt)
cert-manager
Create Let's Encrypt prod ClusterIssuer with HTTP-01 solver
kubectl apply -f - <<EOF
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
email: admin@example.com
privateKeySecretRef:
name: letsencrypt-prod
solvers:
- http01:
ingress:
class: nginx
EOF
Install AWS provider
crossplane
Install Crossplane AWS provider from Upbound registry
kubectl apply -f - <<EOF
apiVersion: pkg.crossplane.io/v1
kind: Provider
metadata:
name: provider-aws
spec:
package: xpkg.upbound.io/upbound/provider-aws:latest
EOF
Apply strategic merge patch
kustomize
Create a strategic merge patch and register it in kustomization.yaml
cat > patch.yaml <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp
spec:
replicas: 3
template:
spec:
containers:
- name: myapp
resources:
limits:
memory: 512Mi
EOF
echo 'patches:\n- path: patch.yaml' >> kustomization.yaml
Enable JWT auth plugin
apisix
Add jwt-auth plugin to an existing route via Admin API
curl -X PATCH http://apisix-admin:9180/apisix/admin/routes/1 \
-H "X-API-KEY: $ADMIN_KEY" \
-d '{"plugins":{"jwt-auth":{"header":"Authorization","query":"jwt"}}}'
Filter by priority error and above
journalctl
Only err/crit/alert/emerg from current boot; -p takes a range too (e.g. -p warning..err)
journalctl -p err -b --no-pager
Match by raw systemd unit field
journalctl
Trusted unit match by indexed field, unlike -u which also pulls coredumps/PAM noise
journalctl _SYSTEMD_UNIT=sshd.service --since today
Combine field filters with OR
journalctl
A bare + is a logical OR between match groups; same-field matches within a group are OR'd too
journalctl _PID=1 + _COMM=sshd -o short-iso
Regex grep across messages
journalctl
PCRE2 match on MESSAGE; pair with -p err to narrow noise. note: scans, not indexed
journalctl --grep='oom|out of memory' --case-sensitive=false -b
Verbose output with all fields
journalctl
Dumps every journal field incl. cursor for an entry; -o json-pretty for machine parsing
journalctl -u <name> -o verbose -n 1
List boots and read previous boot
journalctl
Index past boots, then -b -1 reads the prior boot. note: needs persistent storage
journalctl --list-boots && journalctl -b -1 -p warning
Kernel ring buffer with timestamps
journalctl
Like dmesg but with real wall-clock and boot filtering; -k means _TRANSPORT=kernel
journalctl -k -b -o short-precise --grep='segfault|I/O error'
Disk usage and vacuum by size/time
journalctl
Show on-disk size, then prune to 500M and drop entries older than 2 days
journalctl --disk-usage; journalctl --vacuum-size=500M --vacuum-time=2d
Follow logs by syslog identifier
journalctl
Tail by SYSLOG_IDENTIFIER (not unit); -t repeats, --no-hostname trims clutter
journalctl -t kernel -t sudo -f --no-hostname
Project selected fields as columns
journalctl
Trim JSON to needed fields then tab-format; __REALTIME_TIMESTAMP is microseconds
journalctl -u <name> --output=json --output-fields=__REALTIME_TIMESTAMP,MESSAGE,_PID | jq -r '[.__REALTIME_TIMESTAMP,._PID,.MESSAGE]|@tsv'
Merge journals from a directory
journalctl
Read journals from another root (rescue/forensics) without copying files in
journalctl -D /mnt/crashed/var/log/journal -b -1 -p err
Verify persistent storage is enabled
journalctl
If /var/log/journal is absent, logs are volatile and lost on reboot. fix: mkdir + systemd-tmpfiles
journalctl --header | grep -iE 'file|state'; ls -d /var/log/journal 2>/dev/null || echo volatile
Boot critical chain
systemd
Show the serialized dependency chain that actually delays boot; more honest than blame
systemd-analyze critical-chain <unit>
Boot timeline SVG
systemd
Render full parallel boot timeline as an SVG to spot serialized stalls visually
systemd-analyze plot > boot.svg
Drop-in override
systemd
Patch a unit via drop-in without touching the vendor file; use --full to fork the whole unit
systemctl edit <unit> # writes /etc/systemd/system/<unit>.d/override.conf
Reload unit files
systemd
Reload unit files after editing; note: required after manual edits or systemctl warns of stale config
systemctl daemon-reload
Mask a unit
systemd
Mask symlinks a unit to /dev/null so it cannot start even as a dependency; stronger than disable
systemctl mask <unit> && systemctl unmask <unit>
Recursive dependency tree
systemd
Walk the full Wants/Requires tree to debug why a service pulls in others; --reverse for who needs it
systemctl list-dependencies <unit> --all
Live memory of a unit
systemd
Read live cgroup metrics straight from systemd without ps; MemoryCurrent is the accounted RSS
systemctl show -p MainPID,MemoryCurrent,TasksCurrent <unit>
Clear failed state
systemd
Reset failed counters so units can restart past StartLimitBurst, then list what is still failed
systemctl reset-failed && systemctl list-units --state=failed
Transient one-shot timer
systemd
Spin up a throwaway timer+service without writing unit files; great for ad-hoc scheduled jobs
systemd-run --on-calendar='*-*-* 03:00:00' --unit=backup /usr/local/bin/backup.sh
Runtime resource cap
systemd
Apply cgroup limits live without restart; --runtime keeps them volatile (gone on reboot)
systemctl set-property --runtime <unit> MemoryMax=512M CPUQuota=50%
Pending jobs queue
systemd
Show in-flight start/stop jobs to diagnose a hung boot or a unit stuck activating
systemctl list-jobs
Live RSS vs hard limit for a systemd service; current near max = imminent OOM
cat /sys/fs/cgroup/system.slice/<name>.service/memory.current /sys/fs/cgroup/system.slice/<name>.service/memory.max
Memory PSI pressure stall
cgroups
PSI: time tasks stalled on memory reclaim; rising avg10 = thrashing before OOM
cat /sys/fs/cgroup/system.slice/<name>.service/memory.pressure
CPU throttling stats (cgroup v2)
cgroups
Count and total usec a cgroup was CPU-throttled by cpu.max quota
grep -E 'nr_throttled|throttled_usec' /sys/fs/cgroup/system.slice/<name>.service/cpu.stat
cpu.max is 'quota period' in usec; 'max' = no limit. note: prefer systemctl set-property
cat /sys/fs/cgroup/system.slice/<name>.service/cpu.max # "max 100000" = unlimited; "50000 100000" = 0.5 core
Per-device IO pressure and stats
cgroups
PSI io stall plus per-major:minor rbytes/wbytes/rios; pin noisy disk neighbors
cat /sys/fs/cgroup/system.slice/<name>.service/io.pressure /sys/fs/cgroup/system.slice/<name>.service/io.stat
List PIDs in a service cgroup
cgroups
Every PID currently in the service slice; cross-check with systemctl status tree
cat /sys/fs/cgroup/system.slice/<name>.service/cgroup.procs; systemctl status <name>.service | grep CGroup
cgls --all shows empty cgroups too; cgtop ranks slices by live CPU/mem/io
systemd-cgls --all --no-pager; systemd-cgtop -d 2 --depth=3
Legacy v1 ad-hoc cgroup
cgroups
libcgroup v1 throwaway limit. note: v2 unified hierarchy uses systemd-run --scope -p
cgcreate -g memory:/<name>; cgset -r memory.limit_in_bytes=512M <name>; cgexec -g memory:/<name> <command>
Namespaces of a specific PID
namespaces
List all ns a PID belongs to; compare ns inode links to prove shared namespace
lsns -p <pid>; readlink /proc/<pid>/ns/net /proc/1/ns/net # equal inode = same netns
Tcpdump inside a container netns from host
namespaces
Sniff a container's traffic using host's tcpdump via its netns; no tools needed in image
PID=$(docker inspect -f '{{.State.Pid}}' <name>); nsenter -t $PID -n tcpdump -ni any -c 50
Inspect sockets in a process netns/mntns
namespaces
Enter newest proc's net+mount+pid ns and list listening sockets it actually sees
nsenter -t $(pgrep -n <proc>) -n -m -p ss -tlnp
Isolated sandbox with unshare
namespaces
Spawn shell in fresh net+pid ns with private /proc; ip netns for named netns testing
unshare --net --pid --fork --mount-proc bash # then: ip netns add test; ip netns exec test ip a
Add secondary IP
iproute2
Assign a secondary IP/prefix live; note: not persisted across reboot
ip addr add 10.0.0.5/24 dev <name> && ip addr show dev <name>
Set interface MTU
iproute2
Set jumbo MTU and bring link up; note: path MTU must match end-to-end
ip link set dev <name> mtu 9000 && ip link set dev <name> up
JSON addr to jq
iproute2
Machine-readable interface dump; list UP links with their local IPs
ip -j a | jq -r '.[] | select(.operstate=="UP") | .ifname + " " + (.addr_info[]?.local // "-")'
Which route is chosen
iproute2
Show the exact route, src IP and oif the kernel picks for a destination
ip route get <ip>
Source-based policy routing
iproute2
Route by source IP via a separate table; check with ip rule show
ip rule add from <ip> table 100 && ip route add default via 192.168.1.1 dev <name> table 100
Run command in netns
iproute2
Create an isolated network namespace and run commands inside it
ip netns add test && ip netns exec test ip -br a
Inject latency and loss
iproute2
Simulate WAN latency/packet loss for testing; remove with tc qdisc del
tc qdisc add dev <name> root netem delay 100ms loss 1% && tc -s qdisc show dev <name>
Remove netem qdisc
iproute2
Drop the root qdisc to restore normal traffic after netem testing
tc qdisc del dev <name> root
Watch route/link events
iproute2
Live stream of route/link/addr/neigh changes; great for flapping debug
ip monitor all
Bridge FDB and ports
iproute2
Inspect L2 forwarding DB (MAC->port) and bridge port states
bridge fdb show br <name>; bridge link show
Per-socket TCP internals
iproute2
Show rtt/cwnd/retrans per socket for 443; pinpoint slow/lossy peers
ss -tip state established '( dport = :443 )'
Kill sockets by filter
iproute2
Forcibly close matching sockets (kernel>=4.9); needs CONFIG_INET_DIAG_DESTROY
ss -K dst <ip> dport = :8080
Create input chain with drop policy
nftables
Base-chain default-deny; note: add accept rules first or you lock yourself out
nft add chain inet filter input '{ type filter hook input priority 0 ; policy drop ; }'
Named set as IP blocklist
nftables
Reusable named set; flags interval lets you store CIDR ranges, not just hosts
nft add set inet filter blocklist '{ type ipv4_addr ; flags interval ; }' && nft add element inet filter blocklist '{ 10.0.0.0/8, 192.0.2.5 }'
Verdict map for port dispatch
nftables
vmap maps keys to verdicts in O(1); replaces a chain of dport == rules
nft add rule inet filter input tcp dport vmap '{ 22 : accept, 80 : accept, 443 : accept, 3306 : drop }'
List ruleset with rule handles
nftables
-a prints '# handle N' per rule; you need the handle to delete a single rule
nft -a list ruleset
Delete a single rule by handle
nftables
Surgical removal without flushing; get the handle from nft -a list ruleset
nft delete rule inet filter input handle 7
Named counter on a rule
nftables
Inline counter tracks packets/bytes; reset with nft reset counters inet filter
nft add rule inet filter input tcp dport 22 counter accept comment \"ssh\"
SNAT masquerade for outbound NAT
nftables
Source-NAT egress to the iface IP; needs a nat-type postrouting chain to exist
nft add rule ip nat postrouting oifname \"eth0\" masquerade
DNAT port forward to internal host
nftables
Destination-NAT inbound to a backend; pair with a forward-chain accept rule
nft add rule ip nat prerouting iif \"eth0\" tcp dport 443 dnat to 10.0.0.5:8443
Rate-limit new connections
nftables
Throttle SSH brute-force; over-limit packets fall through to the chain policy
nft add rule inet filter input tcp dport 22 ct state new limit rate 10/minute accept
Watch ruleset changes live
nftables
Streams add/delete events as they happen; great for debugging dynamic rules
nft monitor ruleset
Atomic backup and restore of ruleset
nftables
nft -f applies the whole file atomically; partial failure rolls back, no half state
nft list ruleset > /etc/nftables.conf && nft -f /etc/nftables.conf
Hardware flowtable offload
nftables
Offloads established flows to fast path; add 'flags offload' for NIC hardware offload
nft add flowtable inet filter ft '{ hook ingress priority 0 ; devices = { eth0, eth1 } ; }' && nft add rule inet filter forward ct state established flow add @ft
Capture only TCP SYN packets
tcpdump
Catch only connection-initiating SYNs (no SYN-ACK) to spot scans or backlog floods
tcpdump -nn 'tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn'
Capture SYN and FIN flags
tcpdump
Show only connection open/close packets to trace short-lived churning sessions
tcpdump -nn 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0'
Host filter excluding SSH noise
tcpdump
Watch traffic to/from a host while dropping your own SSH session noise
tcpdump -nn -i any host <ip> and not port 22
Full payload hex+ascii dump
tcpdump
Inspect full packet bodies in hex+ascii; -s 0 ensures no snaplen truncation
tcpdump -nn -s 0 -X -i any port <port>
Ring buffer capture by size
tcpdump
Rotate across 5 files of 100MB each so long captures never fill the disk
tcpdump -nn -i any -s 0 -C 100 -W 5 -w /tmp/cap.pcap
Time-rotated capture files
tcpdump
Start a fresh pcap every hour with a timestamped name for unattended capture
tcpdump -nn -i any -G 3600 -w '/tmp/cap-%Y%m%d-%H%M%S.pcap'
Filter an existing pcap offline
tcpdump
Re-filter a saved capture without re-running it; BPF applies on read
tcpdump -nn -r /tmp/cap.pcap 'port 443 and host <ip>'
Show DNS lookups with MAC addresses (-e) to map queries to clients on the LAN
tcpdump -nn -e -i any port 53
Extract fields to columns
tshark
Pull selected fields as a tabular header-prefixed table; pipe to awk/csv tooling
tshark -r cap.pcap -Y http.request -T fields -e ip.src -e http.host -e http.request.uri -E header=y
Follow a TCP stream as ascii
tshark
Reassemble stream index 0 into readable ascii; prefer tshark over wireshark on servers
tshark -r cap.pcap -q -z follow,tcp,ascii,0
TCP conversation statistics
tshark
Rank TCP conversations by bytes/packets to find top talkers in a capture
tshark -r cap.pcap -q -z conv,tcp
Per-second retransmission counts to correlate packet loss with app latency spikes
tshark -i any -q -z io,stat,1,'COUNT(tcp.analysis.retransmission)tcp.analysis.retransmission'
Live top hot functions with caller chains; dwarf unwind works without frame pointers
perf top -g --call-graph dwarf
Sample whole machine at 99Hz for 30s, then print collapsed report; 99Hz dodges lockstep aliasing
perf record -F 99 -a -g -- sleep 30 && perf report --stdio
Flame graph pipeline
perf
Turn perf.data into an interactive flame graph SVG (Brendan Gregg FlameGraph tools)
perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg
Run with three -d for L1/LLC/TLB and stalled-cycle detail; reveals memory-bound vs CPU-bound
perf stat -d -d -d -- ./app
Record context switches then show per-task wakeup latency; find runqueue starvation
perf sched record -- sleep 10 && perf sched latency --sort max
strace-like syscall trace with -s summary; lower overhead, no ptrace stop-the-world
perf trace -s -p <pid>
Add a kprobe with an argument, then record it; inspect kernel internals without rebuilding
perf probe --add 'tcp_sendmsg size' && perf record -e probe:tcp_sendmsg -a -- sleep 5
Syscall count summary
strace
Aggregate syscall counts/time across forks, sorted by time; pinpoints the costly call
strace -c -f -S time -p <pid>
Decode fds with timing
strace
Show paths/sockets behind fds plus per-call duration and timestamps for file ops
strace -yy -T -tt -e trace=%file -p <pid>
Stack trace per syscall
strace
Print user stack on each openat to find which code path opens a file; needs debug symbols
strace -k -e trace=openat -f -p <pid>
Syscall fault injection
strace
Force the 3rd openat to fail with ENOENT to test error handling; chaos testing without code
strace -f -e inject=openat:error=ENOENT:when=3 -p <pid>
Trace signals delivered
strace
Show only signals (SIGTERM/SIGCHLD) and skip syscalls; debug mysterious kills. note: ltrace for libcalls
strace -f -e signal=all -e trace=none -p <pid>
Find owner of port
lsof
Show which process owns a port; -nP skips DNS/service name lookups for speed
lsof -nP -i :<port>
List every TCP listener with PID, no name resolution; modern: ss -ltnp
lsof -nP -iTCP -sTCP:LISTEN
Deleted open files
lsof
Find unlinked files still held open eating disk; df shows full but du does not
lsof +L1
Reveal processes blocking a 'device busy' umount; pass the mountpoint path
lsof /mnt/<name>
Free a stuck port
lsof
Kill whatever owns a port; -t prints bare PIDs, -r avoids running kill on empty input
lsof -t -i:<port> | xargs -r kill
Spot sockets the app forgot to close; growing CLOSE_WAIT = fd/connection leak
lsof -nP -i -sTCP:CLOSE_WAIT
Show only sockets talking to a specific peer host/port, both ends matched
lsof -nP -i @<host>:<port>
Show only mapped executable and shared libs; -a ANDs the filters, great after a deploy
lsof -p <pid> -a -d txt,mem
Quick fd count to spot leaks vs ulimit -n; faster: ls /proc/<pid>/fd | wc -l
lsof -nP -p <pid> | wc -l
Strip headers/stats; show only the answer section for scripting/diffs
dig +noall +answer example.com
Query each authoritative NS directly; reveals SOA serial mismatches between them
dig +nssearch example.com
Dump full zone if AXFR is open; note: success on public NS is a misconfig
dig axfr @ns1.example.com example.com
Show RRSIG records; check AD flag in flags line for validated answer
dig +dnssec +multi example.com @1.1.1.1
Follow delegation from root to authoritative, hiding RRSIG/DS clutter
dig +trace +nodnssec example.com
Spot split-horizon or stale cache differences between resolvers
diff <(dig +short @1.1.1.1 example.com) <(dig +short @8.8.8.8 example.com)
PTR for an IPv6 address; -x expands nibble format automatically
dig -x 2606:4700:4700::1111 +short
Pull SPF, DMARC and DKIM TXT records in one loop for mail audits
for r in example.com _dmarc.example.com sel._domainkey.example.com; do dig +short TXT $r; done
Show which CAs may issue certs; missing CAA lets any CA issue
dig +short CAA example.com
Get priority/weight/port/target for a service; used by AD, SIP, XMPP
dig +short SRV _sip._tcp.example.com
Test TCP/53 reachability; +ttlunits prints TTL as 1h/30m not raw seconds
dig +tcp +ttlunits +noall +answer example.com @8.8.8.8
Catch syntax errors and missing records; run before rndc reload to avoid SERVFAIL
named-checkzone example.com /etc/bind/db.example.com
Clear cache, reload config without restart, verify; note: reload re-reads zones too
rndc flush && rndc reconfig && rndc status
Validate config syntax, then list current leases (expiry, MAC, IP, hostname)
dnsmasq --test && cat /var/lib/misc/dnsmasq.leases
Full certificate inspect
openssl
Dump all cert fields: subject, issuer, validity, extensions, SANs, key usage
openssl x509 -in cert.pem -noout -text
Cert expiry check (CI gate)
openssl
Exit 0 if cert valid >24h; perfect for monitoring/CI alerts on expiry
openssl x509 -in cert.pem -noout -checkend 86400 && echo OK || echo EXPIRING
Inspect live server chain
openssl
Fetch full chain with SNI; -servername is mandatory for vhosts/SNI backends
openssl s_client -connect <host>:443 -servername <host> -showcerts </dev/null 2>/dev/null
Extract SAN list
openssl
Show only SAN entries; modern browsers ignore CN, so SAN is what matters
openssl x509 -in cert.pem -noout -ext subjectAltName
Verify cert against CA chain
openssl
Validate trust chain; note: -CAfile must hold intermediates+root in order
openssl verify -CAfile ca-chain.pem cert.pem
Match cert and private key
openssl
Equal modulus hashes prove key matches cert; empty diff = match
diff <(openssl x509 -in cert.pem -noout -modulus | md5sum) <(openssl rsa -in key.pem -noout -modulus | md5sum)
CSR + key in one shot
openssl
Generate key+CSR with SAN inline; -addext avoids editing openssl.cnf
openssl req -new -newkey rsa:2048 -nodes -keyout key.pem -out req.csr -subj "/CN=<host>" -addext "subjectAltName=DNS:<host>"
Self-signed cert with SAN
openssl
One-liner self-signed cert valid 1y; SAN required or TLS clients reject it
openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 365 -subj "/CN=<host>" -addext "subjectAltName=DNS:<host>"
PEM to PKCS12 bundle
openssl
Bundle cert+key+chain into .p12 for Java keystores / Windows imports
openssl pkcs12 -export -in cert.pem -inkey key.pem -certfile ca-chain.pem -out bundle.p12 -name <name>
STARTTLS protocol probe
openssl
Inspect TLS on STARTTLS services; swap postgres for smtp/imap/mysql/ldap
openssl s_client -connect <host>:5432 -starttls postgres -showcerts </dev/null 2>/dev/null
Generate Ed25519 key
openssl
Modern: Ed25519 keys are tiny and fast vs RSA; use for signing/mTLS
openssl genpkey -algorithm ed25519 -out ed25519.pem
Test specific TLS protocol
openssl
Force a version to confirm support; use -tls1_3 / -no_tls1_2 to test policy
openssl s_client -connect <host>:443 -tls1_2 </dev/null 2>&1 | grep -E 'Protocol|Cipher'
Fail fast on errors, unset vars, pipe failures; split only on newline/tab
set -euo pipefail; IFS=$'\n\t'
Auto-remove mktemp dir on exit/signal; note: quote $tmp to survive spaces
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT INT TERM
Process substitution compares two streams without temp files
diff <(kubectl get cm a -o yaml) <(kubectl get cm b -o yaml)
mapfile -t strips newlines; handles spaces unlike for-loop word splitting
mapfile -t lines < file.txt; printf '%s\n' "${lines[@]}"
basename, strip extension, and global replace without spawning sed/basename
f=/var/log/app.log.gz; echo "${f##*/}" "${f%.*}" "${f//log/LOG}"
Native regex match extracts groups; note: don't quote the right-hand regex
[[ $s =~ ^([0-9]+)\.([0-9]+) ]] && echo "${BASH_REMATCH[1]}/${BASH_REMATCH[2]}"
Run N parallel jobs safely with NUL separators for names with spaces
find . -name '*.log' -print0 | xargs -0 -P"$(nproc)" -n1 gzip
Inspect exit code of every pipe stage; $? only reports the last command
curl -s "$url" | jq .data; echo "${PIPESTATUS[@]}"
getopts flag parsing
bash
POSIX option parsing with arguments; -n takes a value, -v is a switch
while getopts "n:v" o; do case $o in n) ns=$OPTARG;; v) verbose=1;; esac; done
SIGTERM at 30s then SIGKILL after 5s grace; exit 124 means it was killed
timeout -k 5s 30s ./long_task.sh || echo "timed out: $?"
Open fd 3 to a file, write to it independently of stdout, then close it
exec 3>>audit.log; echo "$(date -Is) start" >&3; exec 3>&-
zsh: list only regular files recursively, then mass-rename safely with zmv
setopt extendedglob; print -l **/*(.); autoload zmv; zmv '(*).txt' '$1.bak'
Preserve hardlinks, ACLs, xattrs, raw uid/gid for host migration; note: trailing slash matters
rsync -aHAXv --numeric-ids /src/ user@<host>:/dst/
Itemized dry-run diff
rsync
Preview every change with itemize codes (>f, cd, *deleting) before touching files
rsync -ai --dry-run --delete /src/ /dst/
Throttled transfer
rsync
Cap bandwidth to 10 MB/s to avoid saturating the link; progress2 shows overall ETA
rsync -a --bwlimit=10M --info=progress2 /src/ user@<host>:/dst/
Time-Machine-style backup: unchanged files hardlink to prev, only deltas use new space
rsync -a --delete --link-dest=../prev /src/ ./$(date +%F)/
Resume interrupted big files and verify appended part by checksum; note: only safe if source unchanged
rsync -a --partial --append-verify --info=progress2 big.img user@<host>:/dst/
Tunnel over custom SSH port and skip paths listed in excludes.txt (.git, node_modules, *.tmp)
rsync -a -e "ssh -p 2222" --exclude-from=excludes.txt /src/ user@<host>:/dst/
Checksum-based sync
rsync
Compare by checksum not mtime+size; delete-after avoids removing files until transfer succeeds
rsync -ac --delete-after /src/ /dst/
Level-based incremental backups: snapshot.snar tracks state so only changed files are archived
tar -czg snapshot.snar -f backup-$(date +%F).tgz /data
Copy a tree without intermediate file, preserving perms; add zstd in pipe for slow links
tar c -C /src . | ssh user@<host> 'tar x -C /dst'
Show bytes/ETA via pv while streaming into zstd; du -sb supplies total size for the bar
tar cf - /data | pv -s $(du -sb /data | awk '{print $1}') | zstd -T0 > data.tar.zst
Level 19 with 128MB long-distance window, all cores; great ratio for logs/backups
zstd -19 --long=27 -T0 huge.bin -o huge.bin.zst
Train a dictionary on similar small files, then compress each with it for big ratio gains
zstd --train samples/*.json -o dict.zstd && zstd -D dict.zstd file.json
Inspect a service account's jobs as root; note: -u needs root or sudo
crontab -l -u <name> 2>/dev/null || echo 'no crontab'
Run job at boot
cron
Append @reboot job idempotently; note: no networking guarantee at boot, use systemd for deps
( crontab -l 2>/dev/null; echo '@reboot /usr/local/bin/warmup.sh' ) | crontab -
Tag stdout+stderr into journald/syslog instead of mailing root
*/5 * * * * /opt/job.sh 2>&1 | /usr/bin/logger -t job
Cron PATH is minimal; set PATH/MAILTO at top or jobs fail silently
crontab - <<'EOF'
MAILTO=ops@example.com
PATH=/usr/local/bin:/usr/bin:/bin
0 3 * * * backup.sh
EOF
List which scripts would execute without running them; debugging cron.daily
run-parts --test /etc/cron.daily
modern: transient OnCalendar timer with logs/retries; replaces a crontab line
systemd-run --on-calendar='*-*-* 03:00:00' --unit=backup /opt/backup.sh
One-shot job with at
cron
Schedule a single deferred command; inspect queue with atq, cancel with atrm
at now + 1 hour <<< 'systemctl restart nginx'
Run only when load avg drops below 1.5; note: atd must be running
batch <<< '/opt/heavy-reindex.sh'
Spawn background session and inject a command; survives SSH disconnect
tmux new-session -d -s work && tmux send-keys -t work 'tail -f /var/log/app.log' Enter
Dump last 3000 lines of a pane to a file for triage without attaching
tmux capture-pane -p -S -3000 -t work > /tmp/pane.log
Launch detached, named, logging session; reattach later with screen -r deploy
screen -L -Logfile /tmp/job.log -dmS deploy bash -c './deploy.sh'
4k random read IOPS test; note: --direct=1 bypasses page cache for true device numbers
fio --name=randread --filename=/dev/<id> --rw=randread --bs=4k --iodepth=32 --numjobs=4 --runtime=60 --time_based --direct=1 --group_reporting
4k random write IOPS on a file; note: destroys data if filename is a raw device
fio --name=randwrite --filename=/data/testfile --size=4G --rw=randwrite --bs=4k --iodepth=64 --numjobs=4 --runtime=60 --time_based --direct=1 --group_reporting
Sequential write throughput (MB/s) with large 1M blocks and direct I/O
fio --name=seqwrite --filename=/data/testfile --size=10G --rw=write --bs=1M --iodepth=16 --direct=1 --runtime=60 --time_based --group_reporting
Pure per-IO latency at iodepth=1; reports p99/p99.9/p99.99 tail latency
fio --name=latency --filename=/dev/<id> --rw=randread --bs=4k --iodepth=1 --numjobs=1 --runtime=30 --time_based --direct=1 --percentile_list=99:99.9:99.99
Realistic mixed workload 70% read / 30% write; closer to OLTP than pure tests
fio --name=mixed --filename=/data/testfile --size=8G --rw=randrw --rwmixread=70 --bs=4k --iodepth=32 --numjobs=4 --runtime=120 --time_based --direct=1 --group_reporting
Run short self-test
smartctl
Start SMART short self-test then read its log; non-destructive background test
smartctl -t short /dev/sda && sleep 120 && smartctl -l selftest /dev/sda
Decode SMART attributes
smartctl
Tabulate raw SMART attribute values; watch Reallocated_Sector_Ct and Pending
smartctl -A /dev/sda | awk '$1~/^[0-9]+$/{printf "%-3s %-24s raw=%s\n",$1,$2,$10}'
Full health + error log
smartctl
Full -x dump: health, attributes, error log, temp history; -d auto detects RAID/USB
smartctl -x -d auto /dev/sda | less
Key NVMe wear/health fields; percentage_used>100 means spec endurance exceeded
nvme smart-log /dev/nvme0 | grep -E 'percentage_used|media_errors|critical_warning|temperature'
Surface non-zero NVMe controller errors; pairs with id-ctrl for model/firmware
nvme error-log /dev/nvme0 | grep -A1 'error_count' | grep -v 'error_count.*: 0'
Worst-case durable write speed (no cache, sync each block); note: not an IOPS test
dd if=/dev/zero of=/data/ddtest bs=1M count=1024 oflag=direct,dsync status=progress; rm /data/ddtest
Block-clone whole disk; conv=noerror,sync keeps copying past bad sectors as zeros
dd if=/dev/sda of=/dev/sdb bs=64M conv=noerror,sync status=progress
Pull raw Prometheus metrics from the apiserver without a metrics stack
kubectl get --raw /metrics | grep apiserver_request_total
Check etcd health via apiserver
kubectl
Verify etcd connectivity through the apiserver health endpoint
kubectl get --raw '/healthz/etcd?verbose'
Raw node usage from metrics API; bypasses kubectl top formatting
kubectl get --raw '/apis/metrics.k8s.io/v1beta1/nodes' | jq '.items[] | {name:.metadata.name, cpu:.usage.cpu, mem:.usage.memory}'
Clone pod with a debug container sharing the PID namespace; original stays untouched
kubectl debug <pod> -n <ns> --copy-to=<pod>-dbg --share-processes --image=nicolaka/netshoot -- sleep infinity
Dump the full nested field tree of a resource spec; great for hunting valid fields
kubectl explain deploy.spec --recursive | less
Pause and resume a rollout
kubectl
Batch multiple edits without triggering rollouts, then resume to apply once
kubectl rollout pause deploy/<name> -n <ns>; kubectl rollout resume deploy/<name> -n <ns>
View last applied configuration
kubectl
Show the last-applied-configuration annotation; diff intent vs live state
kubectl apply view-last-applied deploy/<name> -n <ns> -o yaml
Cluster-wide Warning events newest last; fast triage of failing workloads
kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp
List pods in Failed phase across namespaces for cleanup or investigation
kubectl get pods -A --field-selector status.phase=Failed
Wait on a jsonpath condition
kubectl
Block in CI until a Service gets its external IP; works on any jsonpath field
kubectl wait --for=jsonpath='{.status.loadBalancer.ingress[0].ip}' svc/<name> -n <ns> --timeout=120s
Impersonate a user and group
kubectl
Test RBAC as another identity without their kubeconfig; needs impersonate verb
kubectl auth can-i list secrets -n <ns> --as=<name> --as-group=system:serviceaccounts
Surface the most-restarting pods to catch crashloops fast
kubectl get pods -A -o jsonpath='{range .items[*]}{.metadata.namespace}{"\t"}{.metadata.name}{"\t"}{.status.containerStatuses[0].restartCount}{"\n"}{end}' | sort -k3 -rn | head
Show reserved overhead per node; gap = kube/system reservations
kubectl get nodes -o json | jq -r '.items[] | {node:.metadata.name, capCPU:.status.capacity.cpu, allocCPU:.status.allocatable.cpu, capMem:.status.capacity.memory, allocMem:.status.allocatable.memory}'
Build a CM from KEY=VALUE file, then JSON-patch it into a container's envFrom
kubectl create configmap <name> --from-env-file=app.env -n <ns> --dry-run=client -o yaml | kubectl apply -f -; kubectl patch deploy/<name> -n <ns> --type=json -p='[{"op":"add","path":"/spec/template/spec/containers/0/envFrom/-","value":{"configMapRef":{"name":"<name>"}}}]'
Render one template
helm
Render just one manifest to inspect output; note: path is relative to chart root
helm template <name> ./chart --show-only templates/deployment.yaml
Render with fixed kube/API versions for CRD capability gates offline; includes CRDs
helm template <name> ./chart --kube-version 1.29 --api-versions policy/v1 --include-crds
reuse-values pitfall
helm
note: --reuse-values silently keeps stale overrides; --reset-values forces clean merge
helm upgrade --install <name> ./chart --reset-values -f values.yaml
Dump rendered pre/post-install/upgrade hooks to debug failing job ordering
helm get hooks <rel> -n <ns>
Dry-run a rollback
helm
Preview which revision a rollback targets before committing to it
helm history <rel> -n <ns> && helm rollback <rel> <rev> --dry-run -n <ns>
update refreshes Chart.lock from repos; build fetches subcharts from existing lock
helm dependency update ./chart && helm dependency build ./chart
Block until pods ready AND hook Jobs complete; avoids racing on migrations
helm upgrade --install <name> ./chart --wait --wait-for-jobs --timeout 10m -n <ns>
Extract machine-readable deploy state for scripts and gate checks
helm status <rel> -n <ns> -o json | jq '.info.status, .info.last_deployed'
Patch rendered manifests via kustomize without forking the upstream chart
helm upgrade --install <name> ./chart --post-renderer ./kustomize-hook.sh -n <ns>
Vendor an OCI chart locally for inspection or air-gapped installs
helm pull oci://<host>/charts/<name> --version 1.2.3 --untar --untardir ./charts
Apply with diff gate per env
helmfile
apply runs diff first and only syncs changed releases; idempotent gitops loop
helmfile -e prod diff && helmfile -e prod apply
Target release by selector
helmfile
Sync a single labeled release from a large helmfile; modern: -l app=web,tier=fe
helmfile -e prod -l name=<name> apply
Inflate Helm charts in kustomize build
kustomize
Render helmCharts: block to manifests; note: needs helm in PATH
kustomize build --enable-helm ./overlay
Apply a reusable component overlay
kustomize
Mixin reusable patches/resources via components: (Kustomize v4+)
cat <<'EOF' >> kustomization.yaml
components:
- ../../components/monitoring
EOF
Copy a field with replacements
kustomize
modern: replacements: copies a field cross-resource, replaces deprecated vars:
cat <<'EOF' >> kustomization.yaml
replacements:
- source: {kind: ConfigMap, name: cfg, fieldPath: data.host}
targets:
- select: {kind: Deployment}
fieldPaths: [spec.template.spec.containers.0.env.0.value]
EOF
Inline patch with target selector
kustomize
JSON6902 patch applied to all matching targets, no separate file
cat <<'EOF' >> kustomization.yaml
patches:
- target: {kind: Deployment, labelSelector: app=api}
patch: |-
- op: replace
path: /spec/replicas
value: 3
EOF
Pin image by digest and rename
kustomize
Pin by immutable digest; newName+digest also settable in images: block
kustomize edit set image app=registry.example.com/app@sha256:<id>
Secret generator without hash suffix
kustomize
note: disableNameSuffixHash keeps stable name but breaks rollout-on-change
cat <<'EOF' >> kustomization.yaml
secretGenerator:
- name: db-creds
literals: [PASSWORD=s3cr3t]
generatorOptions:
disableNameSuffixHash: true
EOF
TLS Gateway listener with cert ref
gateway-api
Terminate TLS at the gateway via certificateRefs to a Secret
kubectl apply -f - <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata: {name: gw, namespace: <ns>}
spec:
gatewayClassName: <name>
listeners:
- name: https
protocol: HTTPS
port: 443
tls:
mode: Terminate
certificateRefs: [{name: tls-cert}]
EOF
Register CRD OpenAPI for merge keys
kustomize
Teach kustomize CRD merge/list semantics so patches merge correctly
cat <<'EOF' >> kustomization.yaml
openapi:
path: crd-schema.json
EOF
Check HTTPRoute Accepted condition
gateway-api
Inspect Accepted/ResolvedRefs status to debug why a route is not attached
kubectl describe httproute <name> -n <ns> | grep -A8 Conditions
Inventory Gateway API resources
gateway-api
One-shot view of classes, gateways and routes across all namespaces
kubectl get gatewayclass,gateway,httproute -A
Weighted canary HTTPRoute
gateway-api
Split traffic 90/10 across stable and canary backends by weight
kubectl apply -f - <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: {name: web, namespace: <ns>}
spec:
parentRefs: [{name: gw}]
rules:
- backendRefs:
- {name: web-stable, port: 80, weight: 90}
- {name: web-canary, port: 80, weight: 10}
EOF
Allow cross-namespace route with ReferenceGrant
gateway-api
Permit HTTPRoute in edge ns to target Services in backend ns
kubectl apply -f - <<'EOF'
apiVersion: gateway.networking.k8s.io/v1beta1
kind: ReferenceGrant
metadata: {name: allow-routes, namespace: backend}
spec:
from: [{group: gateway.networking.k8s.io, kind: HTTPRoute, namespace: edge}]
to: [{group: "", kind: Service}]
EOF
Inspect endpoint internals
cilium
Dump full endpoint state: identity, policy enforcement, BPF maps; run inside cilium pod
cilium-dbg endpoint get <id> -o json | jq '.status.policy'
Datapath load balancer table
cilium
List service VIP-to-backend mappings in BPF; verify kube-proxy-free LB programming
cilium-dbg bpf lb list
Conntrack table entries
cilium
Inspect BPF connection-tracking entries; spot stale/leaking flows on a node
cilium-dbg bpf ct list global | head
Trace policy by identity
cilium
Explain allow/deny verdict between two security identities; debug NetworkPolicy drops
cilium-dbg policy trace --src-identity <id> --dst-identity <id> --dport <port>
Verbose agent health
cilium
Full per-node health: datapath mode, IPAM, BPF maps, controllers; first stop on issues
cilium status --verbose
Observe TCP egress to FQDN
cilium
Live L3/L7 flows from a pod to a DNS name; validate FQDN-based egress policy
hubble observe --protocol tcp --from-pod <ns>/<pod> --to-fqdn '*.example.com'
ClusterMesh status
cilium
Check cross-cluster connectivity and remote endpoint/identity sync health
cilium clustermesh status --wait
BPF NAT table
cilium
List BPF masquerade/NAT entries; debug SNAT port exhaustion or egress source IP
cilium-dbg bpf nat list | head
BGP peer status per node
calico
Show BGP session states and peer IPs from a node; Established means routes exchanged
calicoctl node status
Inspect IP pools
calico
List pools with CIDR, IPIP/VXLAN mode, NAT-outgoing; verify encapsulation settings
calicoctl get ippool -o wide
Dump Felix configuration
calico
Read live Felix dataplane config: BPF mode, log level, MTU, iptables backend
calicoctl get felixconfiguration default -o yaml
IPAM allocation by block
calico
Show per-block IP utilization; find pod-IP exhaustion before scheduling fails
calicoctl ipam show --show-blocks
Dump effective nginx config
ingress-nginx
Render the full live nginx.conf with all server blocks the controller actually generated
kubectl exec deploy/ingress-nginx-controller -n ingress-nginx -- nginx -T | less
Controller status metrics
ingress-nginx
Live active connections, reading/writing/waiting counters from the stub_status endpoint
kubectl exec deploy/ingress-nginx-controller -n ingress-nginx -- curl -s localhost:10254/nginx_status
Grep upstream timeouts in logs
ingress-nginx
Hunt backend timeouts and client-aborted requests; note: 499 means client closed before upstream replied
kubectl logs -n ingress-nginx deploy/ingress-nginx-controller --tail=2000 | grep -iE 'upstream timed out|504|499'
Canary traffic split annotation
ingress-nginx
Route 20% of traffic to a canary ingress; needs a primary ingress on the same host/path
kubectl annotate ingress <name> -n <ns> nginx.ingress.kubernetes.io/canary=true nginx.ingress.kubernetes.io/canary-weight="20"
Rate limit and body size annotations
ingress-nginx
Cap requests-per-second per client IP and raise upload limit; rps burst defaults to 5x
kubectl annotate ingress <name> -n <ns> nginx.ingress.kubernetes.io/limit-rps="10" nginx.ingress.kubernetes.io/proxy-body-size="50m"
Rewrite-target with capture group
ingress-nginx
Strip a path prefix via regex capture; path must use (/|$)(.*) for $2 to resolve
kubectl annotate ingress <name> -n <ns> nginx.ingress.kubernetes.io/rewrite-target='/$2' nginx.ingress.kubernetes.io/use-regex='true'
List ingressclasses and default
ingress-nginx
Show controllers and which IngressClass is default; only one should be marked default
kubectl get ingressclass -o custom-columns='NAME:.metadata.name,DEFAULT:.metadata.annotations.ingressclass\.kubernetes\.io/is-default-class'
Force certificate renewal
cert-manager
Trigger immediate reissue without waiting for the renewal window; watch a new CertificateRequest spawn
cmctl renew <name> -n <ns>
Certificate status playbook
cert-manager
End-to-end view: Certificate, Request, Order, Challenge and the exact ACME failure reason
cmctl status certificate <name> -n <ns>
Inspect issued secret contents
cert-manager
Decode the tls.crt and show issuer, SANs, validity without manual openssl x509 piping
cmctl inspect secret <name> -n <ns>
DNS01 Route53 ClusterIssuer
cert-manager
DNS01 issuer for wildcard certs; IRSA/secret must grant route53 change-record perms
kubectl apply -f - <<EOF
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-dns
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
privateKeySecretRef:
name: letsencrypt-dns
solvers:
- dns01:
route53:
region: us-east-1
hostedZoneID: <id>
EOF
Stuck ACME challenges
cert-manager
List pending validations and read the propagation/self-check error blocking issuance
kubectl get challenges -A -o wide && kubectl describe challenge -n <ns> <name>
Trace record reconciliation
external-dns
Watch which DNS records external-dns adds or removes; note: needs --policy=sync to delete stale ones
kubectl logs deploy/external-dns -n external-dns -f | grep -iE 'CREATE|UPDATE|DELETE|record'
Verify metrics API availability
metrics-server
Confirm the aggregated API is healthy; if FailedDiscovery add --kubelet-insecure-tls on self-signed kubelets
kubectl get apiservice v1beta1.metrics.k8s.io -o jsonpath='{.status.conditions[?(@.type=="Available")].message}{"\n"}'
Init HA control-plane endpoint
kubeadm
Bootstrap HA cluster behind a LB VIP; --upload-certs shares CA for other masters
kubeadm init --control-plane-endpoint "<host>:6443" --upload-certs --pod-network-cidr=10.244.0.0/16
Print fresh join command
kubeadm
Generate a new token + ready-to-paste worker join line; default tokens expire in 24h
kubeadm token create --print-join-command
Check cert expiration
kubeadm
List all control-plane cert/kubeconfig expiry dates; catch silent apiserver outages early
kubeadm certs check-expiration
Renew all certs then restart
kubeadm
Renew every control-plane cert; note: restart static pods (mv manifests) for them to reload
kubeadm certs renew all && systemctl restart kubelet
Plan and apply upgrade
kubeadm
Preview available versions then upgrade control-plane; upgrade kubelet/kubectl separately after
kubeadm upgrade plan && kubeadm upgrade apply v1.30.2
Single-node k3s minus bundled Traefik/LB; bring your own ingress + MetalLB instead
curl -sfL https://get.k3s.io | sh -s - --disable traefik --disable servicelb
First server with embedded etcd HA; join more with --server https://<ip>:6443 same token
curl -sfL https://get.k3s.io | sh -s - server --cluster-init --token <id>
Add a worker; node-token lives on the server under /var/lib/rancher/k3s/server
curl -sfL https://get.k3s.io | K3S_URL=https://<ip>:6443 K3S_TOKEN=$(cat /var/lib/rancher/k3s/server/node-token) sh -
Use bundled crictl/ctr to debug pods/images when kubectl is down; talks to containerd directly
k3s crictl ps -a && k3s ctr images ls -q
Declarative server config + enable unit; add tls-san so the LB hostname is in the API cert
printf 'token: <id>\ntls-san:\n - <host>\n' > /etc/rancher/rke2/config.yaml && systemctl enable --now rke2-server
rke2 ships its own kubectl/crictl/ctr under /var/lib/rancher/rke2/bin, not in $PATH by default
export PATH=$PATH:/var/lib/rancher/rke2/bin KUBECONFIG=/etc/rancher/rke2/rke2.yaml && rke2 ctr images ls
Show leader, DB size and raft index per member; spot bloat and split-brain at a glance
ETCDCTL_API=3 etcdctl --endpoints=https://<ip>:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key endpoint status --cluster -w table
Back up etcd then reclaim space; defrag clears NOSPACE alarm after compaction; do off-peak
ETCDCTL_API=3 etcdctl snapshot save /backup/snap.db && etcdctl defrag --cluster && etcdctl alarm disarm
Verify apiserver health + which node holds scheduler/CM leader election lease
curl -sk https://localhost:6443/healthz && kubectl -n kube-system get lease kube-scheduler kube-controller-manager
Top pods by restart count
k8s-debug
Rank pods cluster-wide by restart count to spot crash loops fast
kubectl get po -A --sort-by='.status.containerStatuses[0].restartCount' | tail -20
Detect OOMKilled containers
k8s-debug
List pods whose last container exit was OOMKilled across all namespaces
kubectl get po -A -o jsonpath='{range .items[*]}{.metadata.namespace}{" "}{.metadata.name}{" "}{.status.containerStatuses[*].lastState.terminated.reason}{"\n"}{end}' | grep OOMKilled
Pending pods scheduling reason
k8s-debug
Extract FailedScheduling reasons for every Pending pod (taints, resources, affinity)
kubectl get po -A --field-selector=status.phase=Pending -o name | xargs -I{} kubectl describe {} -n <ns> | grep -A3 FailedScheduling
Node NotReady triage
k8s-debug
Read node Conditions then tail kubelet journal to find why node is NotReady
kubectl describe node <node> | grep -A12 Conditions; ssh <node> 'journalctl -u kubelet -n 100 --no-pager'
ImagePullBackOff root cause
k8s-debug
Surface registry pull failures: bad tag, missing imagePullSecret, or rate limit
kubectl get events -n <ns> --field-selector reason=Failed -o wide | grep -i 'pull\|manifest\|unauthorized'
Cleanup evicted pods
k8s-debug
Bulk-delete all Evicted pods left behind by node-pressure eviction
kubectl get po -A | grep Evicted | awk '{print $2" -n "$1}' | xargs -L1 kubectl delete po
Force-remove stuck Terminating pod
k8s-debug
Clear finalizers to unstick a pod hung in Terminating; note: confirm node is gone first
kubectl patch po <pod> -n <ns> -p '{"metadata":{"finalizers":null}}' --type=merge; kubectl delete po <pod> -n <ns> --grace-period=0 --force
Raw kubelet stats summary
k8s-debug
Pull live per-pod memory from kubelet Summary API, bypassing metrics-server
kubectl get --raw /api/v1/nodes/<node>/proxy/stats/summary | jq '.pods[] | {name:.podRef.name, mem:.memory.workingSetBytes}'
Conntrack stats on node
k8s-debug
Check per-CPU conntrack drops/insert_failed; nf_conntrack table exhaustion drops packets
kubectl debug node/<node> -it --image=nicolaka/netshoot -- conntrack -S
In-cluster DNS resolution test
k8s-debug
Resolve a Service FQDN from an ephemeral pod to isolate CoreDNS vs app DNS issues
kubectl run dnstest --rm -it --image=nicolaka/netshoot --restart=Never -- dig +short <name>.<ns>.svc.cluster.local
Ordered events for a pod
k8s-debug
Stream only Warning events scoped to one pod in chronological order; modern: replaces get events filter
kubectl events --for pod/<pod> -n <ns> --types=Warning
Previous crash logs with timestamps
k8s-debug
Tail the crashed container's prior instance logs to catch the pre-restart stack trace
kubectl logs <pod> -n <ns> -c <name> --previous --timestamps --tail=200
OCI source by semver
flux
Track an OCI artifact by semver range instead of git; modern: GitOps from a registry
flux create source oci <name> --url=oci://reg/repo --tag-semver='>=1.0.0' --interval=5m
Package manifests into an OCI artifact tagged by commit; note: embeds source+revision metadata
flux push artifact oci://reg/manifests:$(git rev-parse --short HEAD) --path=./manifests --source=$(git config --get remote.origin.url) --revision=$(git rev-parse HEAD)
Server-side dry-run showing exactly what Flux would change before applying
flux diff kustomization <name> --path ./overlays/prod
List every object a kustomization owns, including nested kustomizations
flux tree kustomization <name>
Render the final manifests offline with Flux substitutions, then validate server-side
flux build kustomization <name> --path ./ | kubectl apply --dry-run=server -f -
Show all ImageRepositories, policies and update automations across namespaces
flux get images all -A
See which tag each policy selected and last scan results per repository
flux get image policy -A && flux get image repository -A
Slack alert pipeline
flux
Wire reconcile events to Slack via a provider+alert; note: webhook lives in a secret
flux create provider slack --type slack --secret-ref webhook && flux create alert prod --provider-ref slack --event-source 'Kustomization/*' --event-severity info
Generate a webhook URL so git pushes trigger instant reconcile instead of polling
flux create receiver github --type github --event github:push --secret-ref webhook-token --resource GitRepository/<name>
Pull the latest commit now without touching dependent kustomizations
flux reconcile source git <name>
Stream the reconcile event history for one object to diagnose drift or failures
flux events --for Kustomization/<name>
Block app reconcile until infra kustomization is ready; note: enforces apply ordering
flux create kustomization app --source=GitRepository/<name> --path=./app --depends-on=infra --prune=true --interval=10m
Override Helm value at sync
argocd
Override Helm values live without touching Git; note: drifts from source until committed
argocd app set <name> --helm-set image.tag=v2 --helm-set replicaCount=3
Set plain parameter override
argocd
Set Kustomize/Helm parameter overrides via -p; modern: prefer Git-tracked overlays for audit
argocd app set <name> -p key=val -p env=prod
Diff Argo-rendered manifests against live cluster state before syncing
argocd app manifests <name> | kubectl diff -f -
Inspect ApplicationSet
argocd
List/get ApplicationSets and their generated child apps and generators
argocd appset list && argocd appset get <name> -o yaml
Register HTTPS repo with creds; modern: --ssh-private-key-path for SSH-based access
argocd repo add https://git.example.com/repo.git --username <id> --password $TOKEN
Patch app spec inline
argocd
Merge-patch app spec without editing the CR; useful to bump targetRevision fast
argocd app patch <name> --patch '{"spec":{"source":{"targetRevision":"v2.1"}}}' --type merge
Cancel an in-progress sync stuck on a hook or pending resource
argocd app terminate-op <name>
Run resource restart action
argocd
Trigger a Deployment rollout restart through Argo's resource actions
argocd app actions run <name> restart --kind Deployment --resource-name <id>
Add project sync window
argocd
Create a deny sync window to freeze deploys during off-hours; cron-based schedule
argocd proj windows add <name> --kind deny --schedule '0 0 * * *' --duration 8h --applications '*'
Set sync options for safe prune and SSA; note: SSA fixes large-CRD apply conflicts
argocd app set <name> --sync-option Prune=true --sync-option ServerSideApply=true
Backup all Argo objects
argocd
Export/import all apps, projects and settings for DR; cluster-secret aware
argocd admin export -n argocd > argo-backup.yaml # restore: argocd admin import -n argocd - < argo-backup.yaml
Sync only one resource by group:kind:name; isolates a fix without full app sync
argocd app sync <name> --resource apps:Deployment:<id>
Build matrix from bake file
docker
Build/push multiple targets from one HCL file; parallel, DRY group definitions
docker buildx bake -f docker-bake.hcl --push
Inspect multi-arch manifest
docker
Show platforms in a manifest list without pulling layers; verify arm64+amd64
docker buildx imagetools inspect <reg>/<name>:tag --format '{{json .Manifest}}'
Registry build cache
buildkit
Persist full layer cache in a registry for CI; mode=max caches intermediate stages
docker buildx build --cache-to type=registry,ref=<reg>/cache,mode=max --cache-from type=registry,ref=<reg>/cache -t <reg>/<name> --push .
Container driver builder
docker
Create a BuildKit builder supporting multi-arch and cache export; default driver cannot
docker buildx create --name multi --use --driver docker-container --driver-opt network=host
Persistent cache mount in RUN
buildkit
Reuse package cache across builds without bloating layers; survives between runs
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
Secret mount during build
buildkit
Use a secret file in one RUN without baking it into any layer; pair with --secret
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
SSH forward for private repos
buildkit
Forward host SSH agent into build to clone private git; key never enters the image
docker buildx build --ssh default -t <name> . # Dockerfile: RUN --mount=type=ssh git clone git@host:repo
Pass build secret from file
docker
Feed a secret to BuildKit; only RUN --mount=type=secret,id=token sees it, not history
docker buildx build --secret id=token,src=token.txt -t <name> .
Remote daemon over SSH
docker
Run docker against a remote daemon over SSH; no exposed TCP socket needed
docker context create remote --docker host=ssh://<host> && docker context use remote
Hardened read-only container
docker
Immutable rootfs, writable /tmp only, block privilege escalation; container hardening
docker run --read-only --tmpfs /tmp --security-opt no-new-privileges --cap-drop ALL <name>
Watch for OOM kills
docker
Stream live OOM events to catch memory-limited containers being killed
docker events --filter event=oom --filter type=container
Analyze layer efficiency and fail the build if too much space is wasted
CI=true dive --lowestEfficiency 0.95 --highestWastedBytes 20MB <reg>/<name>:tag
Container as systemd unit
podman
Emit a portable .service that recreates the container on start; note: Quadlet is the modern way
podman generate systemd --new --files --name <name>
Reverse-engineer a running pod into a K8s manifest for migration to a cluster
podman generate kube <pod> > pod.yaml
Run Kubernetes YAML locally
podman
Spin up pods/services from a K8s manifest with no cluster; --replace re-applies cleanly
podman play kube pod.yaml --replace
Inspect the user-namespace uid range backing rootless containers; fix perms via chown inside unshare
podman unshare cat /proc/self/uid_map; cat /etc/subuid
Auto-update from registry
podman
Pull newer images and restart labeled containers; needs io.containers.autoupdate=registry label
podman auto-update --dry-run && systemctl --user start podman-auto-update
Refresh OCI runtime and user-namespace config after a podman/kernel upgrade; fixes stale containers
podman system migrate
Dump runtime info, cgroup path, mounts and pid for a CRI container kubectl can't show
crictl inspect <id> | jq '.info'
Clean up orphaned NotReady pod sandboxes the kubelet failed to GC; node-level recovery
crictl rmp -f $(crictl pods -q --state NotReady)
Prune images on a node
crictl
Reclaim disk by deleting images not referenced by any container; safe node disk-pressure fix
crictl rmi --prune
containerd stores k8s images under the k8s.io namespace; default namespace looks empty
ctr -n k8s.io images ls
Show containerd tasks with pid/status when the kubelet or CRI layer is unresponsive
ctr -n k8s.io task ls
Compose stack on containerd
nerdctl
Run docker-compose.yml directly on containerd, no Docker daemon; great for k8s-node parity
nerdctl --namespace k8s.io compose up -d
Daemonless registry-to-registry migration without pulling locally; preserves digests
skopeo copy --src-creds u:p --dest-creds u:p docker://<host>/<name> docker://<host>/<name>
Read labels, arch and layers of a remote image cheaply; modern: add --raw for the manifest list
skopeo inspect docker://<host>/<name> | jq '.Labels, .Architecture, .Created'
95th percentile latency from histogram
prometheus
p95 latency per job; note: always aggregate _bucket by le before histogram_quantile
histogram_quantile(0.95, sum by(le,job)(rate(http_request_duration_seconds_bucket[5m])))
Predict disk full window
prometheus
alert when linear trend predicts disk full within 4h based on last 6h
predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 4*3600) < 0
Detect dead target with absent
prometheus
fires when no series match; catches a job that vanished from discovery entirely
absent(up{job="node"} == 1)
Rewrite label with label_replace
prometheus
extract/derive a new label via regex capture; useful for joins and tidy dashboards
label_replace(node_uname_info, "host", "$1", "nodename", "(.+)")
Max of per-second rate over window
prometheus
subquery: peak 5m rate sampled each minute over the last hour; spot bursts
max_over_time(rate(node_network_receive_bytes_total[5m])[1h:1m])
Aggregate keeping all labels but instance
prometheus
without() keeps every label except instance; cleaner than listing many by() labels
sum without(instance) (rate(http_requests_total{code=~"5.."}[5m]))
Recording rule for expensive ratio
prometheus
precompute SLO error ratio to keep dashboards and alerts fast
groups:
- name: slo
rules:
- record: job:request_errors:ratio5m
expr: sum by(job)(rate(http_requests_total{code=~"5.."}[5m])) / sum by(job)(rate(http_requests_total[5m]))
Validate rules and config with promtool
prometheus
lint before reload; run in CI to catch broken expr/yaml before deploy
promtool check rules rules.yml && promtool check config prometheus.yml
Instant query from CLI
prometheus
run PromQL without a browser; great for scripted top-N investigations
promtool query instant http://localhost:9090 'topk(5, sum by(pod)(rate(container_cpu_usage_seconds_total[5m])))'
Find cardinality offenders in TSDB
prometheus
lists highest-cardinality metrics and label pairs; first stop for memory blowups
promtool tsdb analyze /prometheus --limit 20
Silence an alert with amtool
alertmanager
scoped time-boxed silence by matchers; expire early with amtool silence expire <id>
amtool silence add alertname=HighLatency cluster=prod --duration 2h --comment 'deploy in progress'
Test routing tree without firing
alertmanager
shows which receiver a label set hits; validate routes before pushing config
amtool config routes test --config.file=alertmanager.yml severity=critical team=db
Inspect TSDB cardinality status
victoriametrics
top metrics by series count in VictoriaMetrics; pinpoint label explosions fast
curl -s 'http://vm:8428/api/v1/status/tsdb?topN=10' | jq '.data.seriesCountByMetricName'
Consistent backup of VM storage
victoriametrics
snapshot then vmbackup to S3 for a consistent copy; vmrestore reverses it
curl -s http://vm:8428/snapshot/create | jq -r .snapshot | xargs -I{} vmbackup -storageDataPath=/vmdata -snapshotName={} -dst=s3://bucket/vm
Filter by substring, parse JSON, render only chosen fields. note: | json before line_format.
{app="api"} |= "error" | json | line_format "{{.level}} {{.msg}}"
Per-level log rate
loki
Logs/sec grouped by level over 5m window. modern: logfmt parser for key=value lines.
sum by (level) (rate({app="api"} | logfmt [5m]))
p99 latency from a numeric log field per route. note: unwrap needs a numeric label/field.
quantile_over_time(0.99, {app="api"} | json | unwrap latency_ms [5m]) by (route)
Count regex-matched error lines per minute across a namespace. |~ is regex match.
sum(count_over_time({namespace="prod"} |~ "timeout|deadline exceeded" [1m]))
logcli ad-hoc query
loki
CLI query for last hour with line cap and JSONL output. set LOKI_ADDR env first.
logcli query '{job="app/api"} |= "panic"' --since=1h --limit=200 --output=jsonl
Run a range metric query over HTTP and extract result with jq. step is in seconds.
curl -sG "$LOKI_ADDR/loki/api/v1/query_range" --data-urlencode 'query=sum(rate({app="api"}[5m]))' --data-urlencode 'step=60' | jq '.data.result'
Manually push a log entry to verify ingestion. note: timestamp must be ns epoch.
curl -s -H 'Content-Type: application/json' -XPOST "$LOKI_ADDR/loki/api/v1/push" -d '{"streams":[{"stream":{"app":"test"},"values":[["'$(date +%s%N)'","hello loki"]]}]}'
Find error spans on a service slower than 2s. combine attribute, status and duration.
{ .service.name = "api" && status = error && duration > 2s }
TraceQL search via API
tempo
Search traces by TraceQL over HTTP and list matching trace IDs. limit caps results.
curl -sG "$TEMPO_ADDR/api/search" --data-urlencode 'q={ .http.status_code >= 500 }' --data-urlencode 'limit=20' | jq '.traces[].traceID'
Fetch full trace by ID
tempo
Pull a trace by ID and compute per-span duration. note: times are unix nanos.
curl -s "$TEMPO_ADDR/api/traces/<id>" | jq '.batches[].scopeSpans[].spans[] | {name, durationNs: (.endTimeUnixNano|tonumber)-(.startTimeUnixNano|tonumber)}'
Validate collector config
opentelemetry
Statically check collector pipeline before reload. catches bad receivers/processors/exporters.
otelcol validate --config=/etc/otelcol/config.yaml
Configure OTLP exporter via env
opentelemetry
Auto-instrumentation endpoint and resource attrs without code change. 4317=gRPC, 4318=HTTP.
export OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4317 OTEL_RESOURCE_ATTRIBUTES=service.name=api,deployment.environment=prod
Send OTLP trace via curl
opentelemetry
Smoke-test the OTLP HTTP receiver with a sample payload. note: 4318 path, not 4317.
curl -s -XPOST http://collector:4318/v1/traces -H 'Content-Type: application/json' -d @trace.json -w '%{http_code}'
Live tap component output
vector
Stream live events flowing out of a transform for debugging VRL. modern: vector top for rates.
vector tap --outputs-of parse_logs
Trigger workflow with inputs
github-actions
Dispatch a workflow_dispatch run passing typed inputs; note: needs workflow_dispatch trigger
gh workflow run deploy.yml -f env=prod -f version=1.4.2 --ref main
Watch latest run live
github-actions
Stream the newest run's progress live and exit with its status code
gh run watch $(gh run list -w deploy.yml -L1 --json databaseId -q '.[0].databaseId')
Show only failed logs
github-actions
Print logs of failed steps only, skipping noise from passing jobs
gh run view <id> --log-failed | less -R
Run a job locally with act
github-actions
Run an Actions job in Docker locally before pushing; note: pin a real runner image
act -j build --secret-file .secrets -P ubuntu-latest=catthehacker/ubuntu:act-22.04
Rerun only failed jobs
github-actions
Retry just the failed jobs of a run, reusing prior successful results
gh run rerun <id> --failed
List and prune caches
github-actions
Find the biggest Actions caches and delete stale ones to free quota
gh cache list --sort size_in_bytes --order desc; gh cache delete <id>
OIDC keyless cloud auth
github-actions
Job-level perms enabling OIDC token to assume a cloud role without static keys
permissions:
id-token: write
contents: read
Register a runner by token
gitlab-ci
Register a runner with the new auth token; note: legacy registration-token is deprecated
gitlab-runner register --non-interactive --url https://<host> --token glrt-<id> --executor docker --docker-image alpine:latest
Prune dead runners
gitlab-ci
Verify configured runners and unregister ones GitLab no longer recognizes
gitlab-runner verify --delete
Trigger pipeline via API
gitlab-ci
Kick off a pipeline from outside CI with a trigger token and custom vars
curl -X POST -F token=$CI_TOKEN -F ref=main -F 'variables[DEPLOY]=true' https://<host>/api/v4/projects/<id>/trigger/pipeline
Run CI job locally
gitlab-ci
Run a .gitlab-ci.yml job locally in Docker; note: replaces removed gitlab-runner exec
gitlab-ci-local --job build
Build job via CLI and follow
jenkins
Trigger a job and block until it finishes, streaming console output (-f -v)
java -jar jenkins-cli.jar -s https://<host> -auth user:token build <name> -f -v
Validate declarative pipeline
jenkins
Lint a Jenkinsfile server-side before commit to catch syntax errors early
curl -X POST -F "jenkinsfile=<Jenkinsfile" https://<host>/pipeline-model-converter/validate
Tail logs of the most recent PipelineRun across all its TaskRuns
tkn pipelinerun logs -f --last -n <ns>
Confirm active account, ARN and assumed role before running risky commands
aws sts get-caller-identity --query '{acct:Account,arn:Arn}' --output table
Assume an IAM role and inject temp creds into the shell env in one shot
eval $(aws sts assume-role --role-arn <id> --role-session-name ops --query 'Credentials.[`AWS_ACCESS_KEY_ID=`+AccessKeyId,`AWS_SECRET_ACCESS_KEY=`+SecretAccessKey,`AWS_SESSION_TOKEN=`+SessionToken]' --output text | sed 's/^/export /')
List running prod instances with id, private IP and AZ via JMESPath projection
aws ec2 describe-instances --filters Name=tag:Env,Values=prod Name=instance-state-name,Values=running --query 'Reservations[].Instances[].{id:InstanceId,ip:PrivateIpAddress,az:Placement.AvailabilityZone}' --output table
Mirror dir to bucket; --delete removes stale keys. note: --size-only skips mtime checks
aws s3 sync ./ s3://<name>/ --delete --exclude '*.tmp' --exclude '.git/*' --size-only
Generate a time-limited download URL without making the object public
aws s3 presign s3://<name>/path/file.tgz --expires-in 3600
Add/refresh an EKS context with a clean alias instead of the long ARN
aws eks update-kubeconfig --name <cluster> --region <id> --alias <cluster> --kubeconfig ~/.kube/config
ECR docker login
aws
Auth Docker to ECR via stdin so the token never lands in shell history
aws ecr get-login-password --region <id> | docker login --username AWS --password-stdin <id>.dkr.ecr.<id>.amazonaws.com
Open an interactive shell on an instance with no open port 22 or bastion
aws ssm start-session --target i-<id> --region <id>
Live-stream a log group like tail -f. modern: replaces clunky filter-log-events polling
aws logs tail /aws/lambda/<name> --follow --since 10m --format short
Test if a principal can do an action before granting; explains allow/deny
aws iam simulate-principal-policy --policy-source-arn <id> --action-names s3:GetObject --resource-arns <id> --query 'EvaluationResults[].{action:EvalActionName,decision:EvalDecision}' --output table
Fetch a JSON secret and extract one field. note: value appears in process args
aws secretsmanager get-secret-value --secret-id <name> --query SecretString --output text | jq -r '.password'
Sort current spot history to find the cheapest AZ for an instance type
aws ec2 describe-spot-price-history --instance-types m6i.large --product-descriptions 'Linux/UNIX' --start-time $(date -u +%Y-%m-%dT%H:%M:%S) --query 'sort_by(SpotPriceHistory,&SpotPrice)[0:5].[AvailabilityZone,SpotPrice]' --output table
Idempotent deploy; CAPABILITY_NAMED_IAM required when template creates IAM roles
aws cloudformation deploy --template-file stack.yaml --stack-name <name> --capabilities CAPABILITY_NAMED_IAM --parameter-overrides Env=prod --no-fail-on-empty-changeset
Count unattached EBS volumes in one call using length(); --profile/--region scope it
aws ec2 describe-volumes --filters Name=status,Values=available --query 'length(Volumes[])' --output text --profile staging --region <id>
Activate service account
gcloud
Auth as SA in CI; note: prefer workload identity over long-lived key files
gcloud auth activate-service-account --key-file=key.json && gcloud config set project <id>
GKE kubeconfig credentials
gcloud
Fetch GKE kubeconfig; modern: needs gke-gcloud-auth-plugin in PATH since k8s 1.26
gcloud container clusters get-credentials <cluster> --region <id> --project <id>
Custom table of running VMs and public IPs via --format/--filter projections
gcloud compute instances list --format="table(name,status,EXTERNAL_IP)" --filter="status=RUNNING"
Audit who has which role; --flatten explodes nested bindings into rows
gcloud projects get-iam-policy <id> --flatten="bindings[].members" --format="table(bindings.role,bindings.members)"
Read recent error logs
gcloud
Pull last hour of errors across project; --freshness avoids full scan
gcloud logging read 'severity>=ERROR' --limit 20 --freshness=1h --format='value(timestamp,resource.type,textPayload)'
SSH via IAP tunnel
gcloud
Reach a VM with no public IP through Identity-Aware Proxy; no bastion needed
gcloud compute ssh <name> --zone <id> --tunnel-through-iap
Read secret payload
gcloud
Print latest Secret Manager version to stdout; pin a version in CI for repeatability
gcloud secrets versions access latest --secret=<name> --project <id>
Storage rsync to bucket
gcloud
Mirror dir to GCS; -d deletes extras, modern replacement for gsutil rsync
gcloud storage rsync -r -d ./build gs://<name>/site
Non-interactive auth for CI; modern: use --federated-token for OIDC, no secret
az login --service-principal -u <id> -p "$AZ_SECRET" --tenant <id>
Merge AKS context into kubeconfig; --admin bypasses Azure AD RBAC if enabled
az aks get-credentials -g <name> -n <cluster> --overwrite-existing
Extract raw secret with no quotes via --query/-o tsv; safe to pipe into env
az keyvault secret show --vault-name <name> --name <name> --query value -o tsv
-d enriches with runtime IP/power state; plain list omits these fields
az vm list -d -o table --query "[].{name:name,ip:publicIps,state:powerState}"
Purge cache by URL
cloudflare
Selective purge by file; note: purge_everything thrashes cache, avoid in prod
curl -sX POST "https://api.cloudflare.com/client/v4/zones/<id>/purge_cache" -H "Authorization: Bearer $CF_TOKEN" -H 'Content-Type: application/json' --data '{"files":["https://<host>/app.js"]}'
Create proxied DNS record
cloudflare
Add A record behind CF proxy; proxied=true requires ttl=1 (auto)
curl -sX POST "https://api.cloudflare.com/client/v4/zones/<id>/dns_records" -H "Authorization: Bearer $CF_TOKEN" -H 'Content-Type: application/json' --data '{"type":"A","name":"<host>","content":"<ip>","proxied":true,"ttl":1}'
Set default folder-id for the active profile; verify with config list
yc config set folder-id <id> && yc config list
Isolate creds per env; use yc --profile prod or YC_PROFILE in CI
yc config profile create prod && yc config profile activate prod
OAuth->IAM token, ~12h TTL; feed to API/Terraform via YC_TOKEN env
export YC_TOKEN=$(yc iam create-token)
Create SA for pipelines; bind least-privilege roles separately
yc iam service-account create --name sa-ci --description 'CI deployer'
Authorized key JSON for non-interactive auth; note: rotate & vault it
yc iam key create --service-account-name sa-ci --output key.json
Scope-bind a role at folder level; prefer narrow roles over editor
yc resource-manager folder add-access-binding <id> --role editor --service-account-name sa-ci
Merge external endpoint into kubeconfig; drop --external for internal VPC
yc managed-kubernetes cluster get-credentials <name> --external --force
Tabulate cluster name/status/id for scripting and audits
yc managed-kubernetes cluster list --format json | jq -r '.[]|[.name,.status,.id]|@tsv'
Cluster autoscaler node group with min/max bounds in one zone
yc managed-kubernetes node-group create --cluster-name <name> --name ng-1 --platform standard-v3 --auto-scale min=1,max=5,initial=2 --location zone=ru-central1-a
Zone-scoped subnet bound to a network; CIDR must not overlap peers
yc vpc subnet create --name sub-a --network-name net-1 --range 10.0.0.0/24 --zone ru-central1-a
Add stateful SG rule; note: rules are evaluated as allow-list
yc vpc security-group update-rules <name> --add-rule 'direction=ingress,port=443,protocol=tcp,v4-cidrs=[0.0.0.0/0]'
Dump NLB listeners and target groups to debug routing
yc load-balancer network-load-balancer get <name> --format json | jq '.listeners,.attached_target_groups'
Enumerate ALB instances and health status across folder
yc application-load-balancer load-balancer list --format json | jq -r '.[]|[.name,.status]|@tsv'
Public zone; FQDN trailing dot required, then delegate NS at registrar
yc dns zone create --name myzone --zone example.com. --public-visibility
Add apex A record with 600s TTL; @ means the zone root
yc dns zone add-records --name myzone --record '@ 600 A 1.2.3.4'
Boot VM with public NAT IP and cloud-init user-data bootstrap
yc compute instance create --name web-1 --zone ru-central1-a --network-interface subnet-name=sub-a,nat-ip-version=ipv4 --create-boot-disk image-family=ubuntu-2204-lts,size=20 --metadata-from-file user-data=cloud-init.yaml
Provision HA PG16 cluster; note: pick s3 preset for prod, not burstable b-class
yc managed-postgresql cluster create --name <name> --environment production --postgresql-version 16 --network-name <name> --host zone-id=ru-central1-a,subnet-name=<name> --resource-preset s3-c2-m8 --disk-size 50 --disk-type network-ssd
Show host FQDNs with MASTER/REPLICA role and health for connection routing
yc managed-postgresql cluster list-hosts --cluster-name <name> --format json | jq -r '.[] | "\(.name)\t\(.role)\t\(.health)"'
Create user via stdin then DB with that owner; note: password-stdin avoids shell history leak
yc managed-postgresql user create <name> --cluster-name <name> --password-stdin && yc managed-postgresql database create <name> --cluster-name <name> --owner <name>
Connect via 6432 PgBouncer with YC CA; note: verify-full needs root.crt to pin the host
curl -s https://storage.yandexcloud.net/cloud-certs/CA.pem -o ~/.postgresql/root.crt && psql "host=<host> port=6432 sslmode=verify-full dbname=<name> user=<name> target_session_attrs=read-write"
Filter Redis clusters to unhealthy ones only for a quick fleet triage
yc managed-redis cluster list --format json | jq -r '.[] | select(.health!="ALIVE") | "\(.name)\t\(.status)\t\(.health)"'
Audit ClickHouse cluster versions and presets to spot upgrade candidates
yc managed-clickhouse cluster list --format json | jq -r '.[] | "\(.name)\t\(.config.version)\t\(.resources.resourcePresetId)"'
Mint S3-compatible static key for a SA; note: secret shown once, capture it now
yc iam access-key create --service-account-name <name> --format json | jq -r '"AWS_ACCESS_KEY_ID=\(.access_key.key_id)\nAWS_SECRET_ACCESS_KEY=\(.secret)"'
Sync to YC bucket via S3 API; modern: use --delete to mirror and prune stale objects
aws --endpoint-url=https://storage.yandexcloud.net s3 sync ./dist s3://<name>/<id>/ --delete --exclude '*.map'
List buckets with size cap in GiB and storage class in one pass
yc storage bucket list --format json | jq -r '.[] | "\(.name)\t\(.max_size/1073741824)GiB\t\(.default_storage_class)"'
Auto-expire objects under prefix after 30d to cut storage cost
aws --endpoint-url=https://storage.yandexcloud.net s3api put-bucket-lifecycle-configuration --bucket <name> --lifecycle-configuration '{"Rules":[{"ID":"expire-logs","Status":"Enabled","Filter":{"Prefix":"logs/"},"Expiration":{"Days":30}}]}'
Create CR and wire docker creds helper; modern: uses yc as a credential helper, no docker login
yc container registry create --name <name> && yc container registry configure-docker
Tag with resolved registry id then push; avoids hardcoding the cr.yandex/<reg-id>
docker tag <name>:<id> cr.yandex/$(yc container registry get --name <name> --format json | jq -r .id)/<name>:<id> && docker push cr.yandex/$(yc container registry get --name <name> --format json | jq -r .id)/<name>:<id>
Enumerate every tag across all repos; useful before a registry GC sweep
yc container repository list --format json | jq -r '.[].name' | while read r; do yc container image list --repository-name "$r" --format json | jq -r '.[] | "\(.name):\(.tags[]? // "<none>")"'; done
Roll out a new revision from a CR image; note: concurrency caps in-flight requests per instance
yc serverless container create --name <name>; yc serverless container revision deploy --container-name <name> --image cr.yandex/<id>/<name>:<id> --cores 1 --memory 512M --service-account-id <id> --concurrency 4
Tail YC Cloud Logging filtered to ERROR/WARN; modern: --since accepts 1h/30m relative windows
yc logging read --group-name <name> --since 1h --levels ERROR,WARN --format json | jq -r '.[] | "\(.timestamp) \(.level) \(.message)"'
Request managed wildcard cert then check status; note: needs DNS/HTTP validation to issue
yc certificate-manager certificate request --name <name> --domains <host>,*.<host> && yc certificate-manager certificate list --format json | jq -r '.[] | "\(.name)\t\(.status)\t\(.not_after)"'
Find long-running queries
postgres
List active queries running over 5 minutes, longest first
SELECT pid, now()-query_start AS dur, state, query FROM pg_stat_activity WHERE state='active' AND now()-query_start > interval '5 min' ORDER BY dur DESC;
Kill a stuck backend
postgres
Force-kill a backend by pid; note: try pg_cancel_backend first to cancel the query only
SELECT pg_terminate_backend(<pid>); -- graceful first: SELECT pg_cancel_backend(<pid>);
Top queries by total time
postgres
pg_stat_statements: rank queries by cumulative execution time
SELECT query, calls, total_exec_time, mean_exec_time, rows FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 20;
EXPLAIN with buffers
postgres
Run query and show real timings plus buffer hits/reads to spot disk I/O
EXPLAIN (ANALYZE, BUFFERS, VERBOSE) SELECT ... ; -- shared hit/read shows cache vs disk I/O
Blocking lock tree
postgres
Show backends waiting on locks and which pids block them
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, query FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;
Replication lag bytes
postgres
Measure replica lag in bytes plus write/flush/replay lag intervals
SELECT client_addr, state, pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes, write_lag, flush_lag, replay_lag FROM pg_stat_replication;
Biggest databases
postgres
Human-readable size of every database, largest first
SELECT datname, pg_size_pretty(pg_database_size(datname)) AS size FROM pg_database ORDER BY pg_database_size(datname) DESC;
Table and index sizes
postgres
Top tables by total size including indexes and TOAST
SELECT relname, pg_size_pretty(pg_total_relation_size(oid)) AS total, pg_size_pretty(pg_relation_size(oid)) AS table FROM pg_class WHERE relkind='r' ORDER BY pg_total_relation_size(oid) DESC LIMIT 20;
Find unused indexes
postgres
Indexes never scanned (idx_scan=0); candidates to drop and reclaim space
SELECT relname, indexrelname, idx_scan, pg_size_pretty(pg_relation_size(indexrelid)) AS size FROM pg_stat_user_indexes WHERE idx_scan=0 ORDER BY pg_relation_size(indexrelid) DESC;
Check autovacuum status
postgres
Find tables with dead tuples and stale autovacuum runs
SELECT relname, n_dead_tup, last_autovacuum, last_autoanalyze FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 20;
Reindex without locking
postgres
Rebuild a bloated index online; note: must run outside a transaction
REINDEX INDEX CONCURRENTLY <name>; -- note: cannot run inside a transaction block
Create index online
postgres
Build index without blocking writes; track progress via pg_stat_progress_create_index
CREATE INDEX CONCURRENTLY idx_<name> ON <table>(col); -- monitor: SELECT * FROM pg_stat_progress_create_index;
Parallel dump and restore
postgres
Custom-format parallel dump/restore; note: -j needs directory or custom format, not plain SQL
pg_dump -Fc -j 4 -d <name> -f db.dump && pg_restore -j 4 -d <name> db.dump
Benchmark with pgbench
postgres
Run 60s load test with 32 clients across 8 threads, progress every 5s
pgbench -c 32 -j 8 -T 60 -P 5 -d <name>; -- init once: pgbench -i -s 100 <name>
Find biggest keys
redis
Sample keyspace to find largest keys per type; note: estimates, runs SCAN not blocking
redis-cli --bigkeys
Top memory keys
redis
Sample keys ranked by actual memory usage, not element count; finds RAM hogs
redis-cli --memkeys
Exact key memory
redis
Bytes used by a single key incl overhead; SAMPLES 0 = exact for collections
redis-cli MEMORY USAGE <name> SAMPLES 0
Slowlog inspection
redis
List 10 slowest commands with args and duration, then clear the log
redis-cli SLOWLOG GET 10; redis-cli SLOWLOG RESET
Human-readable latency analysis with likely causes; pair with LATENCY HISTORY <event>
redis-cli LATENCY DOCTOR
Oldest idle clients
redis
Find long-lived/idle connections leaking sockets; sort by age then idle
redis-cli CLIENT LIST | tr ' ' '\n' | grep -E 'addr=|age=|idle=' | paste - - - | sort -t= -k3 -rn | head
Cluster health check
redis
Verify slot coverage, node consistency and open slots across the cluster
redis-cli --cluster check <host>:<port>
Replica set status
mongodb
Per-member state and last applied optime; spot lagging or unhealthy secondaries
mongosh --eval 'rs.status().members.forEach(m=>print(m.name,m.stateStr,m.optimeDate))'
Kill long-running ops
mongodb
List queries running >5s with ns then killOp each; note: killOp is async, verify after
mongosh --eval 'db.currentOp({secs_running:{$gt:5},op:{$ne:"none"}}).inprog.forEach(o=>{print(o.opid,o.secs_running,o.ns); db.killOp(o.opid)})'
Query plan with stats
mongodb
Show docs examined vs returned and index usage; COLLSCAN means missing index
mongosh --eval 'db.<name>.find({status:"active"}).explain("executionStats").executionStats'
Unused index detection
mongodb
Access count per index; zero ops = candidate to drop and reclaim write cost
mongosh --eval 'db.<name>.aggregate([{$indexStats:{}}]).forEach(i=>print(i.name,i.accesses.ops))'
Profile slow queries
mongodb
Capture ops slower than 100ms then read top offenders from system.profile
mongosh --eval 'db.setProfilingLevel(1,{slowms:100}); db.system.profile.find().sort({millis:-1}).limit(5)'
Slowest recent queries
clickhouse
Top slow finished queries last hour with memory; type=2 = QueryFinish
clickhouse-client -q "SELECT query_duration_ms, formatReadableSize(memory_usage) mem, substring(query,1,80) FROM system.query_log WHERE type=2 AND event_time>now()-3600 ORDER BY query_duration_ms DESC LIMIT 10"
Pending mutations
clickhouse
Find stuck ALTER/DELETE mutations with failure reason; blocks schema changes
clickhouse-client -q "SELECT database, table, mutation_id, latest_fail_reason FROM system.mutations WHERE is_done=0"
Lint rule syntax offline before applying; note: nonzero exit on error, use in CI gate
falco -r /etc/falco/falco_rules.yaml --validate
Pull only Critical Falco events from JSON output; requires json_output: true in falco.yaml
kubectl logs -l app.kubernetes.io/name=falco -n falco | jq 'select(.priority=="Critical")'
Pull and manage versioned rules/plugins via OCI; modern: replaces manual rule file copying
falcoctl artifact install falco-rules:latest && falcoctl artifact list
Run Falco for 60s then exit; great for ad-hoc triage on a suspect node
falco -M 60 -o json_output=true 2>/dev/null | jq -c '{rule,output_fields}'
Discover filter fields for writing custom rule conditions and outputs
falco --list | grep -E 'k8s\.|container\.|proc\.' | sort
Minimal custom rule with condition/output/priority; loaded from rules.d drop-in dir
cat > /etc/falco/rules.d/shell.yaml <<'EOF'
- rule: Shell in container
desc: A shell was spawned in a container
condition: container and proc.name in (bash, sh, zsh)
output: "Shell spawned (pod=%k8s.pod.name cmd=%proc.cmdline)"
priority: WARNING
EOF
Show every Kyverno policy with enforce/audit mode and ready state at a glance
kubectl get cpol,pol -A -o custom-columns='NAME:.metadata.name,ACTION:.spec.validationFailureAction,READY:.status.ready'
Dry-run a policy on a manifest without a cluster; emits a PolicyReport for CI gating
kyverno apply policy.yaml --resource resource.yaml --policy-report
Run policy test suite
kyverno
Execute kyverno-test.yaml suites asserting resource pass/fail/skip; -d for detailed diff
kyverno test ./tests --remove-color -d
Aggregate failing PolicyReport results cluster-wide ranked by count
kubectl get polr,cpolr -A -o json | jq -r '.items[].results[] | select(.result=="fail") | "\(.policy)/\(.rule)"' | sort | uniq -c
Auto-inject labels on admission via strategic merge patch; mutate runs before validate
kubectl apply -f - <<'EOF'
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: add-team-label
spec:
rules:
- name: add-label
match:
any:
- resources:
kinds: [Pod]
mutate:
patchStrategicMerge:
metadata:
labels:
team: "{{request.userInfo.username}}"
EOF
List templates and live constraints
opa-gatekeeper
Enumerate ConstraintTemplates and every instantiated constraint kind across namespaces
kubectl get constrainttemplates && kubectl get constraints -A
Audit constraint violations via status
opa-gatekeeper
Read offending resources from a constraint's audit status without re-scanning
kubectl get k8srequiredlabels <name> -o jsonpath='{.status.totalViolations} {range .status.violations[*]}{"\n"}{.kind}/{.name}: {.message}{end}'
Offline policy test with gator
opa-gatekeeper
Validate templates+constraints against fixtures with no cluster; modern: shift-left in CI
gator test -f policy/ && gator verify ./suite
Sign image by digest
cosign
Sign by immutable digest, not tag; note: signing a tag is racy and insecure
cosign sign --key cosign.key <host>/<name>@sha256:<id>
Keyless sign via OIDC
cosign
Keyless signing with Fulcio/Rekor via OIDC identity; modern: default in cosign v2
COSIGN_EXPERIMENTAL=1 cosign sign <host>/<name>@sha256:<id>
Verify keyless signature
cosign
Verify keyless sig pinning the signer identity and OIDC issuer; note: pin both
cosign verify --certificate-identity=<id> --certificate-oidc-issuer=<host> <host>/<name> | jq .
Attest CycloneDX SBOM
cosign
Attach a signed CycloneDX SBOM attestation to an image digest
cosign attest --key cosign.key --predicate sbom.json --type cyclonedx <host>/<name>@sha256:<id>
Verify attestation by type
cosign
Verify attestation then decode the in-toto payload to inspect the predicate
cosign verify-attestation --key cosign.pub --type cyclonedx <host>/<name> | jq -r '.payload' | base64 -d | jq .
Encrypt only values in place; note: keys stay readable so diffs stay reviewable
SOPS_AGE_RECIPIENTS=age1<id> sops -e -i secrets.yaml
Rotate data key to recipients in .sops.yaml without re-encrypting plaintext manually
sops updatekeys secrets.yaml
Inject decrypted secrets as env vars for one command; note: nothing hits disk
sops exec-env secrets.enc.yaml 'terraform apply'
Surgical value edit
sops
Set a single nested key without opening an editor; great for scripted rotation
sops --set '["db"]["password"] "s3cr3t"' secrets.enc.yaml
Reuse an existing SSH key as the age recipient/identity; no new keys to manage
age -R ~/.ssh/id_ed25519.pub -o out.age file && age -d -i ~/.ssh/id_ed25519 out.age
Patch one KV field
vault
Update one field without rewriting the whole secret; note: kv patch needs KV-v2
vault kv patch -mount=secret app api_key=<id>
Pass a secret as a single-use wrapping token; note: any reuse trips a security alarm
T=$(vault kv get -wrap-ttl=60s -field=wrapping_token -mount=secret app); vault unwrap $T
Show effective ACL verbs the current token has on a path; fast policy debugging
vault token capabilities database/creds/readonly
Revoke a dynamic lease
vault
Revoke all leases under a prefix to kill leaked dynamic DB creds instantly
vault lease revoke -prefix database/creds/readonly
Move resource in state
terraform
Rename/refactor address without destroy; prefer moved{} block in newer TF
terraform state mv 'aws_instance.web' 'aws_instance.app'
Remove orphan from state
terraform
Forget resource from state without deleting real infra; note: object keeps existing
terraform state rm 'aws_s3_bucket.legacy'
Inspect single resource state
terraform
Dump all attributes of one resolved address for drift/debug investigation
terraform state show 'module.vpc.aws_subnet.private[0]'
Grep the state list
terraform
Filter managed addresses to find what TF tracks before surgery
terraform state list | grep -i 'aws_iam'
Config-driven import block
terraform
Declarative import; -generate-config-out scaffolds HCL for the imported object
cat > import.tf <<'EOF'
import {
to = aws_instance.web
id = "<id>"
}
EOF
terraform plan -generate-config-out=generated.tf
Refactor with moved block
terraform
Rename addresses in code with no destroy/recreate; survives in version control
cat >> moved.tf <<'EOF'
moved {
from = aws_instance.web
to = aws_instance.app
}
EOF
Replace resource (modern taint)
terraform
Force destroy+recreate of one resource; replaces deprecated terraform taint
terraform apply -replace='aws_instance.web'
Surgical targeted plan
terraform
Limit plan to one address; note: -target is an escape hatch, can mask drift
terraform plan -target='module.db.aws_db_instance.main'
Refresh-only plan (detect drift)
terraform
Sync state to real infra without proposing changes; surfaces out-of-band drift
terraform plan -refresh-only
Migrate backend on init
terraform
Move state to a new backend; use -reconfigure to skip migration and reset
terraform init -migrate-state -backend-config=backend.hcl
Query outputs with jq
terraform
Pipe machine-readable outputs into jq for scripting and downstream wiring
terraform output -json | jq -r '.endpoints.value[]'
Trace plan with TF_LOG
terraform
Capture provider/API debug to a file; use TRACE for the most verbose level
TF_LOG=DEBUG TF_LOG_PATH=tf.log terraform plan
Rekey vault file
ansible
Re-encrypt vault with a new password without exposing plaintext; rotate secrets safely
ansible-vault rekey vault.yml --new-vault-password-file new_pass.txt
Multiple vault IDs with prompt
ansible
Mix vault IDs: file for dev, interactive prompt for prod; lets you stage secrets per env
ansible-playbook site.yml --vault-id dev@dev_pass.txt --vault-id prod@prompt
Edit vault in place
ansible
Decrypt, edit in $EDITOR, re-encrypt atomically — never writes plaintext to disk
EDITOR=vim ansible-vault edit group_vars/prod/secrets.yml --vault-password-file ~/.vault_pass
Dynamic inventory graph
ansible
Render dynamic cloud inventory tree with host vars; verify plugin grouping before a run
ansible-inventory -i aws_ec2.yml --graph --vars
Inventory as YAML
ansible
Materialize a dynamic inventory to static YAML for diffing or offline debugging
ansible-inventory -i aws_ec2.yml --list --yaml > resolved_inventory.yml
Constructed keyed_groups
ansible
Auto-build host groups from facts/tags via constructed plugin; e.g. role_web, region_eu
plugin: constructed
keyed_groups:
- key: tags.Role
prefix: role
- key: placement.region
prefix: region
Molecule scaffold role
ansible
Scaffold a role with a Molecule scenario; MOLECULE_DISTRO picks the test image
molecule init role my_role --driver-name docker && cd my_role && MOLECULE_DISTRO=ubuntu2204 molecule create
Molecule converge then verify
ansible
Apply the role to the test instance, then run assertions (testinfra/ansible verifiers)
molecule converge && molecule verify
Molecule idempotence check
ansible
Re-run the role and fail if any task reports changed — catches non-idempotent tasks
molecule idempotence
Molecule login to instance
ansible
SSH into a live Molecule test container to inspect state mid-scenario before destroy
molecule login --host instance
Resume at a specific task
ansible
Skip everything before a named task; resume a failed long playbook without redoing setup
ansible-playbook site.yml --start-at-task "Deploy app config"
List tasks and hosts dry
ansible
Preview execution plan: every task and resolved target host, without connecting
ansible-playbook site.yml --list-tasks --list-hosts -i prod
Per-task timing profile
ansible
Rank tasks by wall-clock time to find the slow steps; profile_roles is the per-role variant
ANSIBLE_CALLBACKS_ENABLED=profile_tasks ansible-playbook site.yml
Keep remote temp files
ansible
Preserve pushed module scripts under ~/.ansible/tmp to debug a failing module by hand
ANSIBLE_KEEP_REMOTE_FILES=1 ansible-playbook site.yml -vvvv --limit <host>
Per-thread CPU breakdown
troubleshooting
Per-thread CPU%, find the hot TID inside a busy process for jstack/perf
pidstat -t -p <pid> 1
Hot thread live view
troubleshooting
Live per-thread view; convert hot TID to hex (printf %x) to match jstack nid
top -H -p <pid>
Per-core CPU saturation
troubleshooting
Per-core %usr/%sys/%iowait — spot a single saturated core vs balanced load
mpstat -P ALL 1
Run-queue vs cores
troubleshooting
vmstat r column (runnable) above nproc means CPU saturation, not just high load
vmstat 1 5 | awk 'NR>2{print "runq="$1" blocked="$2}'; nproc
Process thread count
troubleshooting
Thread count per pid and system-wide; runaway threads exhaust kernel.pid_max
ps -o nlwp= -p <pid>; ps -eLf | wc -l
RSS leak over time
troubleshooting
Sample RSS every 5s to confirm a real leak (monotonic growth) vs steady churn
while sleep 5; do ps -o rss= -p <pid> | awk '{print strftime("%T"),$1/1024"MB"}'; done
Fast memory rollup
troubleshooting
One-shot Rss/Pss/Swap totals without parsing full smaps; cheap on huge maps
cat /proc/<pid>/smaps_rollup
Largest memory mappings
troubleshooting
Top RSS mappings by region; spot a leaking heap, mmap or shared lib bloat
pmap -x <pid> | sort -k3 -rn | head
Kernel slab top consumers
troubleshooting
Sort slab caches by size; dentry/inode bloat explains kernel memory pressure
slabtop -o -s c | head -20
Reclaimable slab memory
troubleshooting
Split slab into reclaimable vs unreclaimable; high SUnreclaim = real kernel leak
grep -E 'Slab|SReclaimable|SUnreclaim' /proc/meminfo
OOM killer in dmesg
troubleshooting
Find OOM victims with human timestamps; -T avoids unreadable kernel ticks
dmesg -T | grep -iE 'killed process|out of memory' | tail
OOM score of process
troubleshooting
Higher oom_score = likelier victim; set oom_score_adj -1000 to immunize a pid
cat /proc/<pid>/oom_score /proc/<pid>/oom_score_adj
cgroup v2 OOM events
troubleshooting
oom_kill/max counters per cgroup; pod hitting memory.max before node-wide OOM
cat /sys/fs/cgroup/<name>/memory.events | grep -E 'oom|max'
Deleted files holding disk
troubleshooting
df full but du clean? Unlinked files held open by a pid; restart it to reclaim
lsof +L1 | sort -k7 -rn | head
Disk I/O latency saturation
troubleshooting
%util near 100 with rising await = saturated device; correlate with the noisy pid
iostat -x 1 | awk '$1!~/^$/{print $1, "util="$NF, "await="$(NF-2)}'
Per-process block I/O top
troubleshooting
bcc biotop: which pid drives block I/O by bytes/latency; modern: bpftrace one-liners
biotop-bpfcc -C 5 1
Conntrack table full check
troubleshooting
Count tracked flows vs limit; -S shows insert_failed/drop when table full
conntrack -L 2>/dev/null | wc -l; conntrack -S
Conntrack live events
troubleshooting
Stream NEW/DESTROY events live to catch NAT/timeout drops on a port
conntrack -E -p tcp --dport 443 -o timestamp
Ephemeral port exhaustion
troubleshooting
Count TIME-WAIT sockets vs port range; note: tune tw_reuse not tw_recycle
ss -tan state time-wait | wc -l; sysctl net.ipv4.ip_local_port_range
Socket summary stats
troubleshooting
One-shot socket totals by state; SYN-SENT pileup hints at SYN drops/firewall
ss -s; ss -tan state syn-sent | wc -l
Path MTU discovery
troubleshooting
Find PMTU drop hop; ping -M do forbids frag to pinpoint blackhole MTU
tracepath -n <host>; ping -M do -s 1472 -c2 <host>
Confirm egress route and ARP
troubleshooting
Show actual src/iface for a dest; FAILED neigh entries = L2/ARP problem
ip route get <ip>; ip neigh show | grep -E 'FAILED|INCOMPLETE'
TCP port reachability past firewall
troubleshooting
TCP-SYN traceroute survives ICMP filtering; nc -zv confirms open port
traceroute -T -p 443 <host>; nc -zv <host> 443
Bypass DNS with curl --resolve
troubleshooting
Pin host to a specific IP to test backend while keeping SNI/Host header
curl -sv --resolve <host>:443:<ip> https://<host>/healthz
In-cluster DNS smoke test
troubleshooting
Throwaway pod to resolve in-cluster names; verifies CoreDNS + kube-dns svc
kubectl run dnsutils --image=tutum/dnsutils -it --rm --restart=Never -- nslookup kubernetes.default
Query CoreDNS directly
troubleshooting
Hit CoreDNS clusterIP straight; note: ndots:5 makes short names spam queries
dig +short @$(kubectl -n kube-system get svc kube-dns -o jsonpath='{.spec.clusterIP}') <name>.<ns>.svc.cluster.local
Inspect CoreDNS config and logs
troubleshooting
Review Corefile (forward/cache) and tail logs for SERVFAIL/upstream errors
kubectl -n kube-system get cm coredns -o yaml; kubectl -n kube-system logs deploy/coredns --tail=50
TLS cipher and protocol enum
troubleshooting
Grade supported TLS versions/ciphers; flags weak/deprecated suites per port
nmap --script ssl-enum-ciphers -p 443 <host>
Verify full TLS chain and SNI
troubleshooting
Show full chain with correct SNI; Verify line catches missing intermediates
openssl s_client -connect <host>:443 -servername <host> -showcerts 2>/dev/null | grep -E 'Verify|s:|i:'
Batch cert expiry scan
troubleshooting
Loop many hosts to print notAfter dates; pipe to sort for soonest expiry
for h in $(cat hosts.txt); do echo -n "$h "; echo | openssl s_client -connect $h:443 -servername $h 2>/dev/null | openssl x509 -noout -enddate; done
Decode JWT claims
troubleshooting
Decode payload to inspect exp/iss/aud; note: fixes base64url, skips sig check
cut -d. -f2 <<<"$JWT" | tr '_-' '/+' | base64 -d 2>/dev/null | jq .
List gRPC services via reflection
troubleshooting
Enumerate services/methods over reflection; -plaintext skips TLS for debug
grpcurl -plaintext <host>:<port> list; grpcurl -plaintext <host>:<port> describe <svc>