devops cheatsheet

1661 commands · click to copy

1661 shown
tool
tag
All pods with node placement and IPs
kubectl get pods -A -o wide
#pods
Describe a pod kubectl
Full details: events, conditions, volume mounts
kubectl describe pod <name> -n <ns>
#pods#debug
Follow pod logs kubectl
Stream logs in real time; add -c <container> for multi-container pods
kubectl logs -f <pod> -n <ns>
#logs#debug
Logs from the last crashed/restarted container instance
kubectl logs <pod> --previous -n <ns>
#logs#debug
Exec into pod kubectl
Interactive shell inside a running container
kubectl exec -it <pod> -n <ns> -- bash
#pods#debug
Tunnel a cluster service port to localhost
kubectl port-forward svc/<name> 8080:80 -n <ns>
#debug#network
Block until rollout completes or times out (use in CI)
kubectl rollout status deployment/<name> -n <ns>
#deployments
Revert to the previous revision
kubectl rollout undo deployment/<name> -n <ns>
#deployments
Immediately change replica count
kubectl scale deployment/<name> --replicas=3 -n <ns>
#deployments
Recent cluster events, oldest first — great for post-incident review
kubectl get events -A --sort-by='.lastTimestamp'
#debug
Validate manifest against live API without applying changes
kubectl apply --server-side --dry-run=server -f file.yaml
#config
Current live state with managed fields stripped; useful as a base
kubectl get deployment/<name> -n <ns> -o yaml
#config
Remove a Terminating pod immediately (use with caution)
kubectl delete pod <name> -n <ns> --grace-period=0 --force
#pods#debug
Extract a file from a running container
kubectl cp <ns>/<pod>:/remote/path ./local-path
#debug
Cordon a node kubectl
Mark node as unschedulable — no new pods land here
kubectl cordon <node>
#nodes
Drain a node kubectl
Gracefully evict all pods before maintenance
kubectl drain <node> --ignore-daemonsets --delete-emptydir-data
#nodes
Open resource in $EDITOR; changes applied on save
kubectl edit deployment/<name> -n <ns>
#deployments#config
Check what a ServiceAccount is allowed to do
kubectl auth can-i list pods --as=system:serviceaccount:<ns>:<sa> -n <ns>
#rbac#debug
Deploy a chart; creates namespace if it doesn't exist
helm install <release> <chart> -f values.yaml -n <ns> --create-namespace
#helm
Safe in CI — installs if absent, upgrades if present
helm upgrade --install <release> <chart> -f values.yaml -n <ns>
#helm
Show exactly what will change (requires helm-diff plugin)
helm diff upgrade <release> <chart> -f values.yaml -n <ns>
#helm#debug
Output rendered YAML to stdout without deploying
helm template <release> <chart> -f values.yaml --debug
#helm#debug
All computed values for a deployed release
helm get values <release> -n <ns> --all
#helm
All Helm releases across every namespace
helm list -A --output table
#helm
Revert to a specific historical revision
helm rollback <release> <revision> -n <ns>
#helm
Remove release and all managed resources
helm uninstall <release> -n <ns>
#helm
Validate chart structure and values; fails on warnings in --strict mode
helm lint <chart-dir> -f values.yaml --strict
#helm#debug
Verify all Flux controllers are running and CRDs are installed
flux check
#flux
Summary table: Kustomizations, HelmReleases, Sources — with sync status
flux get all -A
#flux
Trigger immediate git pull + apply
flux reconcile kustomization <name> --with-source -n <ns>
#flux
Re-run Helm install/upgrade cycle immediately
flux reconcile helmrelease <name> --with-source -n <ns>
#flux
Show which Flux objects own and manage this resource
flux trace <kind>/<name> -n <ns>
#flux#debug
Pause sync — useful while doing manual hotfixes
flux suspend kustomization <name> -n <ns>
#flux
Re-enable a suspended Kustomization or HelmRelease
flux resume kustomization <name> -n <ns>
#flux
Backup current Flux config as plain YAML for bootstrapping another cluster
flux export kustomization --all > clusters/cluster.yaml
#flux#config
Cross-compile and push directly to registry with BuildKit
docker buildx build --platform linux/amd64,linux/arm64 -t reg/img:tag --push .
#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
#docker
See each layer, its command, and size; identify bloat
docker history --no-trunc img:tag
#docker#debug
Remove stopped containers, unused images, networks, volumes
docker system prune -af --volumes
#docker
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
#docker
Export an image for air-gapped transfer
docker save img:tag | gzip > img.tar.gz
#docker
Plan with var file terraform
Show changes; save plan artifact for CI gating
terraform plan -var-file=prod.tfvars -out=plan.tfplan
#terraform
Apply a saved plan terraform
Apply exactly the previously generated plan — no interactive prompts
terraform apply plan.tfplan
#terraform
Bring an already-existing resource under Terraform control
terraform import module.path.resource_type.name <remote-id>
#terraform
Inspect Terraform state attributes for a single resource
terraform state show module.path.resource_type.name
#terraform
Rename/reorganize resource without destroying and recreating it
terraform state mv old.address new.address
#terraform
Attach a debug container (netshoot) to a running pod — shares PID/net namespaces
kubectl debug -it <pod> --image=nicolaka/netshoot -n <ns>
#debug#network#pods
CPU and memory per node (requires metrics-server)
kubectl top nodes
#nodes#monitoring
Memory-sorted pod usage across all namespaces — find the hungry ones
kubectl top pods -A --sort-by=memory
#pods#monitoring
Print just the data field; pipe to python -m json.tool for formatting
kubectl get cm <name> -n <ns> -o jsonpath='{.data}'
#config#debug
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()]"
#secrets#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
#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}'
#debug#pods
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'
#pods
Inline JSON patch without editing the whole manifest
kubectl patch deployment <name> -n <ns> -p '{"spec":{"replicas":2}}'
#deployments#config
Set or update an annotation; --overwrite replaces existing value
kubectl annotate pod <pod> -n <ns> key=value --overwrite
#config
Label resource kubectl
Add or change a label on any resource
kubectl label node <node> role=worker --overwrite
#nodes#config
Prevent pods without matching toleration from scheduling on node
kubectl taint nodes <node> key=value:NoSchedule
#nodes
Remove a taint by appending a dash at the end
kubectl taint nodes <node> key=value:NoSchedule-
#nodes
Rolling-update the container image without editing YAML
kubectl set image deployment/<name> <container>=image:tag -n <ns>
#deployments
Show all revisions with change cause (requires --record or annotations)
kubectl rollout history deployment/<name> -n <ns>
#deployments
Trigger zero-downtime pod rotation without changing spec
kubectl rollout restart deployment/<name> -n <ns>
#deployments
Create a new namespace; idempotent with --dry-run=client | apply
kubectl create namespace <ns>
#config
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>
#deployments#config
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
#debug#pods
Get node labels kubectl
See all labels assigned to each node
kubectl get nodes --show-labels
#nodes
Uncordon a node kubectl
Re-enable scheduling on a previously cordoned node
kubectl uncordon <node>
#nodes
Get HPA status kubectl
Horizontal Pod Autoscaler current/desired replicas and metrics
kubectl get hpa -A
#deployments#monitoring
Used vs hard limits for CPU, memory, object counts in namespace
kubectl describe resourcequota -n <ns>
#config
Show min-available and current healthy pod counts
kubectl get pdb -A
#deployments
View LimitRange kubectl
Default and max resource limits applied to pods in namespace
kubectl describe limitrange -n <ns>
#config
Get all CRDs kubectl
List all Custom Resource Definitions sorted by creation time
kubectl get crds --sort-by='.metadata.creationTimestamp'
#config#debug
Show pod IPs backing a Service — diagnose selector mismatch
kubectl get endpoints <svc> -n <ns>
#network#debug
See cert-manager Certificate ready status and expiry dates
kubectl get certificate -A -o wide
#network#debug
Inspect topology spread constraints on a pod
kubectl get pod <pod> -n <ns> -o jsonpath='{.spec.topologySpreadConstraints}'
#pods#config
Apply manifests and remove stale objects matching the label selector
kubectl apply -f ./dir/ --prune -l app=<label> -n <ns>
#config
Show what would change if you applied this manifest now
kubectl diff -f file.yaml
#config#debug
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>
#pods#debug
Live-refresh pod list as statuses change
kubectl get pods -n <ns> -w
#pods#debug
Top pods by CPU kubectl
CPU-sorted pod usage across all namespaces
kubectl top pods -A --sort-by=cpu
#pods#monitoring
Generate a short-lived bound service account token
kubectl create token <sa-name> -n <ns> --duration=1h
#rbac#config
Show all permissions the current user has in a namespace
kubectl auth can-i --list -n <ns>
#rbac#debug
Force recreation of all pods — useful after ConfigMap changes
kubectl delete pods --all -n <ns>
#pods
All Ingress resources with hosts and addresses
kubectl get ingress -A
#network
Backup/inspect entire pod state in a namespace
kubectl get pods -n <ns> -o yaml > pods-dump.yaml
#debug#pods
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}'
#debug#pods
List all available versions of a chart in added repositories
helm search repo <chart> --versions
#helm
Authenticate to an OCI-based Helm registry
helm registry login registry.example.com -u user -p pass
#helm
Upload a packaged chart to an OCI registry
helm push mychart-0.1.0.tgz oci://registry.example.com/charts
#helm
Create a .tgz archive from a chart directory
helm package ./my-chart --destination ./dist
#helm
Print the chart README to stdout
helm show readme <chart>
#helm
Dump default values to a file for customization
helm show values <chart> > values.yaml
#helm
Install a Helm plugin from URL (e.g. helm-diff, helm-secrets)
helm plugin install https://github.com/databus23/helm-diff
#helm
Show all installed Helm plugins with versions
helm plugin list
#helm
All Kubernetes manifests generated by this Helm release
helm get manifest <release> -n <ns>
#helm#debug
Run any test hooks defined in the chart
helm test <release> -n <ns>
#helm#debug
Decrypt a SOPS/age-encrypted values file (requires helm-secrets plugin)
helm secrets view secrets.yaml
#helm#secrets
Print post-install notes for a deployed release
helm get notes <release> -n <ns>
#helm
Install Flux and push initial config to GitHub repo
flux bootstrap github --owner=<org> --repository=<repo> --branch=main --path=clusters/production --personal
#flux#config
Register a git repo as a Flux source
flux create source git <name> --url=https://github.com/org/repo --branch=main -n flux-system
#flux
Register a Helm chart repository as a Flux source
flux create source helm <name> --url=https://charts.example.com -n flux-system
#flux
Deploy a chart via Flux HelmRelease resource
flux create helmrelease <name> --source=HelmRepository/<repo> --chart=<chart> --chart-version='>=1.0.0' -n <ns>
#flux#helm
Recent events from the flux-system namespace
kubectl get events -n flux-system --sort-by='.lastTimestamp' | tail -20
#flux#debug
Remove a Kustomization or HelmRelease from the cluster
flux delete kustomization <name> -n <ns>
#flux
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
#flux#config
Follow logs from a specific Flux controller
flux logs --kind=kustomize-controller -n flux-system --tail=50
#flux#debug
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
#flux
Render all manifests for an overlay to stdout
kustomize build ./overlays/prod
#kustomize
Build and apply kustomization in one step via kubectl
kubectl apply -k ./overlays/prod
#kustomize
Diff kustomization kustomize
Show what changes before applying
kubectl diff -k ./overlays/prod
#kustomize#debug
Append a resource file to kustomization.yaml
kustomize edit add resource ./deployment.yaml
#kustomize
Update image tag in kustomization.yaml
kustomize edit set image myapp=registry/myapp:v2.0.0
#kustomize
Set namespace kustomize
Override namespace for all resources in the overlay
kustomize edit set namespace production
#kustomize
Inject a common label into all generated resources
kustomize edit add label env:production
#kustomize
Add patch kustomize
Register a strategic merge patch in kustomization.yaml
kustomize edit add patch --path patch.yaml --kind Deployment --name <name>
#kustomize
List resources kustomize
List all settable fields in the kustomization
kustomize cfg list-setters .
#kustomize
Pass build-time variables into Dockerfile ARG instructions
docker build --build-arg VERSION=1.2.3 --build-arg ENV=prod -t img:tag .
#docker
Fail pipeline if HIGH or CRITICAL CVEs found
trivy image --exit-code 1 --severity HIGH,CRITICAL img:tag
#docker#security
Generate Software Bill of Materials for an image (Docker Desktop)
docker sbom img:tag
#docker#security
Drill into network settings of a running container
docker inspect <container> | jq '.[0].NetworkSettings.Networks'
#docker#debug#network
Build and start all services in background
docker compose up -d --build
#docker#compose
Stream last 100 lines and follow a compose service
docker compose logs -f --tail=100 <service>
#docker#compose#logs
Stop and remove containers, networks, and volumes
docker compose down -v
#docker#compose
Detailed breakdown of disk usage per image, container, volume
docker system df -v
#docker
Enter container as root even if default user is non-root
docker exec -it -u root <container> bash
#docker#debug
Inject a file into a running container without rebuild
docker cp ./local-file.conf <container>:/etc/app/config.conf
#docker#debug
Import an image exported with docker save
docker load < img.tar.gz
#docker
Free disk space in a self-hosted Docker Registry
docker exec -it registry bin/registry garbage-collect /etc/docker/registry/config.yml
#docker
Build only up to a specific stage in a multi-stage Dockerfile
docker build --target builder -t img:builder .
#docker
Workspace list terraform
Show all workspaces; current one marked with *
terraform workspace list
#terraform
Create a new workspace and switch to it
terraform workspace new staging && terraform workspace select staging
#terraform
Check Terraform configuration for syntax and consistency errors
terraform validate
#terraform
Format code terraform
Auto-format all .tf files recursively
terraform fmt -recursive
#terraform
Show output values terraform
Print all outputs as JSON; useful for pipeline scripting
terraform output -json
#terraform
Destroy a single resource without touching everything else
terraform destroy -target=module.vpc.aws_vpc.main
#terraform
Mark resource for replacement on next apply
terraform taint module.eks.aws_instance.node
#terraform
Forget a resource from state without destroying it in cloud
terraform state rm module.path.resource_type.name
#terraform
Refresh state terraform
Update state file to match real infrastructure
terraform refresh -var-file=prod.tfvars
#terraform
Visualize resource dependency graph (requires Graphviz)
terraform graph | dot -Tsvg > graph.svg
#terraform#debug
Filter state resources by pattern
terraform state list | grep <pattern>
#terraform
Plan all modules terragrunt
Plan all dependent Terragrunt modules in order
terragrunt run-all plan --terragrunt-non-interactive
#terragrunt
Apply all modules terragrunt
Apply all modules in dependency order, non-interactive
terragrunt run-all apply --terragrunt-non-interactive
#terragrunt
Destroy all modules terragrunt
Destroy all modules in reverse dependency order
terragrunt run-all destroy --terragrunt-non-interactive
#terragrunt
Print outputs from all modules as JSON
terragrunt run-all output -json
#terragrunt
Run terraform validate across all modules
terragrunt run-all validate
#terragrunt
Run a playbook ansible
Run playbook with diff output to see what changes
ansible-playbook -i inventory/prod playbook.yml --diff
#ansible
Run only against specific hosts from inventory
ansible-playbook -i inventory playbook.yml --limit host1,host2
#ansible
Execute only tasks matching these tags
ansible-playbook -i inventory playbook.yml --tags install,configure
#ansible
Skip tasks with the specified tags
ansible-playbook -i inventory playbook.yml --skip-tags cleanup
#ansible
Simulate execution without making changes
ansible-playbook -i inventory playbook.yml --check --diff
#ansible
Check connectivity to all hosts in inventory
ansible all -i inventory -m ping
#ansible
Run a one-liner shell command on all hosts
ansible all -i inventory -m shell -a 'uptime'
#ansible
Copy a file to all hosts
ansible all -i inventory -m copy -a 'src=./file dest=/tmp/file'
#ansible
Collect all Ansible facts (OS, CPU, network) from a host
ansible <host> -i inventory -m setup | jq '._ansible_facts'
#ansible#debug
Inline-encrypt a string for use in playbooks
ansible-vault encrypt_string 'secret_value' --name 'db_password'
#ansible#secrets
Encrypt an entire variable file with Ansible Vault
ansible-vault encrypt vars/secrets.yml
#ansible#secrets
Decrypt an Ansible Vault-encrypted file in place
ansible-vault decrypt vars/secrets.yml
#ansible#secrets
View contents of vault-encrypted file without decrypting on disk
ansible-vault view vars/secrets.yml
#ansible#secrets
Download roles listed in requirements.yml to local roles dir
ansible-galaxy install -r requirements.yml -p roles/
#ansible
Install an Ansible collection from Ansible Galaxy
ansible-galaxy collection install community.kubernetes
#ansible
Show all hosts and groups parsed from inventory
ansible-inventory -i inventory --list | jq 'keys'
#ansible
Pass extra variables at runtime overriding playbook defaults
ansible-playbook playbook.yml -e 'env=prod version=2.0'
#ansible
Verbose output ansible
Maximum verbosity — shows every task, connection, output
ansible-playbook playbook.yml -vvv
#ansible#debug
Validate YAML syntax without executing any tasks
ansible-playbook playbook.yml --syntax-check
#ansible
Authenticate to Vault using a token
vault login <token>
#vault
Authenticate via AppRole auth method
vault write auth/approle/login role_id=<role> secret_id=<secret>
#vault
Read a KV v2 secret; add -format=json for scripting
vault kv get -mount=secret path/to/secret
#vault#secrets
Write or update a KV v2 secret
vault kv put -mount=secret path/to/secret key=value
#vault#secrets
List all keys under a KV path
vault kv list -mount=secret path/to/
#vault#secrets
Soft-delete the latest version of a KV secret
vault kv delete -mount=secret path/to/secret
#vault#secrets
See all versions, creation dates, deletion status
vault kv metadata get -mount=secret path/to/secret
#vault#secrets
Issue a short-lived token limited to a specific policy
vault token create -policy=read-only -ttl=1h
#vault
Show all enabled auth backends in Vault
vault auth list
#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
#vault#config
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
#vault#config
Write policy vault
Upload an HCL policy file to Vault
vault policy write my-policy policy.hcl
#vault#config
List all policies in Vault
vault policy list
#vault
Mount a new secrets engine at a given path
vault secrets enable -path=myapp kv-v2
#vault#config
Encrypt data using Vault's transit encryption engine
vault write transit/encrypt/my-key plaintext=$(echo -n 'secret' | base64)
#vault#secrets
Decrypt a ciphertext with transit engine
vault write transit/decrypt/my-key ciphertext=vault:v1:... | base64 -d
#vault#secrets
Show TTL, policies, and capabilities of current token
vault token lookup
#vault
Renew token vault
Extend the current token's TTL
vault token renew
#vault
Vault status vault
Show seal status, HA mode, cluster info
vault status
#vault#debug
Describe ExternalSecret external-secrets
Show sync status, last sync time, and error message if failed
kubectl describe externalsecret <name> -n <ns>
#secrets#debug
List all ExternalSecrets external-secrets
See all ESO ExternalSecrets and their Ready status
kubectl get externalsecret -A
#secrets
Force sync ExternalSecret external-secrets
Trigger immediate re-sync by updating annotation
kubectl annotate externalsecret <name> -n <ns> force-sync=$(date +%s) --overwrite
#secrets
List ClusterSecretStores external-secrets
Show all cluster-scoped secret stores and their status
kubectl get clustersecretstore
#secrets
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
#secrets#config
Fetch public cert sealed-secrets
Download the sealing certificate for offline operations
kubeseal --fetch-cert --controller-name=sealed-secrets > pub-cert.pem
#secrets
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
#secrets
List SealedSecrets sealed-secrets
Show all SealedSecrets and their sync status
kubectl get sealedsecret -A
#secrets
Cilium status cilium
Check health of all Cilium components; wait until ready
cilium status --wait
#cilium#network
Run built-in end-to-end connectivity tests
cilium connectivity test
#cilium#network#debug
Show all Cilium-managed endpoints with security identity
cilium endpoint list
#cilium#network
Live-stream network flows for a specific pod
hubble observe --pod <ns>/<pod> -f
#cilium#hubble#network#debug
Show only dropped/denied flows cluster-wide
hubble observe --verdict DROPPED -f
#cilium#hubble#network#debug
Show flows for all pods in a namespace over last 5 minutes
hubble observe --namespace <ns> --since 5m
#cilium#hubble#network
All Cilium and standard NetworkPolicy resources
kubectl get ciliumnetworkpolicies,networkpolicies -A
#cilium#network
Hubble status cilium
Show Hubble relay and observer status
hubble status
#cilium#hubble
Real-time packet drops from Cilium dataplane
cilium monitor --type drop
#cilium#network#debug
Ad-hoc PromQL query from CLI
curl -sG 'http://prometheus:9090/api/v1/query' --data-urlencode 'query=up' | jq .
#prometheus#monitoring
Run an instant PromQL query using promtool
promtool query instant http://prometheus:9090 'up{job="kubelet"}'
#prometheus#monitoring#debug
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 .
#prometheus#monitoring
Check alert rules prometheus
Validate Prometheus alert/recording rule files for syntax
promtool check rules rules.yml
#prometheus#monitoring
Create a silence to mute alert notifications during maintenance
amtool silence add --alertmanager.url=http://alertmanager:9093 alertname=<name> --duration=2h --comment='Maintenance'
#alertmanager#monitoring
List silences prometheus
Show all active silences in Alertmanager
amtool silence query --alertmanager.url=http://alertmanager:9093
#alertmanager#monitoring
Expire silence prometheus
Immediately end an active silence
amtool silence expire <id> --alertmanager.url=http://alertmanager:9093
#alertmanager#monitoring
Validate Alertmanager configuration file
amtool check-config alertmanager.yml
#alertmanager#monitoring
List active alerts prometheus
Show all firing alerts in Alertmanager
amtool alert query --alertmanager.url=http://alertmanager:9093
#alertmanager#monitoring
Hot-reload Prometheus configuration without restart
curl -X POST http://prometheus:9090/-/reload
#prometheus#monitoring
Cluster health elasticsearch
Show cluster status: green/yellow/red, shards, nodes
curl -s http://localhost:9200/_cluster/health | jq .
#elasticsearch#monitoring
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'
#elasticsearch
Delete index elasticsearch
Remove an index and all its data
curl -X DELETE http://localhost:9200/<index>
#elasticsearch
Get index settings elasticsearch
Inspect number of shards, replicas, refresh interval
curl -s http://localhost:9200/<index>/_settings | jq .
#elasticsearch
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"}}'
#elasticsearch
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'
#elasticsearch
Node stats elasticsearch
Show all ES nodes with JVM heap, load, roles
curl -s http://localhost:9200/_cat/nodes?v
#elasticsearch#monitoring
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"}}}'
#elasticsearch
Snapshot create elasticsearch
Create a snapshot to the registered repository
curl -X PUT http://localhost:9200/_snapshot/<repo>/<snapshot>
#elasticsearch
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}'
#elasticsearch
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
#kibana
Import a previously exported dashboard
curl -X POST 'http://kibana:5601/api/saved_objects/_import' -H 'kbn-xsrf: true' --form file=@dashboard.ndjson
#kibana
List topics kafka
List all Kafka topics in the cluster
kafka-topics.sh --bootstrap-server kafka:9092 --list
#kafka
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
#kafka
Show partition count, replication, leaders and ISR
kafka-topics.sh --bootstrap-server kafka:9092 --describe --topic <name>
#kafka
Delete topic kafka
Permanently delete a Kafka topic
kafka-topics.sh --bootstrap-server kafka:9092 --delete --topic <name>
#kafka
Read all messages from a topic starting from offset 0
kafka-console-consumer.sh --bootstrap-server kafka:9092 --topic <name> --from-beginning
#kafka#debug
Send messages to a topic interactively from stdin
kafka-console-producer.sh --bootstrap-server kafka:9092 --topic <name>
#kafka#debug
Show all consumer groups
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --list
#kafka
Show lag per partition for a consumer group
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --describe --group <group>
#kafka#monitoring#debug
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
#kafka
Increase (only) the number of partitions for a topic
kafka-topics.sh --bootstrap-server kafka:9092 --alter --topic <name> --partitions 6
#kafka
Show earliest and latest offsets per partition
kafka-run-class.sh kafka.tools.GetOffsetShell --broker-list kafka:9092 --topic <name>
#kafka#debug
Open interactive Redis CLI session
redis-cli -h redis -p 6379 -a <password>
#redis
Full server information: memory, CPU, clients, persistence
redis-cli -h redis INFO all
#redis#monitoring
Stream all commands executed on the Redis server
redis-cli -h redis MONITOR
#redis#debug
Slow log redis
Show last 20 slow queries with execution time
redis-cli -h redis SLOWLOG GET 20
#redis#debug#monitoring
Show bytes consumed by a specific key
redis-cli -h redis MEMORY USAGE <key>
#redis#debug
Delete all keys in current DB asynchronously
redis-cli -h redis FLUSHDB ASYNC
#redis
Trigger background RDB snapshot save
redis-cli -h redis BGSAVE
#redis
Show master/replica role, replication offset, connected replicas
redis-cli -h redis INFO replication
#redis#monitoring
Non-blocking key scan by pattern (prefer over KEYS in production)
redis-cli -h redis --scan --pattern 'session:*' | head -20
#redis#debug
TTL of a key redis
Remaining TTL in seconds; -1 = no expiry, -2 = not found
redis-cli -h redis TTL <key>
#redis#debug
Open interactive shell to a MongoDB instance
mongosh 'mongodb://user:pass@mongo:27017/dbname'
#mongodb
Show replica set members, lag, and election status
mongosh --eval 'rs.status()' mongodb://mongo:27017
#mongodb#monitoring
Database stats mongodb
Data size, storage size, collection count for a database
mongosh --eval 'db.stats()' mongodb://mongo:27017/mydb
#mongodb#monitoring
Document count, index sizes, storage for a collection
mongosh --eval 'db.myCollection.stats()' mongodb://mongo:27017/mydb
#mongodb
Show operations running longer than 5 seconds
mongosh --eval 'db.currentOp({active:true,secs_running:{$gt:5}})' mongodb://mongo:27017
#mongodb#debug#monitoring
Create dump mongodb
Export database to BSON files
mongodump --uri='mongodb://user:pass@mongo:27017' --db=mydb --out=/backups/
#mongodb
Restore dump mongodb
Import BSON backup into MongoDB
mongorestore --uri='mongodb://user:pass@mongo:27017' --db=mydb /backups/mydb/
#mongodb
List indexes mongodb
Show all indexes on a collection
mongosh --eval 'db.myCollection.getIndexes()' mongodb://mongo:27017/mydb
#mongodb
Register a MinIO server in the mc client
mc alias set myminio https://minio.example.com ACCESSKEY SECRETKEY
#minio
List buckets minio
Show all buckets on the server
mc ls myminio
#minio
Create a new S3-compatible bucket
mc mb myminio/my-bucket
#minio
Upload a local file to MinIO
mc cp ./file.tar.gz myminio/my-bucket/backups/
#minio
Continuously sync a local directory to a bucket
mc mirror --watch ./data myminio/my-bucket/data
#minio
Server info minio
Show server capacity, uptime, drives, and status
mc admin info myminio
#minio#monitoring
Show storage size per bucket
mc du --depth 1 myminio
#minio#monitoring
Apply object expiry/transition lifecycle rules to a bucket
mc ilm import myminio/my-bucket < lifecycle.json
#minio#config
Delete a specific object from a bucket
mc rm myminio/my-bucket/path/to/file.txt
#minio
Delete a bucket and all its objects
mc rb --force myminio/my-bucket
#minio
Open interactive ClickHouse CLI session
clickhouse-client -h clickhouse -u default --password <pass> --database mydb
#clickhouse
Show databases clickhouse
List all databases in ClickHouse
clickhouse-client -q 'SHOW DATABASES'
#clickhouse
Show tables clickhouse
List all tables in a database
clickhouse-client -q 'SHOW TABLES FROM mydb'
#clickhouse
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"
#clickhouse#monitoring
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'
#clickhouse#monitoring#debug
Kill query clickhouse
Terminate a long-running or stuck query
clickhouse-client -q "KILL QUERY WHERE query_id='<id>'"
#clickhouse#debug
Drop caches clickhouse
Flush ClickHouse caches to free memory
clickhouse-client -q 'SYSTEM DROP MARK CACHE; SYSTEM DROP UNCOMPRESSED CACHE'
#clickhouse
Sync replica clickhouse
Force replica to sync with ZooKeeper state
clickhouse-client -q 'SYSTEM SYNC REPLICA mydb.myTable'
#clickhouse#monitoring
Nodetool status cassandra
Show ring topology, load, state, and host IDs
nodetool status
#cassandra#monitoring
Nodetool info cassandra
Local node heap, uptime, gossip, data center info
nodetool info
#cassandra#monitoring
Connect with cqlsh cassandra
Open CQL interactive shell
cqlsh <host> 9042 -u cassandra -p cassandra
#cassandra
List keyspaces cassandra
Show all keyspaces in the cluster
cqlsh -e 'DESCRIBE KEYSPACES'
#cassandra
Repair keyspace cassandra
Run incremental repair on the primary range (use in maintenance)
nodetool repair -pr <keyspace>
#cassandra
Compaction stats cassandra
Show ongoing compaction operations and queue length
nodetool compactionstats
#cassandra#monitoring
Force memtable flush to SSTables
nodetool flush <keyspace> <table>
#cassandra
Describe table cassandra
Show CREATE TABLE statement with all settings
cqlsh -e 'DESCRIBE TABLE <keyspace>.<table>'
#cassandra
List queues rabbitmq
Show queues with message count and consumer count
rabbitmqctl list_queues name messages consumers durable
#rabbitmq#monitoring
List exchanges rabbitmq
Show all exchanges and their types
rabbitmqctl list_exchanges name type durable
#rabbitmq
List bindings rabbitmq
Show all queue-exchange bindings
rabbitmqctl list_bindings
#rabbitmq
List connections rabbitmq
Show all active AMQP connections
rabbitmqctl list_connections name peer_host port user
#rabbitmq#monitoring
Purge a queue rabbitmq
Delete all messages from a queue without removing it
rabbitmqctl purge_queue <queue>
#rabbitmq
Node status rabbitmq
Show node info, running applications, memory, listeners
rabbitmqctl status
#rabbitmq#monitoring
Enable the HTTP management API and web UI on port 15672
rabbitmq-plugins enable rabbitmq_management
#rabbitmq#config
Export all exchanges, queues, bindings, users, policies
rabbitmqctl export_definitions /tmp/rabbitmq-definitions.json
#rabbitmq#config
Squash, reorder, or edit the last 5 commits
git rebase -i HEAD~5
#git
Apply a single commit from another branch
git cherry-pick <sha>
#git
Show recent HEAD movements including rebases and resets
git reflog show --date=relative | head -20
#git#debug
Save uncommitted work (including untracked files) with a label
git stash push -m 'WIP: feature-x' -u
#git
Apply and drop a specific stash entry
git stash pop stash@{2}
#git
Binary search through history to find a regression
git bisect start && git bisect bad HEAD && git bisect good <good-sha>
#git#debug
Check out a branch in a parallel directory without stashing
git worktree add ../feature-branch feature/my-feature
#git
Initialize and update all submodules recursively
git submodule update --init --recursive
#git
Print the content of a file at a historical commit
git show <sha>:path/to/file
#git
Compact visual branch graph of the entire repo
git log --oneline --graph --decorate --all | head -40
#git
Find all commits that added or removed the string 'password'
git log -S 'password' --oneline --all
#git#security#debug
Include staged changes in last commit without changing message
git commit --amend --no-edit
#git
Remove a branch from the remote repository
git push origin --delete feature/old-branch
#git
Remove untracked files and directories (incl. gitignored)
git clean -fdx
#git
Update all remotes and delete stale tracking branches
git fetch --all --prune --tags
#git
Format and colorize a JSON file
cat data.json | jq '.'
#jq
Select objects where a field equals a value
cat data.json | jq '.items[] | select(.status == "Running")'
#jq
Project only specific fields into a new array
cat data.json | jq '[.items[] | {name:.metadata.name, ns:.metadata.namespace}]'
#jq
Aggregate items by a field value
cat data.json | jq 'group_by(.namespace) | map({ns: .[0].namespace, count: length})'
#jq
Remove a field from JSON output
cat data.json | jq 'del(.metadata.managedFields)'
#jq
Raw output (-r) for scripting; one value per line
cat data.json | jq -r '.items[].metadata.name'
#jq
Deep-merge two JSON files (override wins)
jq -s '.[0] * .[1]' base.json override.json
#jq
Extract a value from a YAML file
yq '.spec.replicas' deployment.yaml
#yq
In-place update of a YAML field
yq -i '.spec.replicas = 3' deployment.yaml
#yq
Output YAML as JSON for jq processing
yq -o=json deployment.yaml
#yq
Deep-merge a base YAML with an override file
yq '. *= load("override.yaml")' base.yaml
#yq
Split a multi-document YAML into a JSON array
yq -s '.' multi.yaml | yq -o=json
#yq
Find files larger than 100MB sorted by size
find / -type f -size +100M -exec ls -lh {} \; 2>/dev/null | sort -k5 -rh | head -20
#linux
Top 15 largest directories at root level
du -sh /* 2>/dev/null | sort -rh | head -15
#linux
TCP listening ports with PID and process name (modern netstat)
ss -tlnp
#linux#network
Which process is listening on a specific port
ss -tlnp | grep :<port>
#linux#network#debug
Top 15 processes by CPU consumption
ps aux --sort=-%cpu | head -15
#linux#monitoring
Top 15 processes by memory consumption
ps aux --sort=-%mem | head -15
#linux#monitoring
Stream logs for a systemd unit from the last 10 minutes
journalctl -u <service> -f --since '10 minutes ago'
#linux#logs
Service status, recent log lines, and active timers
systemctl status <service> --no-pager -l
#linux
Capture specific traffic to a pcap file
tcpdump -i eth0 -nn host <ip> and port 80 -w /tmp/capture.pcap
#linux#network#debug
Show inode usage per filesystem; can cause 'no space' without disk full
df -i | sort -k5 -rn
#linux
Show all files, sockets, and connections opened by a process
lsof -p <pid>
#linux#debug
Re-run a command every 2 seconds with diff highlighting
watch -n 2 'kubectl get pods -n <ns>'
#linux
Run a script immune to SIGHUP; redirect output to file
nohup ./script.sh > /tmp/out.log 2>&1 &
#linux
Forward local port 8080 to an internal host via bastion
ssh -L 8080:internal-service:80 user@bastion -N -f
#linux#network
Extract a gzipped tar archive to a specific directory
tar -xzf archive.tar.gz -C /target/dir/
#linux
Cryptographically secure random 32-byte password
openssl rand -base64 32
#linux#security
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
#linux#network#security
Sum the 3rd column of a space-delimited text file
awk '{sum += $3} END {print sum}' file.txt
#linux
In-place global string replacement
sed -i 's/old-string/new-string/g' file.txt
#linux
Count and rank duplicate lines in a file
sort file.txt | uniq -c | sort -rn | head -20
#linux
Scan a local directory for vulnerabilities and misconfigs
trivy fs --severity HIGH,CRITICAL .
#trivy#security
Security audit of the whole cluster: images, configs, RBAC
trivy k8s --report summary cluster
#trivy#security
Scan workloads only in a specific namespace
trivy k8s --namespace production --report summary all
#trivy#security
Check Helm chart templates for security misconfigurations
trivy config ./my-chart
#trivy#security#helm
Machine-readable vulnerability scan results
trivy image --format json -o results.json img:tag
#trivy#security
Find misconfigurations in Terraform/Kubernetes/Helm code
trivy config --severity MEDIUM,HIGH,CRITICAL ./terraform
#trivy#security#terraform
Skip vulnerabilities that have no fix available yet
trivy image --ignore-unfixed --severity HIGH,CRITICAL img:tag
#trivy#security
Pre-download the latest vulnerability database
trivy image --download-db-only
#trivy#security
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}'
#apisix#network
Inspect a single APISIX route configuration
curl -s http://apisix:9180/apisix/admin/routes/<id> -H 'X-API-KEY: <key>' | jq .
#apisix#network
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}'
#apisix#network
List plugins apisix
All available APISIX plugins
curl -s http://apisix:9180/apisix/admin/plugins/list -H 'X-API-KEY: <key>' | jq .
#apisix
Hot-reload APISIX configuration from etcd
curl -X PUT http://apisix:9180/apisix/admin/configs/reload -H 'X-API-KEY: <key>'
#apisix#config
APISIX process health via control plane API
curl -s http://apisix:9080/apisix/status | jq .
#apisix#monitoring
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 .
#curl#network
Show full request/response headers including redirects
curl -sLv https://example.com 2>&1 | grep -E '^[<>*]'
#curl#network#debug
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
#curl#network#debug
Download a file showing a clean progress bar
curl -L --progress-bar -o output.file https://example.com/file.tar.gz
#curl#network
HTTP request with Basic Authentication
curl -s -u user:password https://api.example.com/endpoint | jq .
#curl#network
Get just the response status code — useful in scripts
curl -so /dev/null -w '%{http_code}' https://example.com
#curl#network#debug
Open k9s scoped to a single namespace
k9s -n <ns>
#k9s
Open k9s using a specific kubeconfig context
k9s --context <context>
#k9s
Switch resource view: :pods, :svc, :helmreleases, :ns
# In k9s press ':' then type 'helmreleases' or 'kustomizations'
#k9s
Type / and a pattern to filter the displayed resources
# In k9s press '/' to filter by name pattern
#k9s
Show kubectl describe output for highlighted resource
# In k9s press 'd' on selected resource
#k9s
Stream logs for the selected pod/container
# In k9s press 'l' on a pod
#k9s
Open interactive shell inside the selected pod
# In k9s press 's' on a pod
#k9s
Delete the selected resource with confirmation
# In k9s press Ctrl+D on selected resource
#k9s
Switch the active cluster context
kubectl config use-context <context>
#config
Show all contexts in current kubeconfig
kubectl config get-contexts
#config
Combine multiple kubeconfig files into one
KUBECONFIG=~/.kube/config:~/.kube/cluster2.yaml kubectl config view --flatten > ~/.kube/merged.yaml
#config
Avoid typing -n on every command for this context
kubectl config set-context --current --namespace=<ns>
#config
Show API server and CoreDNS endpoints
kubectl cluster-info
#debug#config
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}'
#nodes#debug
Immediately run a CronJob as a one-off Job
kubectl create job --from=cronjob/<name> manual-run -n <ns>
#config#debug
Block until matching pods are Ready or timeout
kubectl wait pod -l app=<label> -n <ns> --for=condition=Ready --timeout=120s
#pods#config
Tree of disks, partitions, loop devices with filesystem info
lsblk -o NAME,SIZE,TYPE,FSTYPE,MOUNTPOINT,UUID
#linux#disk#filesystem
Print UUID, LABEL, and FSTYPE for all block devices
blkid
#linux#disk#filesystem
Mount ext4 partition to /mnt/data
mount -t ext4 /dev/sdb1 /mnt/data
#linux#filesystem
List all real (non-virtual) mounted filesystems in a tree
findmnt --real
#linux#filesystem
Remount the root filesystem as read-write (e.g. after rescue boot)
mount -o remount,rw /
#linux#filesystem
Dry-run fsck check (no changes); unmount first for a live fix
fsck -n /dev/sdb1
#linux#filesystem#debug
Format partition as ext4 with a label
mkfs.ext4 -L datalabel /dev/sdb1
#linux#filesystem#disk
Grow ext4 to fill the partition (after partition resize)
resize2fs /dev/sdb1
#linux#filesystem#disk
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'
#linux#filesystem
Disk usage of /var up to 2 directory levels deep
du -h --max-depth=2 /var | sort -rh | head -20
#linux#disk
Show free space only for real filesystems (skip tmpfs/overlay)
df -hT --type=ext4 --type=xfs --type=btrfs
#linux#disk
Interactive MBR/GPT partition table editor
fdisk /dev/sdb
#linux#disk#partitions
Create a single GPT partition using the full disk
parted /dev/sdb -- mklabel gpt mkpart primary ext4 1MiB 100%
#linux#disk#partitions
List LVM physical volumes with space usage
pvs && pvdisplay
#linux#lvm#disk
List LVM volume groups with free PE
vgs && vgdisplay
#linux#lvm#disk
List logical volumes with device paths
lvs -o +devices
#linux#lvm#disk
Extend LVM logical volume by 10G and grow ext4 filesystem online
lvextend -L +10G /dev/vg0/lv_data && resize2fs /dev/vg0/lv_data
#linux#lvm#disk#filesystem
Allocate 2G swap file, set permissions, format and enable
fallocate -l 2G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile
#linux#disk#memory
List active swap spaces and overall memory/swap stats
swapon --show && free -h
#linux#memory
Brief list of all interfaces with IPs
ip -br a
#linux#network
All routing rules including policy routes
ip route show table all
#linux#network
Add a persistent-until-reboot static route
ip route add 10.0.0.0/8 via 192.168.1.1 dev eth0
#linux#network
Neighbour (ARP/NDP) cache with reachability state
ip neigh show
#linux#network
TX/RX bytes, errors, drops for an interface
ip -s link show eth0
#linux#network#monitoring
DNS lookup linux
Query A records via a specific DNS server
dig +short A example.com @8.8.8.8
#linux#network#dns
PTR record for an IP address
dig +short -x 8.8.8.8
#linux#network#dns
Follow full DNS resolution chain from root nameservers
dig +trace example.com
#linux#network#dns
All established TCP connections with process info
ss -tnp state established
#linux#network
How many connections are in ESTABLISHED, TIME_WAIT, etc.
ss -tan | awk 'NR>1{print $1}' | sort | uniq -c | sort -rn
#linux#network#monitoring
Combine traceroute and ping; TCP mode to bypass ICMP blocks
mtr --report --tcp --port 443 example.com
#linux#network#debug
Send DF-bit ping of 1500-byte frames to detect MTU issues
ping -M do -s 1472 -c 3 8.8.8.8
#linux#network#debug
All filter table rules with packet counters and line numbers
iptables -L -n -v --line-numbers
#linux#network#security
Full nftables ruleset in human-readable form
nft list ruleset
#linux#network#security
Measure TCP throughput with 4 parallel streams for 10 seconds
iperf3 -c <server_ip> -t 10 -P 4
#linux#network#monitoring
Real-time bandwidth per connection on an interface
iftop -i eth0 -n
#linux#network#monitoring
Kernel release string and full system info
uname -r && uname -a
#linux#kernel
Last 50 kernel errors/warnings with human-readable timestamps
dmesg -T --level=err,warn | tail -50
#linux#kernel#debug
All currently loaded kernel modules
lsmod | sort
#linux#kernel
Load a module with dependencies and verify
modprobe <module> && lsmod | grep <module>
#linux#kernel
Module parameters, version, license, and dependencies
modinfo <module>
#linux#kernel
List all kernel parameters; filter by name
sysctl -a | grep vm.swappiness
#linux#kernel
Enable IP forwarding at runtime (also add to /etc/sysctl.d/)
sysctl -w net.ipv4.ip_forward=1
#linux#kernel#network
Parameters passed to the kernel at boot time
cat /proc/cmdline
#linux#kernel
Allocated FDs, free FDs, and system-wide max (file-max)
cat /proc/sys/fs/file-nr
#linux#kernel#monitoring
Extended disk IO stats every 2s, 5 iterations; look for %iowait, await
iostat -xz 2 5
#linux#disk#monitoring
System-wide CPU, memory, swap, IO stats per second
vmstat 1 5
#linux#memory#monitoring
Accumulated disk read/write per process (requires root)
iotop -ao
#linux#disk#monitoring
CPU, memory, and disk stats via sysstat (5 samples, 1s interval)
sar -u -r -d 1 5
#linux#monitoring
Trace network and file syscalls of a running process
strace -f -e trace=network,file -p <pid>
#linux#debug#monitoring
Hardware CPU counters during a 5-second window
perf stat -e cycles,instructions,cache-misses -- sleep 5
#linux#monitoring#performance
CPU model, socket/core/thread topology, and clock speed
lscpu | grep -E 'Model|Socket|Core|Thread|MHz'
#linux#hardware
Physical DIMM slots: size, speed, type (requires root)
dmidecode -t memory | grep -E 'Size|Speed|Locator|Type:'
#linux#hardware
Network cards, GPUs, NVMe controllers with driver info
lspci -v | grep -A5 'VGA\|Ethernet\|NVMe'
#linux#hardware
Prevent any user (incl. root) from modifying the file
chattr +i /etc/resolv.conf && lsattr /etc/resolv.conf
#linux#filesystem#security
List non-default extended attrs in /etc/
lsattr -R /etc/ 2>/dev/null | grep -v '^\-\-\-\-'
#linux#filesystem
Show POSIX ACL entries including owner, group, and extra users
getfacl /srv/shared
#linux#filesystem#security
Grant alice full access without changing group ownership
setfacl -m u:alice:rwx /srv/shared
#linux#filesystem#security
Locate setuid/setgid executables (security audit)
find / -perm /6000 -type f -ls 2>/dev/null
#linux#security
List PIDs and full command lines matching a name
pgrep -la nginx
#linux
Send SIGTERM to the entire process group
kill -TERM -$(pgrep -f 'my-app')
#linux
Lower priority (nice +10) of a running process
renice -n 10 -p <pid>
#linux#performance
Run a command in a transient systemd scope with resource limits
systemd-run --scope -p MemoryMax=512M -p CPUQuota=50% -- ./heavy.sh
#linux#performance#cgroups
Logs for nginx between two timestamps
journalctl --since '2024-01-15 10:00' --until '2024-01-15 10:30' -u nginx
#linux#logs
Structured log export for ingestion into log aggregators
journalctl -u <service> -o json | jq '{ts: .REALTIME_TIMESTAMP, msg: .MESSAGE}'
#linux#logs
Clock sync state, offset, and NTP source details
timedatectl status && chronyc tracking
#linux#network
All timers with last/next trigger times
systemctl list-timers --all --no-pager
#linux
Append public key to remote authorized_keys
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host
#linux#ssh
Mirror directory to remote with deletion of extra files
rsync -avz --progress --delete src/ user@host:/dest/
#linux#filesystem
One-pass overwrite with zeros + verify (use hdparm ATA for NVMe)
shred -vzn 1 /dev/sdb
#linux#disk#security
SMART overall health and key failure indicators
smartctl -a /dev/sda | grep -E 'SMART overall|Reallocated|Pending|Uncorrectable'
#linux#disk#monitoring
Write 1GB with forced sync to measure raw write speed
dd if=/dev/zero of=/tmp/testfile bs=1M count=1024 conv=fdatasync
#linux#disk#performance
List Linux namespaces for network, PID, and mount isolation
lsns -t net,pid,mnt
#linux#kernel#containers
Tree view of systemd cgroup hierarchy and resource assignments
systemd-cgls
#linux#kernel#cgroups
Find the biggest log files by line count
find /var/log -name '*.log' -exec wc -l {} + | sort -rn | head -20
#linux#logs
Stream multiple log files interleaved in one terminal
tail -f /var/log/syslog /var/log/auth.log
#linux#logs
grep inside .gz files without manual decompression
zgrep -i 'error' /var/log/syslog.*.gz
#linux#logs
Force log rotation regardless of schedule
logrotate -f /etc/logrotate.conf
#linux#logs
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
#linux
Parse and show next 5 trigger times for a cron expression
systemd-analyze calendar '*/5 * * * *'
#linux
Split stdout and stderr into separate files
command > /tmp/out.log 2> /tmp/err.log
#linux
Redirect stdout+stderr to file and screen simultaneously
command 2>&1 | tee /tmp/all.log
#linux
Find files containing text, then replace in-place
grep -rl 'old_string' /etc/ | xargs sed -i 's/old_string/new_string/g'
#linux
Print 1st and 3rd fields of a space-delimited file
awk '{print $1, $3}' /etc/passwd
#linux
Sum values in column 2 of a text file
awk '{sum += $2} END {print sum}' file.txt
#linux
Remove all comment lines starting with #
sed -i '/^#/d' config.conf
#linux
Print block of text between START and END markers
sed -n '/START/,/END/p' file.txt
#linux
Count occurrences of each unique line
sort file.txt | uniq -c | sort -rn
#linux
Active user sessions and what they are running
who -H && w
#linux#security
Last logins linux
Last 20 login records with IP and duration
last -n 20 | head -25
#linux#security
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
#linux#security
List sudo rules for a specific user
sudo -l -U <username>
#linux#security
Append user to multiple groups without removing existing ones
usermod -aG docker,sudo alice
#linux
Total virtual memory size of a process from smaps
cat /proc/<pid>/smaps | awk '/^Size/{sum+=$2} END{print sum/1024" MB"}'
#linux#memory#debug
Check if THP / hugepages are used and configured
grep -E 'HugePages|AnonHugePages|Transparent' /proc/meminfo
#linux#memory#kernel
Disable THP at runtime (fix for Redis, MongoDB latency spikes)
echo never > /sys/kernel/mm/transparent_hugepage/enabled
#linux#memory#kernel
NUMA nodes, CPU assignment, and memory distribution
numactl --hardware
#linux#hardware#performance
Increase socket listen backlog for high-connection services
sysctl -w net.core.somaxconn=65535 net.ipv4.tcp_max_syn_backlog=65535
#linux#network#kernel
Enable Google BBR congestion control for better throughput
sysctl -w net.core.default_qdisc=fq net.ipv4.tcp_congestion_control=bbr
#linux#network#kernel#performance
All UDP listening sockets with process info
ss -ulnp
#linux#network
Pin a running process to specific CPU cores
taskset -cp 0,1 <pid>
#linux#performance
Per-CPU interrupt counts, updated every second
watch -n1 'cat /proc/interrupts | head -30'
#linux#hardware#monitoring
Hard and soft resource limits for a running process
cat /proc/<pid>/limits
#linux#debug
Set high FD limit for current session and persist it
ulimit -n 1048576 && echo '* soft nofile 1048576 * hard nofile 1048576' >> /etc/security/limits.conf
#linux#kernel#performance
Rewrite the most recent commit message (local only)
git commit --amend -m 'new message'
#git
Squash, reorder, or edit last 5 commits
git rebase -i HEAD~5
#git
Stash only src/ with a descriptive name
git stash push -m 'wip: feature-x' -- src/
#git
List stashes and apply a specific one by index
git stash list && git stash apply stash@{2}
#git
Apply commits from A to B (inclusive) onto current branch
git cherry-pick A^..B
#git
Annotate lines 10–25 with author and date
git blame -L 10,25 --date=short src/main.py
#git#debug
Binary search through history to find the breaking commit
git bisect start && git bisect bad HEAD && git bisect good v1.0
#git#debug
List files added, modified, deleted between two branches
git diff --name-status main..feature/x
#git
ASCII branch graph of the full commit history
git log --oneline --graph --decorate --all
#git
Move HEAD back one commit; staged changes return to working tree
git reset HEAD~1
#git
Reset tracked files and remove untracked files/directories
git restore . && git clean -fd
#git
List all tags with their first annotation line
git tag -l -n1
#git
GPG-signed annotated tag for releases
git tag -s v1.2.3 -m 'Release 1.2.3'
#git#security
Remove local refs to remote branches that no longer exist
git fetch --prune
#git
Clone only the latest commit of one branch (fast CI checkout)
git clone --depth=1 --single-branch --branch main <url>
#git
Ranked list of authors by total commit count
git shortlog -sn --all
#git
Find all commits whose message contains a pattern
git log --all --grep='fix:' --oneline
#git
Find when a string was added or removed across all branches
git log -S 'functionName' --patch --all
#git#debug
Download commits and trees; blobs fetched on-demand (fast)
git clone --filter=blob:none <url>
#git
Check out a branch in a separate directory without switching
git worktree add ../hotfix-branch hotfix/urgent
#git
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 .
#docker
Build and push multi-arch image using BuildKit
docker buildx build --platform linux/amd64,linux/arm64 -t myapp:latest --push .
#docker
Show all layers with full commands and sizes
docker history --no-trunc <image>
#docker#debug
Inspect a container's merged filesystem as a tar stream
docker export <container> | tar -tvf - | head -30
#docker#debug
Files added (A), changed (C), or deleted (D) in a running container
docker diff <container>
#docker#debug
Snapshot a running container's filesystem as an image
docker commit -m 'debug snapshot' <container> debug-snapshot:$(date +%s)
#docker#debug
Limit container to 512MB RAM and half a CPU core
docker run --memory=512m --cpus=0.5 --oom-kill-disable=false myapp
#docker#performance
One-shot CPU and memory snapshot for all containers
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}'
#docker#monitoring
Remove all <none>:<none> dangling images
docker image prune -f
#docker
Remove stopped containers, unused images, networks, volumes
docker system prune -a --volumes -f
#docker
Extract a single file from a running or stopped container
docker cp <container>:/app/config.yaml ./local-config.yaml
#docker#debug
Rebuild and start services, remove containers not in compose file
docker compose up -d --build --remove-orphans
#docker
Run 5 replicas of the worker service
docker compose up -d --scale worker=5
#docker
Stream last 100 lines of a specific compose service
docker compose logs -f --tail=100 worker
#docker#logs
Show IPs of all containers in the bridge network
docker network inspect bridge | jq '.[0].Containers | to_entries[] | .value | {Name, IPv4Address}'
#docker#network
Create a bridge network with a custom subnet
docker network create --driver bridge --subnet 172.30.0.0/24 mynet
#docker#network
Export image to archive and reimport on another host
docker save myapp:1.0 | gzip > myapp.tar.gz && docker load < myapp.tar.gz
#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
Show only CVEs that already have a fix available
docker scout cves --only-fixed myapp:latest
#docker#security
Full-featured network debug container sharing host PID and network
docker run --rm -it --pid=host --network=host --privileged nicolaka/netshoot
#docker#debug#network
Send JSON payload via POST
curl -X POST https://api.example.com/v1/items -H 'Content-Type: application/json' -d '{"name":"foo"}'
#curl
Attach JWT/Bearer token in Authorization header
curl -H 'Authorization: Bearer $TOKEN' https://api.example.com/me
#curl#security
Follow up to 5 redirects and show full request/response
curl -Lv --max-redirs 5 https://example.com
#curl#debug
Download silently, fail on error, follow redirects
curl -sSL -o /tmp/result.json https://api.example.com/data
#curl
Benchmark TTFB and total request time
curl -o /dev/null -sS -w 'ttfb: %{time_starttransfer}s\ntotal: %{time_total}s\n' https://example.com
#curl#monitoring
Print HTTP response headers without body
curl -sI https://example.com
#curl#debug
Multipart form-data upload with extra fields
curl -F 'file=@./report.pdf' -F 'user=alice' https://upload.example.com/api
#curl
Force HTTP/2 and check protocol in response
curl --http2 -sI https://example.com | grep -i 'http\|alt-svc'
#curl#network
Override DNS for a host:port pair (test behind CDN/LB)
curl --resolve example.com:443:1.2.3.4 https://example.com
#curl#network#debug
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
#curl
Send URL-encoded form data
curl -d 'user=alice&pass=secret' -X POST https://auth.example.com/login
#curl
mTLS request with client cert and custom CA
curl --cert client.crt --key client.key --cacert ca.crt https://secure.example.com
#curl#security
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' {}
#curl
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
#curl#network#debug
Limit download bandwidth to 1 MB/s
curl --limit-rate 1M -O https://example.com/bigfile.iso
#curl
Stream every command sent to Redis (exclude health pings)
redis-cli MONITOR | grep -v PING
#redis#debug#monitoring
Last 20 slow commands with execution time in microseconds
redis-cli SLOWLOG GET 20
#redis#debug#monitoring
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"}'
#redis#monitoring
Safely scan-delete matching keys without KEYS command
redis-cli --scan --pattern 'cache:*' | xargs -r redis-cli DEL
#redis
Set key with 1-hour expiry (EX = seconds)
redis-cli SET mykey 'value' EX 3600
#redis
Atomically increment an integer counter
redis-cli INCRBY counter:hits 1
#redis
Publish a message to a Redis pub/sub channel
redis-cli PUBLISH events '{"type":"login","user":"alice"}'
#redis
Subscribe and listen to messages on a channel
redis-cli SUBSCRIBE events
#redis
Role, connected replicas, replication lag
redis-cli INFO replication
#redis#monitoring
Trigger background RDB save and check its timestamp
redis-cli BGSAVE && redis-cli LASTSAVE
#redis
Asynchronously flush database index 1 only
redis-cli -n 1 FLUSHDB ASYNC
#redis
Top 10 entries from a sorted set with scores
redis-cli ZREVRANGEBYSCORE leaderboard +inf -inf WITHSCORES LIMIT 0 10
#redis
Append a message to a Redis Stream with auto-ID
redis-cli XADD mystream '*' event login user alice
#redis
Cluster info redis
Cluster health and node list with slot ranges
redis-cli -c CLUSTER INFO && redis-cli -c CLUSTER NODES
#redis#monitoring
100k requests, 50 clients, 10 pipeline depth (quiet output)
redis-benchmark -q -n 100000 -c 50 -P 10
#redis#performance
Check SSH connectivity and Python for all hosts
ansible all -m ping -i inventory.ini
#ansible
Run a shell command on all hosts in the webservers group
ansible webservers -m shell -a 'uptime && free -h' -i inventory.ini
#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}'
#ansible#debug
Show what would change without making any modifications
ansible-playbook site.yml --check --diff -i inventory.ini
#ansible#debug
Override variables from the command line
ansible-playbook deploy.yml -e 'env=prod version=2.1.0' -i inventory.ini
#ansible
Run playbook only on specified hosts
ansible-playbook site.yml --limit 'web-01,web-02' -i inventory.ini
#ansible
Execute only tasks marked with specified tags
ansible-playbook site.yml --tags 'config,restart' -i inventory.ini
#ansible
Skip tasks with specified tags
ansible-playbook site.yml --skip-tags 'slow,optional' -i inventory.ini
#ansible
Maximum verbosity for debugging; save to log
ansible-playbook site.yml -vvv -i inventory.ini 2>&1 | tee /tmp/ansible.log
#ansible#debug
Inline-encrypt a value for use in playbook vars
ansible-vault encrypt_string 'supersecret' --name 'db_password'
#ansible#security
Display decrypted content of a vault-encrypted file
ansible-vault view group_vars/all/vault.yml
#ansible#security
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
#ansible
Ad-hoc service restart with privilege escalation (-b)
ansible webservers -m service -a 'name=nginx state=restarted' -b -i inventory.ini
#ansible
Display inventory group hierarchy as a tree
ansible-inventory -i inventory.ini --graph
#ansible
Run full Molecule test suite: create, converge, verify, destroy
molecule test -s default
#ansible#debug
Display all values (user + chart defaults) for a release
helm get values <release> -n <ns> --all
#helm#debug
Render and validate manifests without installing
helm template myrelease ./mychart -f values-prod.yaml | kubectl apply --dry-run=client -f -
#helm#debug
Show YAML diff between current and new release (requires helm-diff plugin)
helm diff upgrade <release> ./mychart -f values.yaml -n <ns>
#helm#debug
Roll back automatically if upgrade does not succeed in 5m
helm upgrade <release> ./mychart -n <ns> -f values.yaml --atomic --timeout 5m
#helm
Override specific chart values from command line
helm upgrade <release> ./mychart --set image.tag=v1.5.0 --set replicaCount=3
#helm
Print the Kubernetes YAML applied by the current release
helm get manifest <release> -n <ns>
#helm#debug
Show history and roll back to previous revision (0 = latest-1)
helm history <release> -n <ns> && helm rollback <release> 0 -n <ns>
#helm
List all available versions of a chart in configured repos
helm search repo <chart> --versions | head -20
#helm
Print default values.yaml for a chart version
helm show values <repo>/<chart> --version <ver>
#helm
Create a versioned .tgz chart archive
helm package ./mychart --destination ./dist
#helm
Upload chart package to an OCI-compliant container registry
helm push mychart-1.0.0.tgz oci://registry.example.com/charts
#helm
Install a chart directly from an OCI registry
helm install myrelease oci://registry.example.com/charts/mychart --version 1.0.0
#helm
Lint chart helm
Validate chart structure and templates with strict mode
helm lint ./mychart -f values-prod.yaml --strict
#helm#debug
Force replace resources that can't be patched (delete+create)
helm upgrade <release> ./mychart -n <ns> --force
#helm
Install helm-diff plugin for release comparison
helm plugin install https://github.com/databus23/helm-diff
#helm
Format all files terraform
Recursively format all .tf files in subdirectories
terraform fmt -recursive
#terraform
Check configuration syntax without accessing remote state
terraform validate
#terraform#debug
Plan with var file terraform
Generate plan with prod variables, save to file
terraform plan -var-file=prod.tfvars -out=prod.tfplan
#terraform
Apply saved plan terraform
Apply exactly the plan generated earlier (no re-prompts)
terraform apply prod.tfplan
#terraform
Display all attributes of a specific resource in state
terraform state show 'aws_instance.web[0]'
#terraform#debug
Rename or move a resource without destroying it
terraform state mv 'aws_instance.web' 'module.app.aws_instance.web'
#terraform
Bring an existing resource under Terraform management
terraform import 'aws_s3_bucket.mybucket' my-existing-bucket
#terraform
Mark resource to be destroyed and recreated on next apply
terraform taint 'aws_instance.web[0]'
#terraform
Remove a resource from state without destroying it in the cloud
terraform state rm 'aws_instance.legacy'
#terraform
Show outputs terraform
Print all outputs as compact JSON
terraform output -json | jq 'to_entries[] | {(.key): .value.value}'
#terraform
Destroy a single resource without full plan
terraform destroy -target='aws_instance.web' -auto-approve
#terraform
Unlock stuck state terraform
Release a stuck state lock after a failed apply
terraform force-unlock <lock-id>
#terraform#debug
Create and activate a Terraform workspace
terraform workspace new staging && terraform workspace select staging
#terraform
Render resource dependency graph as SVG (requires graphviz)
terraform graph | dot -Tsvg > graph.svg && open graph.svg
#terraform#debug
Lock provider versions for multiple platforms in .terraform.lock.hcl
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64
#terraform
Filter array elements where value is not null
jq '[.[] | select(.value != null)]' data.json
#jq
Count records grouped by status field
jq 'group_by(.status) | map({status: .[0].status, count: length})' data.json
#jq
Flatten one level of nested arrays
jq 'flatten(1)' nested.json
#jq
Build an object keyed by the id field
jq 'INDEX(.[]; .id)' items.json
#jq
Deep merge two JSON objects (right wins on conflicts)
jq -s '.[0] * .[1]' base.json override.json
#jq
Optional chaining with fallback default value
jq '.config?.database?.host // "localhost"' config.json
#jq
Get 5 most recent events sorted by timestamp descending
jq 'sort_by(.timestamp) | reverse | .[0:5]' events.json
#jq
Output selected fields as comma-separated values
jq -r '.[] | [.id, .name, .status] | @csv' data.json
#jq
Inject a new key-value pair into every array element
jq '[.[] | . + {"env": "prod"}]' items.json
#jq
Recursively lowercase all string values in a JSON document
jq 'walk(if type == "string" then ascii_downcase else . end)' data.json
#jq
Run an instant PromQL query via HTTP API
curl -sG 'http://prometheus:9090/api/v1/query' --data-urlencode 'query=up' | jq '.data.result'
#prometheus#monitoring
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'
#prometheus#monitoring
PromQL: top 10 pods by CPU usage rate
topk(10, sum by (pod) (rate(container_cpu_usage_seconds_total[5m])))
#prometheus#monitoring
PromQL expression: fire when root disk > 85% used
100 - (node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"} * 100) > 85
#prometheus#monitoring
Hot reload Prometheus config and rules without restart
curl -X POST http://prometheus:9090/-/reload
#prometheus
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}'
#prometheus#monitoring
Count total metric names and preview first 20
curl -s http://prometheus:9090/api/v1/label/__name__/values | jq '.data | length, .[0:20]'
#prometheus#debug
PromQL: count active time series grouped by job label
count by (job) ({__name__=~".+"})
#prometheus#monitoring
Silence an alert prometheus
Create an Alertmanager silence for 2 hours
amtool silence add alertname=HighMemory --duration=2h --comment='Investigating'
#prometheus#monitoring
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}'
#prometheus#monitoring
Interactive psql session to a database
psql -h localhost -U myuser -d mydb
#postgres
List databases postgres
Show all databases with size and encoding
psql -U postgres -c '\l+'
#postgres
List all tables in the public schema
psql -U myuser -d mydb -c '\dt public.*'
#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;'
#postgres#debug#performance
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;"
#postgres#monitoring#performance
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;"
#postgres#monitoring
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';"
#postgres#debug
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;"
#postgres#monitoring
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;"
#postgres#monitoring#performance
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;"
#postgres#performance
Dump database postgres
Custom-format dump (fastest, supports parallel restore)
pg_dump -U myuser -d mydb -F c -f mydb.dump
#postgres
Restore database postgres
Parallel restore with 4 workers, drop existing objects first
pg_restore -U myuser -d mydb -j 4 --clean mydb.dump
#postgres
Reclaim dead tuples and update statistics for query planner
psql -U myuser -d mydb -c 'VACUUM (VERBOSE, ANALYZE) orders;'
#postgres#performance
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;"
#postgres#monitoring
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;"
#postgres#debug
Validate nginx.conf without reloading
nginx -t
#nginx
Gracefully reload config — zero connection drop
nginx -s reload
#nginx
List all built-in and dynamic modules in the binary
nginx -V 2>&1 | tr ' ' '\n' | grep module
#nginx#debug
Stream IP, path, status code, and response size
tail -f /var/log/nginx/access.log | awk '{print $1, $7, $9, $10}'
#nginx#logs#monitoring
Frequency of each HTTP status code in access log
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
#nginx#monitoring
Most popular request paths from access log
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10
#nginx#monitoring
Top 10 client IPs hitting the server
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10
#nginx#monitoring#security
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;
#nginx#security
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; }
#nginx#network
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;
#nginx#performance
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"}'; }
#nginx
Permanent redirect all HTTP traffic to HTTPS
server { listen 80; return 301 https://$host$request_uri; }
#nginx#security
Built-in nginx status page: active, reading, writing, waiting
curl -s http://localhost/stub_status
#nginx#monitoring
Block a subnet and specific IP in nginx location/server block
deny 192.168.1.0/24; deny 10.0.0.1; allow all;
#nginx#security
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'; }
#nginx#network
Generate a 4096-bit RSA private key
openssl genrsa -out private.key 4096
#openssl#security
Modern Ed25519 key (smaller, faster than RSA)
openssl genpkey -algorithm ed25519 -out private.key && openssl pkey -in private.key -pubout -out public.key
#openssl#security
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'
#openssl#security
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'
#openssl#security
Show subject, issuer, validity dates, SANs
openssl x509 -in cert.pem -noout -text | grep -E 'Subject:|Issuer:|Not (Before|After)|DNS:'
#openssl#security#debug
Print notBefore and notAfter dates
openssl x509 -in cert.pem -noout -dates
#openssl#security
Check certificate chain against a CA bundle
openssl verify -CAfile ca.pem cert.pem
#openssl#security#debug
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'
#openssl#security#debug
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
#openssl#security
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
#openssl#security
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
#openssl#security#network
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:'
#openssl#security#debug
Password-encrypt a file with AES-256-CBC + PBKDF2
openssl enc -aes-256-cbc -pbkdf2 -in secret.txt -out secret.enc
#openssl#security
Decrypt a file encrypted with the enc command above
openssl enc -d -aes-256-cbc -pbkdf2 -in secret.enc -out secret.txt
#openssl#security
Generate a 64-char hex random string (e.g. for API keys)
openssl rand -hex 32
#openssl#security
Start a new tmux session named 'work'
tmux new-session -s work
#tmux
Attach to an existing named session
tmux attach-session -t work
#tmux
Show all active tmux sessions
tmux ls
#tmux
Detach from current session leaving it running in background
<prefix> d
#tmux
Terminate a named session and all its windows
tmux kill-session -t work
#tmux
Split current pane into left and right
<prefix> %
#tmux
Split current pane into top and bottom
<prefix> "
#tmux
Move focus to adjacent pane
<prefix> <arrow keys>
#tmux
Resize current pane down 5 rows (-U up, -L left, -R right)
tmux resize-pane -D 5
#tmux
New window tmux
Create a new window in current session
<prefix> c
#tmux
Rename the current window
<prefix> ,
#tmux
Jump to window by its index number
<prefix> 0-9
#tmux
Enter scroll/copy mode; use arrows or vi keys to navigate
<prefix> [
#tmux
Send keystrokes to all panes simultaneously (multi-server ops)
tmux setw synchronize-panes on
#tmux
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
#tmux
Search all files under /var/log for 'error' (any case)
grep -ri 'error' /var/log/
#grep
Print 3 lines before and 5 lines after each match
grep -B3 -A5 'FATAL' app.log
#grep#debug
Print only the number of matching lines
grep -c 'POST /api' /var/log/nginx/access.log
#grep#monitoring
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
#grep
Remove comment and blank lines from a config file
grep -v '^#' /etc/nginx/nginx.conf | grep -v '^\s*$'
#grep
Limit recursive search to .py files only
grep -r --include='*.py' 'import os' /srv/app/
#grep
Search recursively skipping vcs and dependency dirs
grep -r --exclude-dir='.git' --exclude-dir='node_modules' 'TODO' .
#grep
Show file and line number for each match
grep -rn 'panic:' /var/log/app/
#grep#debug
List files containing TODO/FIXME/HACK in Python files
rg 'TODO|FIXME|HACK' --type py -l
#grep
3 lines of context around matches in Go files
rg 'panic' -C3 --glob '*.go'
#grep#debug
Search hidden and .gitignore'd files
rg 'secret_key' --hidden --no-ignore
#grep#security
Preview how a replacement would look without writing
rg 'old_value' --replace 'new_value' --passthru config.yaml
#grep
Show total matches, files searched, elapsed time
rg 'error' /var/log/ --stats 2>&1 | tail -5
#grep#monitoring
Treat binary as text (-a) to search process memory
grep -a 'password' /proc/<pid>/mem 2>/dev/null | strings | head -20
#grep#security#debug
Match lines containing ERROR, WARN, or CRIT
grep -E '(ERROR|WARN|CRIT)' app.log | tail -50
#grep
Enable at boot and start immediately in one command
systemctl enable --now myapp.service
#systemd
List all units that are in a failed state
systemctl list-units --state=failed
#systemd#debug
Reload unit definitions and restart the service
systemctl daemon-reload && systemctl restart myapp.service
#systemd
Create /etc/systemd/system/myapp.service.d/override.conf with partial overrides
systemctl edit myapp.service
#systemd
Print the full unit file including drop-ins
systemctl cat myapp.service
#systemd#debug
Show top 20 units by initialization time
systemd-analyze blame | head -20
#systemd#performance#monitoring
Render full boot dependency graph as SVG
systemd-analyze dot --require | dot -Tsvg > boot.svg && open boot.svg
#systemd#debug
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
#systemd
Run a transient one-shot unit under a specific user
systemd-run --uid=1000 --gid=1000 --wait /usr/bin/myapp --task
#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
#systemd
Apply cgroup limits without editing unit file
systemctl set-property myapp.service MemoryMax=512M CPUQuota=50%
#systemd#performance
Current memory, CPU, and task counts from cgroup
systemctl status myapp.service | grep -E 'Memory:|CPU:|Tasks:'
#systemd#monitoring
All socket-activated units and their state
systemctl list-units --type=socket --all
#systemd#network
Mask a service systemd
Prevent a service from being started by anything
systemctl mask snapd.service
#systemd#security
Print environment variables injected into the service
systemctl show myapp.service -p Environment
#systemd#debug
Create and activate an isolated Python environment
python3 -m venv .venv && source .venv/bin/activate
#python
Install dependencies without using pip cache
pip install -r requirements.txt --no-cache-dir
#python
Save exact versions of all installed packages
pip freeze > requirements.txt
#python
List packages with newer versions available
pip list --outdated --format=columns
#python
Serve current directory over HTTP on port 8080
python3 -m http.server 8080
#python
Pretty-print a JSON file using stdlib
python3 -m json.tool < input.json
#python
CPU profiling sorted by cumulative time
python3 -m cProfile -s cumulative script.py | head -30
#python#performance#debug
Start script under the Python debugger
python3 -m pdb script.py
#python#debug
Built-in breakpoint() is equivalent to import pdb; pdb.set_trace()
breakpoint() # Python 3.7+ — drops into pdb at this line
#python#debug
Stop at first failure, verbose, short traceback
pytest -x -v --tb=short tests/
#python#debug
Compile to bytecode only to catch syntax errors
python3 -m py_compile script.py && echo OK
#python#debug
Preview changes then apply Black formatting
black --check --diff . && black .
#python
Fast linter + auto-fix (replaces flake8, isort, pyupgrade)
ruff check . --fix
#python
Strict static type checking for a package
mypy --strict --ignore-missing-imports src/
#python#debug
List public attributes of any Python object
python3 -c "import json; print([x for x in dir(json) if not x.startswith('_')])"
#python#debug
Specify an identity file explicitly
ssh -i ~/.ssh/id_ed25519 user@host
#ssh
Single-hop jump through bastion host
ssh -J bastion.example.com user@internal-host
#ssh#network
Chain multiple jump hosts in one command
ssh -J user@bastion1,user@bastion2 user@target
#ssh#network
Forward localhost:5432 to db.internal:5432 via bastion
ssh -L 5432:db.internal:5432 user@bastion -N
#ssh#network
Expose local port 3000 as port 8080 on VPS
ssh -R 8080:localhost:3000 user@vps -N
#ssh#network
Create a local SOCKS5 proxy tunnelled through VPS
ssh -D 1080 user@vps -N -f
#ssh#network#security
Reuse existing connection for subsequent SSH commands
ssh -o ControlMaster=auto -o ControlPath=~/.ssh/mux-%r@%h:%p -o ControlPersist=10m user@host
#ssh#performance
Execute a command over SSH without interactive shell
ssh user@host 'sudo systemctl status nginx'
#ssh
Recursive copy on non-standard port
scp -r -P 2222 ./dist/ user@host:/var/www/app/
#ssh
Forward local SSH agent to the remote host (use with caution)
ssh -A user@bastion
#ssh#security
Start agent and load a key for the session
eval $(ssh-agent) && ssh-add ~/.ssh/id_ed25519
#ssh
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
#ssh
Terminate a frozen/hung SSH session: type tilde then dot
~.
#ssh#debug
Fetch and fingerprint server host keys without connecting
ssh-keyscan -t ed25519,rsa host 2>/dev/null | ssh-keygen -lf -
#ssh#security
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
#ssh#security
Kibana Query Language — filter logs by field values
status: 404 AND method: GET
#kibana
Filter events in the last hour with slow responses
response_time > 500 AND @timestamp > now-1h
#kibana#monitoring
Wildcard match in a field value
message: *OOMKilled*
#kibana#debug
Filter by nested Kubernetes metadata fields
kubernetes.pod.name: web-* AND kubernetes.namespace: prod
#kibana#debug
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"}}'
#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
#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
#kibana
Overall health status and Kibana version
curl -s http://kibana:5601/api/status | jq '{status: .status.overall.level, version: .version.number}'
#kibana#monitoring
Show all registered index patterns
curl -s http://kibana:5601/api/saved_objects/_find?type=index-pattern | jq '.saved_objects[].attributes.title'
#kibana
Run Elasticsearch queries directly in Kibana Dev Tools
GET logs-*/_search { "query": {"match": {"level": "error"}}, "size": 10 }
#kibana#elasticsearch#debug
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'
#kibana#debug
List all Kibana Spaces by ID
curl -s http://kibana:5601/api/spaces/space | jq '.[].id'
#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}'
#kibana
Seal a secret from file sealed-secrets
Encrypt a Kubernetes Secret YAML into a SealedSecret
kubeseal --format=yaml < secret.yaml > sealed-secret.yaml
#sealed-secrets#security
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
#sealed-secrets#security
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
#sealed-secrets#security
Seal offline with cert sealed-secrets
Encrypt without cluster access using saved cert
kubeseal --cert pub.pem --format yaml < secret.yaml > sealed.yaml
#sealed-secrets#security
Stream controller logs to debug sealing issues
kubectl logs -n kube-system -l app.kubernetes.io/name=sealed-secrets -f
#sealed-secrets#debug
List all SealedSecrets sealed-secrets
Show all SealedSecrets across namespaces
kubectl get sealedsecrets -A
#sealed-secrets
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
#sealed-secrets#security
Check SecretStore status external-secrets
Show all SecretStores and their sync status
kubectl get secretstore,clustersecretstore -A -o wide
#external-secrets#debug
Force ExternalSecret refresh external-secrets
Trigger immediate re-sync by updating annotation
kubectl annotate externalsecret mysecret force-sync=$(date +%s) --overwrite
#external-secrets
View sync conditions: Ready, SecretSynced
kubectl get externalsecret mysecret -o jsonpath='{.status.conditions[*]}'
#external-secrets#debug
Inspect value templating in ExternalSecret spec
kubectl get externalsecret mysecret -o yaml | grep -A10 'template:'
#external-secrets#debug
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'
#external-secrets
Extract a single field from YAML
yq '.spec.replicas' deployment.yaml
#yq
Modify YAML file in-place with yq v4
yq -i '.spec.replicas = 3' deployment.yaml
#yq
Append an env var to the first container
yq -i '.spec.containers[0].env += {"name":"DEBUG","value":"true"}' deployment.yaml
#yq
Remove a specific annotation from YAML
yq -i 'del(.metadata.annotations."kubectl.kubernetes.io/last-applied-configuration")' resource.yaml
#yq
Deep-merge two YAML documents
yq eval-all 'select(fileIndex==0) * select(fileIndex==1)' base.yaml override.yaml
#yq
Output YAML document as JSON
yq -o=json '.' config.yaml
#yq
Pretty-print JSON as YAML
cat config.json | yq -P '.'
#yq
Select only Running pods from a list
yq '.items[] | select(.status.phase == "Running")' pods.yaml
#yq#debug
Targeted image update for a named container
yq -i '(.spec.template.spec.containers[] | select(.name == "app") | .image) = "myapp:v2.0.0"' deployment.yaml
#yq#ci
Extract metadata.name from all YAML files in a directory
yq '.metadata.name' manifests/*.yaml
#yq
Run terraform plan in the current Terragrunt module
terragrunt plan
#terragrunt#terraform
Apply all modules in the stack in dependency order
terragrunt run-all apply
#terragrunt#terraform
Destroy all modules terragrunt
Destroy all stack modules non-interactively
terragrunt run-all destroy --terragrunt-non-interactive
#terragrunt#terraform
Run terraform validate across all modules
terragrunt run-all validate
#terragrunt#terraform
Show all Terragrunt outputs as JSON
terragrunt output -json | jq '.'
#terragrunt
Init with upgrade terragrunt
Re-initialise and upgrade provider locks
terragrunt init --upgrade
#terragrunt#terraform
Render final config terragrunt
Dump the resolved terragrunt.hcl as JSON (debug)
terragrunt render-json
#terragrunt#debug
Visualise Terragrunt module dependency graph
terragrunt graph-dependencies | dot -Tsvg > deps.svg
#terragrunt
Skip a specific module during stack-wide operations
terragrunt run-all plan --terragrunt-exclude-dir ./module-to-skip
#terragrunt
Fetch dependency outputs from state to avoid ordering issues
terragrunt apply --terragrunt-no-auto-approve --terragrunt-fetch-dependency-output-from-state
#terragrunt#terraform
Attach an ephemeral debug container to a running pod
kubectl debug -it mypod --image=busybox --target=app
#k8s-debug#kubectl
Get privileged shell on a cluster node via debug pod
kubectl debug node/my-node -it --image=ubuntu
#k8s-debug#kubectl
Open shell in a specific container of a multi-container pod
kubectl exec -it mypod -c sidecar-name -- /bin/sh
#k8s-debug#kubectl
Show resource requests and limits for each container
kubectl get pod mypod -o jsonpath='{range .spec.containers[*]}{.name}{"\t"}{.resources}{"\n"}{end}'
#k8s-debug#kubectl
Check node conditions: Ready, MemoryPressure, DiskPressure
kubectl describe node my-node | grep -A5 'Conditions:'
#k8s-debug#kubectl
Top 20 pods sorted by memory consumption
kubectl top pods -A --sort-by=memory | head -20
#k8s-debug#kubectl#monitoring
Watch pod events k8s-debug
Stream events for a specific pod
kubectl get events -n mynamespace --field-selector involvedObject.name=mypod --watch
#k8s-debug#kubectl
Copy file from pod k8s-debug
Download a file from a running container
kubectl cp mynamespace/mypod:/var/log/app.log ./app.log
#k8s-debug#kubectl
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
#kafka
Show per-partition lag for a consumer group
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --describe --group my-group
#kafka#monitoring
Reset consumer offsets to earliest
kafka-consumer-groups.sh --bootstrap-server kafka:9092 --group my-group --reset-offsets --to-earliest --topic my-topic --execute
#kafka
Produce key:value messages interactively
kafka-console-producer.sh --bootstrap-server kafka:9092 --topic my-topic --property 'key.separator=:' --property 'parse.key=true'
#kafka
Read first 10 messages from a topic
kafka-console-consumer.sh --bootstrap-server kafka:9092 --topic my-topic --from-beginning --max-messages 10
#kafka
Increase partition count (cannot decrease)
kafka-topics.sh --bootstrap-server kafka:9092 --alter --topic my-topic --partitions 12
#kafka
Show all overridden config values for a topic
kafka-configs.sh --bootstrap-server kafka:9092 --describe --entity-type topics --entity-name my-topic
#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
#kafka
List all API versions supported by the broker
kafka-broker-api-versions.sh --bootstrap-server kafka:9092
#kafka#debug
Show queue names, message depth and consumer count
rabbitmqctl list_queues name messages consumers
#rabbitmq
Show cluster nodes, disk nodes and partitions
rabbitmqctl cluster_status
#rabbitmq#debug
Purge a queue rabbitmq
Remove all messages from a queue without deleting it
rabbitmqctl purge_queue my_queue -p my_vhost
#rabbitmq
List exchanges rabbitmq
Show all exchanges with type and durability
rabbitmqctl list_exchanges name type durable
#rabbitmq
List bindings rabbitmq
Show exchange-to-queue bindings for a vhost
rabbitmqctl list_bindings -p my_vhost
#rabbitmq
Enable web UI on port 15672
rabbitmq-plugins enable rabbitmq_management && rabbitmqctl restart
#rabbitmq
Export all vhosts, exchanges and policies via management API
curl -s -u guest:guest http://localhost:15672/api/definitions | jq '.' > rabbitmq-defs.json
#rabbitmq
Connect to Atlas or any MongoDB URI with mongosh
mongosh 'mongodb+srv://user:pass@cluster.example.com/mydb'
#mongodb
Show execution stats including index usage
db.orders.find({status:'new'}).explain('executionStats')
#mongodb#debug
Ascending userId + descending createdAt index
db.orders.createIndex({userId: 1, createdAt: -1}, {background: true})
#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}])
#mongodb
Show secondary lag and oplog window
rs.printSecondaryReplicationInfo()
#mongodb#monitoring
List operations running longer than 5 seconds
db.currentOp({active:true, secs_running:{$gt:5}})
#mongodb#debug
Dump a database mongodb
Dump all collections in a database to BSON files
mongodump --uri='mongodb://localhost:27017' --db=mydb --out=/backup/$(date +%F)
#mongodb
Execute a one-shot query via clickhouse-client
clickhouse-client --host ch.example.com --user default --password secret -q 'SELECT version()'
#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'
#clickhouse#debug#monitoring
Force-stop a specific query by its query_id
clickhouse-client -q "KILL QUERY WHERE query_id = 'abc-123'"
#clickhouse#debug
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'
#clickhouse#monitoring
Force merging of all parts (use with caution on large tables)
clickhouse-client -q 'OPTIMIZE TABLE mydb.mytable FINAL'
#clickhouse
Bulk-load a CSV file into a ClickHouse table
clickhouse-client --query 'INSERT INTO mydb.events FORMAT CSVWithNames' < events.csv
#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'
#clickhouse#monitoring
Check node status cassandra
Show cluster ring with status, load and ownership
nodetool status
#cassandra
Show pending and active compaction tasks
nodetool compactionstats
#cassandra#monitoring
Run CQL from cqlsh cassandra
Execute a CQL statement non-interactively
cqlsh -u cassandra -p cassandra -e 'DESCRIBE KEYSPACES;'
#cassandra
Check table stats cassandra
Show read/write latencies and SSTable count for a table
nodetool tablestats mykeyspace.mytable
#cassandra#monitoring
Repair a keyspace cassandra
Full repair to sync all replicas for a keyspace
nodetool repair -full mykeyspace
#cassandra
Get gossip info cassandra
Show gossip state for all nodes (debug)
nodetool gossipinfo
#cassandra#debug
Force flush in-memory data to SSTables
nodetool flush mykeyspace
#cassandra
Check cluster health elasticsearch
Show cluster status: green/yellow/red with shard counts
curl -s http://es:9200/_cluster/health?pretty
#elasticsearch#monitoring
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'
#elasticsearch#monitoring
Delete old index elasticsearch
Remove a specific index (irreversible)
curl -X DELETE http://es:9200/logs-2024.01.01
#elasticsearch
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}'
#elasticsearch#debug
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'
#elasticsearch#debug
Retry allocation of all failed/unassigned shards
curl -X POST http://es:9200/_cluster/reroute?retry_failed=true
#elasticsearch#debug
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}}'
#elasticsearch
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}}}'
#elasticsearch
Snapshot to repository elasticsearch
Create a cluster snapshot synchronously
curl -X PUT 'http://es:9200/_snapshot/my_repo/snap1?wait_for_completion=true'
#elasticsearch
Print the 3rd whitespace-delimited field
awk '{print $3}' file.txt
#awk#linux
Use colon as field separator, print user and UID
awk -F: '{print $1, $3}' /etc/passwd
#awk#linux
Print line number and content for lines matching ERROR
awk '/ERROR/ {print NR": "$0}' app.log
#awk#linux#debug
Accumulate a numeric column and print total
awk '{sum += $4} END {print sum}' access.log
#awk#linux
Range pattern: include lines from START to END inclusive
awk '/START/,/END/' file.txt
#awk#linux
Process all lines except the first (header)
awk 'NR>1 {print $1, $2}' data.csv
#awk#linux
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
#awk#linux#network
NF holds the number of fields; $NF is the last field
awk '{print $NF}' file.txt
#awk#linux
Print lines where field 2 > 500 AND field 5 is POST
awk '$2 > 500 && $5 == "POST"' access.log
#awk#linux
Aligned printf formatting with fixed column widths
awk '{printf "%-20s %5d\n", $1, $2}' data.txt
#awk#linux
Load awk program from an external script file
awk -f transform.awk input.txt
#awk#linux
Global substitution and write back to same file
awk '{gsub(/foo/, "bar"); print}' input.txt > tmp && mv tmp input.txt
#awk#linux
Parse quoted CSV fields correctly with FPAT in gawk
gawk -v FPAT='([^,]+)|("[^"]+")' '{print $2}' data.csv
#awk#linux
Run code before and after processing all lines
awk 'BEGIN{print "Start"} {lines++} END{print lines" lines processed"}' file.txt
#awk#linux
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
#awk#linux
Replace the first occurrence of 'foo' with 'bar' per line
sed 's/foo/bar/' file.txt
#sed#linux
Replace every occurrence per line with the /g flag
sed 's/foo/bar/g' file.txt
#sed#linux
Modify file in-place (no backup); on macOS add empty string: -i ''
sed -i 's/old/new/g' config.cfg
#sed#linux
Edit in-place and save original as file.txt.bak
sed -i.bak 's/old/new/g' file.txt
#sed#linux
Delete all comment lines starting with #
sed '/^#/d' config.txt
#sed#linux
Remove all empty or whitespace-only lines
sed '/^[[:space:]]*$/d' file.txt
#sed#linux
Print lines 10 through 20 only (suppress default output with -n)
sed -n '10,20p' file.txt
#sed#linux
Print only lines that match ERROR
sed -n '/ERROR/p' app.log
#sed#linux#debug
Insert a comment line before every server_name directive
sed '/^server_name/i # Added by deploy script' nginx.conf
#sed#linux
Append a setting line after the [defaults] header
sed '/^\[defaults\]/a ansible_python_interpreter=/usr/bin/python3' ansible.cfg
#sed#linux
GNU sed /I flag for case-insensitive match
sed 's/error/ERROR/gI' file.txt
#sed#linux
Apply multiple substitutions in one command
sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt
#sed#linux
Trim leading and trailing whitespace from each line
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' file.txt
#sed#linux
Apply substitution only to lines 5 through 15
sed '5,15s/DEBUG/INFO/g' app.log
#sed#linux
Print the value of DB_HOST from a .env file
sed -n 's/^DB_HOST=//p' .env
#sed#linux
Write file and quit vim
:wq
#vim#linux
Force quit discarding all changes
:q!
#vim#linux
Replace all occurrences interactively (c = confirm)
:%s/old/new/gc
#vim#linux
Start vim with cursor on line 42
vim +42 file.txt
#vim#linux
/ searches forward, ? searches backward; n/N cycle results
/pattern (n/N next/prev) ?pattern (backward)
#vim#linux
Delete all lines starting with # (comment lines)
:g/^#/d
#vim#linux
Go to top (gg), re-indent to end of file (=G)
gg=G
#vim#linux
Macros automate repetitive edits in vim
qa (record into a) q (stop) @a (play) 10@a (play 10 times)
#vim#linux
Toggle line numbers on (use :set nonumber to hide)
:set number
#vim#linux
Vertical split; use Ctrl-w + arrow to navigate panes
:vsplit other.txt
#vim#linux
Execute the 'build' target in the current Makefile
make build
#make#linux
Print what would be executed without running it
make -n deploy
#make#linux
Override Makefile variables at call time
make IMAGE=myapp:v2 TAG=latest push
#make#linux#ci
Run up to 4 recipe lines in parallel
make -j4 test
#make#linux
Convention: annotate targets with ## comments for self-documenting Makefiles
grep -E '^[a-zA-Z_-]+:.*?##' Makefile | awk -F':.*##' '{printf "%-20s %s\n", $1, $2}'
#make#linux
Unconditionally remake all targets (-B / --always-make)
make -B build
#make#linux
Use a Makefile in a different directory or with a different name
make -f infra/Makefile plan
#make#linux
Prevent make from confusing targets with files of the same name
.PHONY: build test deploy clean
#make#linux
$@ expands to the current target name in a recipe
build: docker build -t $(IMAGE) . && echo 'Built $@'
#make#linux
Split a large Makefile into modular includes
include mk/*.mk
#make#linux
Start a detached nginx container without root privileges
podman run -d --name web -p 8080:80 nginx:alpine
#podman#containers
Build image podman
Build from a Containerfile (Dockerfile-compatible)
podman build -t myapp:latest -f Containerfile .
#podman#containers
Create a systemd unit to manage the container lifecycle
podman generate systemd --new --name web > ~/.config/systemd/user/web.service
#podman#containers#systemd
Run a pod from a Kubernetes manifest (local testing)
podman play kube deployment.yaml
#podman#containers#kubectl
Generate a Kubernetes-compatible manifest from a running pod
podman generate kube mypod > pod.yaml
#podman#containers#kubectl
Group containers into a pod sharing network namespace
podman pod create --name mypod -p 8080:80 && podman run -d --pod mypod nginx:alpine
#podman#containers
List filesystem layers of an image
podman image inspect myapp:latest | jq '.[0].RootFS.Layers'
#podman#containers#debug
Show all containers with name, status and image
podman ps -a --format '{{.Names}}\t{{.Status}}\t{{.Image}}'
#podman#containers
Non-interactively delete all exited containers
podman container prune -f
#podman#containers
Authenticate with a container registry
podman login registry.example.com -u myuser
#podman#containers
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)
#argocd#kubectl
Show all ArgoCD applications with sync/health status
argocd app list
#argocd
Trigger sync and prune removed resources
argocd app sync myapp --prune
#argocd
Force ArgoCD to re-fetch manifests from Git
argocd app get myapp --refresh
#argocd#debug
Show what would change if the app were synced now
argocd app diff myapp
#argocd#debug
Rollback to revision 3 of the application history
argocd app rollback myapp 3
#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
#argocd#ci
Remove ArgoCD app object without deleting Kubernetes resources
argocd app delete myapp --cascade=false
#argocd
Register an external cluster using a kubeconfig context
argocd cluster add my-k8s-context
#argocd#kubectl
Show all clusters managed by ArgoCD
argocd cluster list
#argocd
Override container image for a Kustomize app without changing Git
argocd app set myapp --kustomize-image myapp=myregistry/myapp:v1.2.3
#argocd#kustomize
Disable automated sync for manual control
argocd app set myapp --sync-policy none
#argocd
List all Kubernetes resources managed by an app
argocd app resources myapp
#argocd#debug
Block until app is synced and healthy (CI use case)
argocd app wait myapp --sync --health --timeout 120
#argocd#ci
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/*'
#argocd#security
Cross-compile a Go binary for Linux/amd64
GOOS=linux GOARCH=amd64 go build -o bin/app ./cmd/app
#go#ci
Run all tests with race condition detection enabled
go test -race -count=1 ./...
#go#debug
Generate HTML coverage report and open in browser
go test -coverprofile=cov.out ./... && go tool cover -html=cov.out
#go#debug
Download a specific module version and update go.mod
go get github.com/some/pkg@v1.2.3
#go
Add missing and remove unused module dependencies
go mod tidy
#go
Copy all module dependencies into the vendor/ directory
go mod vendor
#go#ci
Run benchmarks, collect CPU profile, open pprof interactive UI
go test -cpuprofile=cpu.prof -bench=. ./... && go tool pprof cpu.prof
#go#debug#performance
Print import paths of all packages in the module
go list ./...
#go
Reformat all .go files in the current tree
gofmt -w .
#go
Report likely mistakes in Go source code
go vet ./...
#go#debug
Run a command under strace and save output to file
strace -o trace.log ls /tmp
#strace#linux#debug
Trace syscalls of an already-running process by PID
strace -p $(pgrep nginx | head -1) -o /tmp/nginx.trace
#strace#linux#debug
Filter to file-related syscalls only
strace -e trace=openat,read,write curl https://example.com
#strace#linux#debug
Summary table of syscall counts and time spent
strace -c -e trace=all python3 app.py
#strace#linux#debug#performance
Trace syscalls in all forked children (-f)
strace -f -e trace=process nginx -t
#strace#linux#debug
-tt adds absolute time; -T shows time spent in each call
strace -tt -T curl https://example.com 2>&1 | head -40
#strace#linux#debug#performance
Find files the process tries to open but cannot find
strace -e trace=openat -e trace=file myapp 2>&1 | grep 'ENOENT'
#strace#linux#debug
Capture all network-related syscalls
strace -e trace=network,socket curl https://example.com 2>&1 | grep -v '^---'
#strace#linux#debug#network
Capture all traffic on eth0 without DNS resolution
tcpdump -i eth0 -n
#tcpdump#network#linux
Capture to file tcpdump
Save raw packets to PCAP file for Wireshark analysis
tcpdump -i eth0 -w /tmp/capture.pcap
#tcpdump#network#linux
Read PCAP file tcpdump
Replay and display packets from a saved PCAP file
tcpdump -r /tmp/capture.pcap -n | head -50
#tcpdump#network#linux
Filter by host tcpdump
Capture only traffic to/from a specific IP
tcpdump -i any host 10.0.0.5 -n
#tcpdump#network#linux
Filter by port tcpdump
Capture HTTPS traffic only
tcpdump -i eth0 port 443 -n
#tcpdump#network#linux
Monitor all DNS lookups on any interface
tcpdump -i any -n port 53
#tcpdump#network#linux#debug
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 /'
#tcpdump#network#linux#debug
BPF filter: traffic between exactly two endpoints
tcpdump -i eth0 'host 10.0.0.1 and host 10.0.0.2'
#tcpdump#network#linux
Full verbose output with ASCII packet content for PostgreSQL
tcpdump -i eth0 -vvv -A -s 0 port 5432
#tcpdump#network#linux#debug
Stop after capturing 100 packets
tcpdump -i eth0 -c 100 -w capture.pcap
#tcpdump#network#linux
Show INPUT chain rules with packet/byte counters
iptables -L INPUT --line-numbers -n -v
#iptables#linux#network#security
Append a rule to accept inbound HTTPS traffic
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
#iptables#linux#network#security
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
#iptables#linux#network#security
Enable IP masquerading for outbound traffic (router/NAT)
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
#iptables#linux#network
Persist rules across reboots
iptables-save > /etc/iptables/rules.v4 iptables-restore < /etc/iptables/rules.v4
#iptables#linux#network
Remove rule number 3 from the INPUT chain
iptables -D INPUT 3
#iptables#linux#network
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
#iptables#linux#network#security
Show complete nftables configuration
nft list ruleset
#iptables#linux#network#security
Accept inbound TCP traffic on port 8080 in nftables
nft add rule inet filter input tcp dport 8080 accept
#iptables#linux#network#security
Delete all nftables rules (caution: drops all firewall rules)
nft flush ruleset
#iptables#linux#network#security
Show all files (sockets, regular, pipes) opened by nginx
lsof -p $(pgrep nginx) | head -30
#lsof#linux#debug
Find which process is listening on port 8080
lsof -i :8080
#lsof#linux#network#debug
Show all open network connections without DNS resolution
lsof -i -n -P
#lsof#linux#network
Show all processes with open files under /var/log
lsof +D /var/log
#lsof#linux#debug
Find files deleted but still held open by processes (disk bloat)
lsof | grep '(deleted)'
#lsof#linux#debug
Show TCP listening ports with process names
ss -tlnp
#lsof#linux#network
Filter established TCP connections with process info
ss -tanp | grep ESTAB
#lsof#linux#network
List UDP listening ports with process names
ss -ulnp
#lsof#linux#network
Print socket usage summary by state
ss -s
#lsof#linux#network#monitoring
Show connections going TO port 443
ss -tnp dst :443
#lsof#linux#network
Build, deploy and watch for changes; auto-rebuild on save
skaffold dev --port-forward
#skaffold#ci#kubectl
Build images, push to registry and deploy to cluster
skaffold run --tail
#skaffold#ci#kubectl
Build images and export artifact metadata to file
skaffold build --file-output=artifacts.json
#skaffold#ci
Deploy using previously built image digests from CI
skaffold deploy --build-artifacts=artifacts.json
#skaffold#ci#kubectl
Produce final Kubernetes YAML without applying it
skaffold render --output=manifests.yaml
#skaffold#ci#kubectl
Activate a named profile from skaffold.yaml
skaffold dev -p staging
#skaffold#ci
Validate skaffold.yaml and print resolved configuration
skaffold diagnose
#skaffold#debug
Delete all Kubernetes resources created by skaffold run
skaffold delete
#skaffold#kubectl
Verify SSH connectivity to all hosts in inventory
ansible all -i inventory.ini -m ping
#ansible
Execute a shell command on all webservers with sudo (-b)
ansible webservers -i inventory.ini -m shell -a 'df -h' -b
#ansible
Collect and inspect Ansible facts for one host
ansible myhost -i inventory.ini -m setup | jq '.ansible_facts.ansible_distribution'
#ansible#debug
Execute only tasks tagged nginx or ssl
ansible-playbook site.yml -i inventory.ini --tags 'nginx,ssl'
#ansible
Skip tasks tagged slow or optional
ansible-playbook site.yml -i inventory.ini --skip-tags 'slow,optional'
#ansible
Inline-encrypt a single string value for use in vars
ansible-vault encrypt_string 'mysecretpassword' --name 'db_password'
#ansible#security
Run playbook only on web01 and web02
ansible-playbook deploy.yml -i inventory.ini --limit 'web01,web02'
#ansible
Confirm each task before execution (debug mode)
ansible-playbook site.yml -i inventory.ini --step
#ansible#debug
Mount a KV version 2 secrets engine at 'secret/'
vault secrets enable -path=secret kv-v2
#vault#security
Store multiple key-value pairs at a path
vault kv put secret/myapp/config db_password=s3cr3t api_key=abc123
#vault#security
Read a KV v2 secret and extract the data payload
vault kv get -format=json secret/myapp/config | jq '.data.data'
#vault#security
List all keys under a KV v2 prefix
vault kv list secret/myapp/
#vault#security
Issue a renewable token with a 24h TTL for CI
vault token create -policy=read-only -period=24h -display-name=ci-pipeline
#vault#security#ci
Allow pods to authenticate with Vault via ServiceAccount JWT
vault auth enable kubernetes && vault write auth/kubernetes/config kubernetes_host=https://kubernetes.default.svc
#vault#security#kubectl
Obtain short-lived Postgres credentials from the database secrets engine
vault read database/creds/readonly-role
#vault#security#postgres
Manually seal or unseal Vault with an unseal key shard
vault operator seal vault operator unseal $UNSEAL_KEY
#vault#security
Show what would change in the cluster (requires helm-diff plugin)
helm diff upgrade myrelease ./chart -f values.yaml
#helm#debug
Print the user-supplied values for a deployed release
helm get values myrelease -n mynamespace
#helm#debug
Show all values including chart defaults (-a / --all)
helm get values myrelease -a -n mynamespace
#helm#debug
Roll back a release to revision number 2
helm rollback myrelease 2 -n mynamespace
#helm
List all revisions of a Helm release with status
helm history myrelease -n mynamespace
#helm#debug
Create a versioned .tgz package from a chart directory
helm package ./mychart --version 1.2.3 --app-version 1.2.3
#helm#ci
Publish a chart to an OCI-compatible registry (Helm 3.8+)
helm push mychart-1.2.3.tgz oci://registry.example.com/charts
#helm#ci
Validate chart structure and catch template errors
helm lint ./mychart -f values.yaml --strict
#helm#debug#ci
Basic port scan of a single host
nmap 192.168.1.1
#nmap#network#scan
Stealth SYN scan (requires root)
nmap -sS 192.168.1.1
#nmap#network#syn
Scan all 65535 ports
nmap -p- 192.168.1.1
#nmap#network#ports
Probe open ports to determine service/version info
nmap -sV 192.168.1.1
#nmap#network#version
Enable OS detection (requires root)
nmap -O 192.168.1.1
#nmap#network#os
Enables OS detection, version detection, script scanning, and traceroute
nmap -A 192.168.1.1
#nmap#network#aggressive
Scan all hosts in a /24 subnet
nmap 192.168.1.0/24
#nmap#network#subnet
Discover live hosts without port scan
nmap -sn 192.168.1.0/24
#nmap#network#ping
Scan only specified ports
nmap -p 22,80,443,8080 192.168.1.1
#nmap#network#ports
Scan ports in a given range
nmap -p 1-1024 192.168.1.1
#nmap#network#ports
UDP scan nmap
Scan UDP ports (slower, requires root)
nmap -sU 192.168.1.1
#nmap#network#udp
Run default NSE scripts against target
nmap -sC 192.168.1.1
#nmap#network#scripts#nse
Run a named Nmap scripting engine script
nmap --script http-title 192.168.1.1
#nmap#network#scripts#nse
Save scan results in XML format
nmap -oX scan.xml 192.168.1.1
#nmap#network#output
Scan only the 100 most common ports
nmap -F 192.168.1.1
#nmap#network#fast
Start a netcat listener on port 4444
nc -lvp 4444
#netcat#nc#network#listen
Open a TCP connection to host on port 80
nc 192.168.1.1 80
#netcat#nc#network#connect
Port scanning netcat
Scan ports 20-80 on a host (zero I/O mode)
nc -zv 192.168.1.1 20-80
#netcat#nc#network#scan
Send file to a remote listener
nc -lvp 4444 < file.tar.gz
#netcat#nc#transfer#file
Receive a file from a netcat sender
nc 192.168.1.1 4444 > file.tar.gz
#netcat#nc#transfer#file
UDP mode netcat
Connect using UDP instead of TCP
nc -u 192.168.1.1 5005
#netcat#nc#network#udp
Send a raw HTTP GET request with netcat
echo -e "GET / HTTP/1.0 " | nc example.com 80
#netcat#nc#http#debug
Wait for an incoming reverse shell connection
nc -lvp 4444
#netcat#nc#shell#debug
Connect to port and read service banner
nc -v 192.168.1.1 22
#netcat#nc#network#banner
Set connection timeout to 3 seconds
nc -w 3 192.168.1.1 80
#netcat#nc#network#timeout
Record performance data with call-graph info
perf record -g ./my_app
#perf#profiling#cpu#linux
Interactive display of recorded perf data
perf report
#perf#profiling#report
List all supported perf events on current system
perf list
#perf#profiling#events
Show hardware counters for a command
perf stat ls -la
#perf#profiling#stat
Record only cache-miss events
perf record -e cache-misses ./my_app
#perf#profiling#cache
Show live per-function CPU usage (like top)
perf top
#perf#profiling#top#live
Show annotated assembly for hottest function
perf annotate
#perf#profiling#annotate
Collect data suitable for flamegraph generation
perf record -F 99 -ag -- sleep 30 && perf script > out.perf
#perf#profiling#flamegraph
Count specific syscall events
perf stat -e syscalls:sys_enter_read ./my_app
#perf#profiling#syscalls
Profile an already-running process for 5 seconds
perf record -p 1234 sleep 5
#perf#profiling#attach#pid
Start the Grafana service via systemd
systemctl start grafana-server
#grafana#monitoring#service
Check if Grafana service is running
systemctl status grafana-server
#grafana#monitoring#status
Reset admin password via Grafana CLI
grafana-cli admin reset-admin-password newpassword
#grafana#admin#cli
List plugins grafana
List all available plugins from Grafana marketplace
grafana-cli plugins list-remote
#grafana#plugins#cli
Install plugin grafana
Install a Grafana plugin by name
grafana-cli plugins install grafana-piechart-panel
#grafana#plugins#install
Export dashboard JSON via Grafana HTTP API
curl -s http://admin:admin@localhost:3000/api/dashboards/uid/MY_UID | jq .dashboard
#grafana#api#dashboard#export
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
#grafana#api#dashboard#import
List all configured datasources
curl -s http://admin:admin@localhost:3000/api/datasources | jq .[].name
#grafana#api#datasource
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
#grafana#api#datasource#create
Grafana auto-loads dashboards from provisioning directory on startup
# Place YAML in /etc/grafana/provisioning/dashboards/
#grafana#provisioning#dashboards
Install Istio with the demo configuration profile
istioctl install --set profile=demo -y
#istio#service-mesh#install
Enable automatic Envoy sidecar injection for a namespace
kubectl label namespace default istio-injection=enabled
#istio#service-mesh#sidecar
Get sync status of all Envoy proxies in the mesh
istioctl proxy-status
#istio#service-mesh#proxy
Analyze Istio configuration for potential issues
istioctl analyze
#istio#service-mesh#analyze#debug
Show complete Envoy proxy config for a deployment
istioctl proxy-config all deploy/myapp
#istio#service-mesh#envoy#debug
Apply a VirtualService to define traffic routing rules
kubectl apply -f virtualservice.yaml
#istio#service-mesh#virtualservice#routing
Apply a DestinationRule to define load balancing and circuit breaker policies
kubectl apply -f destinationrule.yaml
#istio#service-mesh#destinationrule
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
#istio#service-mesh#mtls#security
Manually inject Istio sidecar into a deployment manifest
istioctl kube-inject -f deployment.yaml | kubectl apply -f -
#istio#service-mesh#sidecar#inject
Open Kiali service mesh dashboard in browser
istioctl dashboard kiali
#istio#service-mesh#kiali#dashboard
Open Jaeger distributed tracing dashboard
istioctl dashboard jaeger
#istio#service-mesh#jaeger#tracing
View Envoy access logs from the sidecar container
kubectl logs -l app=myapp -c istio-proxy | head -50
#istio#service-mesh#logs#envoy
Inject artificial delay to test resilience (in VirtualService)
# In VirtualService spec.http[].fault.delay
#istio#service-mesh#fault-injection#testing
Mirror traffic to a shadow service for testing
# In VirtualService spec.http[].mirror
#istio#service-mesh#mirroring#canary
Completely remove Istio from the cluster
istioctl uninstall --purge -y
#istio#service-mesh#uninstall
Install cert-manager with CRDs into its own namespace
helm install cert-manager jetstack/cert-manager --namespace cert-manager --create-namespace --set installCRDs=true
#cert-manager#tls#k8s#helm
Verify all cert-manager components are running
kubectl get pods -n cert-manager
#cert-manager#tls#k8s#debug
List certificates cert-manager
List all Certificate resources across namespaces
kubectl get certificates -A
#cert-manager#tls#k8s
Describe certificate cert-manager
Show status and events for a Certificate resource
kubectl describe certificate my-cert -n default
#cert-manager#tls#k8s#debug
List all CertificateRequest objects
kubectl get certificaterequests -A
#cert-manager#tls#k8s
Apply a ClusterIssuer manifest for Let's Encrypt ACME
kubectl apply -f clusterissuer-letsencrypt.yaml
#cert-manager#tls#letsencrypt#acme
Check ClusterIssuers cert-manager
List all ClusterIssuer resources and their ready status
kubectl get clusterissuers
#cert-manager#tls#issuer
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
#cert-manager#tls#renew
View cert-manager logs cert-manager
Stream logs from the main cert-manager controller
kubectl logs -n cert-manager deploy/cert-manager -f
#cert-manager#tls#logs#debug
cmctl check API cert-manager
Verify cert-manager API is ready using the cmctl CLI
cmctl check api
#cert-manager#tls#cmctl#cli
Install Crossplane into its own namespace
helm install crossplane crossplane-stable/crossplane --namespace crossplane-system --create-namespace
#crossplane#k8s#helm#infrastructure
List providers crossplane
List all installed Crossplane providers
kubectl get providers
#crossplane#k8s#providers
Apply a Crossplane Provider manifest for AWS
kubectl apply -f provider-aws.yaml
#crossplane#k8s#aws#providers
List all Crossplane managed resources across all kinds
kubectl get managed
#crossplane#k8s#managed
List all Crossplane composite resource instances
kubectl get composite
#crossplane#k8s#composite#xr
Show status and conditions of a managed resource
kubectl describe rdsinstance my-db
#crossplane#k8s#managed#debug
List XRDs crossplane
List all CompositeResourceDefinitions (XRDs)
kubectl get compositeresourcedefinitions
#crossplane#k8s#xrd
List Compositions crossplane
List all Crossplane Compositions
kubectl get compositions
#crossplane#k8s#composition
Show provider readiness and installed packages
kubectl describe provider provider-aws
#crossplane#k8s#providers#debug
Trace a composite resource and all its children
crossplane beta trace xr my-xr
#crossplane#k8s#trace#debug
Download and install the Linkerd CLI
curl --proto =https --tlsv1.2 -sSfL https://run.linkerd.io/install | sh
#linkerd#service-mesh#install
Validate cluster meets requirements before installing Linkerd
linkerd check --pre
#linkerd#service-mesh#check
Install Linkerd CRDs into the cluster
linkerd install --crds | kubectl apply -f -
#linkerd#service-mesh#crds#install
Install Linkerd control plane components
linkerd install | kubectl apply -f -
#linkerd#service-mesh#install
Validate Linkerd installation is healthy
linkerd check
#linkerd#service-mesh#check
Inject Linkerd proxy sidecar into existing deployment
kubectl get deploy my-app -o yaml | linkerd inject - | kubectl apply -f -
#linkerd#service-mesh#inject#sidecar
Show real-time golden metrics for all deployments
linkerd viz stat deploy
#linkerd#service-mesh#stats#monitoring
Show a top-like view of live requests to a deployment
linkerd viz top deploy/my-app
#linkerd#service-mesh#top#requests
Open the Linkerd web dashboard in the browser
linkerd viz dashboard
#linkerd#service-mesh#dashboard
Watch live HTTP request/response stream for a deployment
linkerd viz tap deploy/my-app
#linkerd#service-mesh#tap#debug
Enable Hubble observability with the web UI
cilium hubble enable --ui
#cilium#cni#hubble#ui
Stream live network flows through Hubble
hubble observe --follow
#cilium#cni#hubble#flows
Run a full connectivity test suite in the cluster
cilium connectivity test
#cilium#cni#connectivity#test
Show all Cilium endpoints with their status
cilium endpoint list
#cilium#cni#endpoints
Show dropped packets in real time
cilium monitor --type drop
#cilium#cni#monitor#drop
List BGP peers managed by Cilium BGP control plane
cilium bgp peers
#cilium#cni#bgp#networking
Scan the current directory for vulnerabilities
trivy fs .
#trivy#security#scan#filesystem
Scan the entire Kubernetes cluster for vulnerabilities and misconfigs
trivy k8s --report summary cluster
#trivy#security#k8s#scan
Output scan results in SARIF format for CI/IDE integration
trivy image --format sarif --output results.sarif myimage:tag
#trivy#security#sarif#ci
Scan IaC config files for misconfigurations
trivy config .
#trivy#security#iac#config
Show only HIGH and CRITICAL vulnerabilities
trivy image --severity HIGH,CRITICAL myimage:tag
#trivy#security#severity#filter
Skip vulnerabilities that have no fix available
trivy image --ignore-unfixed myimage:tag
#trivy#security#ignore#filter
Scan sbom trivy
Scan a Software Bill of Materials file for vulnerabilities
trivy sbom ./sbom.json
#trivy#security#sbom#scan
Filter deployments by label selector in k9s
: deploy / app=myapp
#k9s#k8s#filter#labels
Press l on a pod to stream its logs
l (on selected pod)
#k9s#k8s#logs#pods
Press s on a pod to open a shell session
s (on selected pod)
#k9s#k8s#exec#pods
Delete the selected Kubernetes resource
ctrl-d (on selected resource)
#k9s#k8s#delete
Show full kubectl describe output for selected resource
d (on selected resource)
#k9s#k8s#describe
Open the resource YAML for editing in k9s
e (on selected resource)
#k9s#k8s#edit#yaml
Start k9s connected to a specific kubeconfig context
k9s --context my-cluster
#k9s#k8s#context#kubeconfig
Build and apply kustomize
Build kustomize overlay and apply directly to cluster
kubectl apply -k ./overlays/prod
#kustomize#k8s#deploy
Preview output kustomize
Render kustomize output without applying
kubectl kustomize ./overlays/prod | head -100
#kustomize#k8s#preview
Set image tag kustomize
Update image tag in kustomization.yaml
kustomize edit set image myapp=myapp:v1.2.3
#kustomize#k8s#image#deploy
Add a ConfigMap generator entry to kustomization.yaml
kustomize edit add configmap my-config --from-literal=key=value
#kustomize#k8s#configmap
Quickly list all resource kinds in a kustomize build
kustomize build ./overlays/prod | grep "^kind:"
#kustomize#k8s#resources
Use patchesStrategicMerge to partially override base resources
# Add patchesStrategicMerge in kustomization.yaml
#kustomize#k8s#patch#strategic-merge
Check APISIX pods are running in Kubernetes
kubectl get pods -n ingress-apisix
#apisix#api-gateway#k8s
List all configured APISIX routes
curl http://apisix-admin:9180/apisix/admin/routes -H "X-API-KEY: $ADMIN_KEY"
#apisix#api-gateway#admin#api
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"}}'
#apisix#api-gateway#route#create
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"}}}'
#apisix#api-gateway#plugin#rate-limit
List all configured APISIX upstreams
curl http://apisix-admin:9180/apisix/admin/upstreams -H "X-API-KEY: $ADMIN_KEY"
#apisix#api-gateway#upstream
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"}}}'
#apisix#api-gateway#consumer#auth
Enable JWT authentication on a route via plugin config
# Add jwt-auth to plugins in route or consumer config
#apisix#api-gateway#jwt#auth
List plugins apisix
List all available APISIX plugins
curl http://apisix-admin:9180/apisix/admin/plugins/list -H "X-API-KEY: $ADMIN_KEY"
#apisix#api-gateway#plugins
Hot-reload APISIX configuration without downtime
apisix reload
#apisix#api-gateway#reload#config
Show inode usage per filesystem (important for many small files)
df -i
#linux#filesystem#inode#df
Find files larger than 100MB on the entire filesystem
find / -type f -size +100M 2>/dev/null | sort
#linux#filesystem#find#disk
Count open file descriptors for a running process
cat /proc/$(pgrep myapp)/fd | wc -l
#linux#process#fd#proc
Show current SELinux enforcement mode
getenforce
#linux#security#selinux
List all system and user cron job locations
ls /etc/cron.* /var/spool/cron/crontabs/
#linux#cron#scheduling
Display all environment variables sorted alphabetically
printenv | sort
#linux#env#shell
Show extended disk I/O statistics updated every second
iostat -xz 1
#linux#disk#io#iostat
Display process hierarchy with PIDs
pstree -p
#linux#process#pstree
Increase the maximum connection backlog for sockets
sysctl -w net.core.somaxconn=65535
#linux#network#sysctl#tcp#tuning
Display CPU architecture and core count information
lscpu
#linux#cpu#hardware#lscpu
Interactively reorder, squash, or edit last 5 commits
git rebase -i HEAD~5
#git#rebase#history
Apply a specific commit from another branch
git cherry-pick abc1234
#git#cherry-pick#commits
Save working changes with a descriptive stash message
git stash push -m "WIP: feature X"
#git#stash#workflow
Show all stashed changesets
git stash list
#git#stash#list
Apply a specific stash entry without dropping it
git stash apply stash@{2}
#git#stash#apply
Start binary search for the commit that introduced a bug
git bisect start && git bisect bad && git bisect good v1.0
#git#bisect#debug#history
Show full diff history of a file including renames
git log --follow -p -- path/to/file.py
#git#log#history#diff
Move HEAD back one commit, keeping staged changes
git reset --soft HEAD~1
#git#reset#undo
Remove untracked files and directories from working tree
git clean -fd
#git#clean#working-tree
List local branches already merged into main
git branch --merged main
#git#branch#merged#cleanup
Navigate to a resource type by pressing ':' then typing the resource name
:pod # or :svc :deployment :helmreleases :kustomizations
#k9s
Filter listed resources by name pattern (press '/' to activate)
/pattern # Press '/' then type filter string, Esc to clear
#k9s
Describe selected resource (equivalent to kubectl describe)
d # Press 'd' on selected resource to view describe output
#k9s
View pod logs (press 'l' on pod, '0' for all containers)
l # Press 'l' on a pod; '0' for all containers, 'w' to wrap
#k9s
Open shell in pod container (press 's' on pod)
s # Press 's' on a pod to open a shell (uses first container)
#k9s
Delete selected resource (press Ctrl+D, confirm with Enter)
ctrl-d # Press Ctrl+D on selected resource, confirm with Enter
#k9s
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
#grafana#provisioning#dashboards
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
#istio#service-mesh#virtualservice#routing
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
#istio#service-mesh#destinationrule
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
#istio#service-mesh#fault-injection#testing
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
#istio#service-mesh#mirroring#canary
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
#cert-manager#tls#letsencrypt#acme
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
#crossplane#k8s#aws#providers
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
#kustomize#k8s#patch#strategic-merge
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"}}}'
#apisix#api-gateway#jwt#auth
Only err/crit/alert/emerg from current boot; -p takes a range too (e.g. -p warning..err)
journalctl -p err -b --no-pager
#journalctl#debug#troubleshooting
Trusted unit match by indexed field, unlike -u which also pulls coredumps/PAM noise
journalctl _SYSTEMD_UNIT=sshd.service --since today
#journalctl#systemd#troubleshooting
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
#journalctl#debug#troubleshooting
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
#journalctl#debug#troubleshooting
Dumps every journal field incl. cursor for an entry; -o json-pretty for machine parsing
journalctl -u <name> -o verbose -n 1
#journalctl#debug#observability
Index past boots, then -b -1 reads the prior boot. note: needs persistent storage
journalctl --list-boots && journalctl -b -1 -p warning
#journalctl#kernel#troubleshooting
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'
#journalctl#kernel#disk
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
#journalctl#disk#performance
Tail by SYSLOG_IDENTIFIER (not unit); -t repeats, --no-hostname trims clutter
journalctl -t kernel -t sudo -f --no-hostname
#journalctl#monitoring#observability
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'
#journalctl#observability#debug
Read journals from another root (rescue/forensics) without copying files in
journalctl -D /mnt/crashed/var/log/journal -b -1 -p err
#journalctl#troubleshooting#disk
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
#journalctl#disk#troubleshooting
Show the serialized dependency chain that actually delays boot; more honest than blame
systemd-analyze critical-chain <unit>
#systemd#performance#troubleshooting
Render full parallel boot timeline as an SVG to spot serialized stalls visually
systemd-analyze plot > boot.svg
#systemd#performance#observability
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
#systemd#gitops#troubleshooting
Reload unit files after editing; note: required after manual edits or systemctl warns of stale config
systemctl daemon-reload
#systemd#troubleshooting
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>
#systemd#security#troubleshooting
Walk the full Wants/Requires tree to debug why a service pulls in others; --reverse for who needs it
systemctl list-dependencies <unit> --all
#systemd#debug#troubleshooting
Read live cgroup metrics straight from systemd without ps; MemoryCurrent is the accounted RSS
systemctl show -p MainPID,MemoryCurrent,TasksCurrent <unit>
#systemd#monitoring#performance
Reset failed counters so units can restart past StartLimitBurst, then list what is still failed
systemctl reset-failed && systemctl list-units --state=failed
#systemd#troubleshooting#debug
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
#systemd#ci#troubleshooting
Apply cgroup limits live without restart; --runtime keeps them volatile (gone on reboot)
systemctl set-property --runtime <unit> MemoryMax=512M CPUQuota=50%
#systemd#performance#troubleshooting
Show in-flight start/stop jobs to diagnose a hung boot or a unit stuck activating
systemctl list-jobs
#systemd#debug#troubleshooting
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
#cgroups#memory#performance#troubleshooting
PSI: time tasks stalled on memory reclaim; rising avg10 = thrashing before OOM
cat /sys/fs/cgroup/system.slice/<name>.service/memory.pressure
#cgroups#memory#performance#observability
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
#cgroups#cpu#performance#troubleshooting
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
#cgroups#cpu#performance
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
#cgroups#disk#performance#observability
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
#cgroups#systemd#troubleshooting#debug
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
#cgroups#systemd#monitoring#performance
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>
#cgroups#memory#systemd
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
#namespaces#debug#troubleshooting#network
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
#namespaces#network#debug#troubleshooting
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
#namespaces#network#debug#troubleshooting
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
#namespaces#network#security#kernel
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>
#iproute2#network#troubleshooting
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
#iproute2#network#performance
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 // "-")'
#iproute2#observability#network
Show the exact route, src IP and oif the kernel picks for a destination
ip route get <ip>
#iproute2#network#troubleshooting#debug
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
#iproute2#network#security#troubleshooting
Create an isolated network namespace and run commands inside it
ip netns add test && ip netns exec test ip -br a
#iproute2#network#k8s#debug
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>
#iproute2#network#performance#troubleshooting
Drop the root qdisc to restore normal traffic after netem testing
tc qdisc del dev <name> root
#iproute2#network#performance
Live stream of route/link/addr/neigh changes; great for flapping debug
ip monitor all
#iproute2#monitoring#network#debug
Inspect L2 forwarding DB (MAC->port) and bridge port states
bridge fdb show br <name>; bridge link show
#iproute2#network#troubleshooting#k8s
Show rtt/cwnd/retrans per socket for 443; pinpoint slow/lossy peers
ss -tip state established '( dport = :443 )'
#iproute2#ss#performance#network#debug
Forcibly close matching sockets (kernel>=4.9); needs CONFIG_INET_DIAG_DESTROY
ss -K dst <ip> dport = :8080
#iproute2#ss#network#troubleshooting#security
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 ; }'
#nftables#security#network#firewall
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 }'
#nftables#security#network#firewall
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 }'
#nftables#network#performance#firewall
-a prints '# handle N' per rule; you need the handle to delete a single rule
nft -a list ruleset
#nftables#troubleshooting#network
Surgical removal without flushing; get the handle from nft -a list ruleset
nft delete rule inet filter input handle 7
#nftables#network#troubleshooting
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\"
#nftables#monitoring#observability#network
Source-NAT egress to the iface IP; needs a nat-type postrouting chain to exist
nft add rule ip nat postrouting oifname \"eth0\" masquerade
#nftables#network#cloud#firewall
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
#nftables#network#cloud#firewall
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
#nftables#security#performance#network
Streams add/delete events as they happen; great for debugging dynamic rules
nft monitor ruleset
#nftables#debug#monitoring#troubleshooting
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
#nftables#gitops#network#firewall
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
#nftables#performance#network#kernel
Catch only connection-initiating SYNs (no SYN-ACK) to spot scans or backlog floods
tcpdump -nn 'tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn'
#tcpdump#network#security#troubleshooting
Show only connection open/close packets to trace short-lived churning sessions
tcpdump -nn 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0'
#tcpdump#network#debug#troubleshooting
Watch traffic to/from a host while dropping your own SSH session noise
tcpdump -nn -i any host <ip> and not port 22
#tcpdump#network#debug
Inspect full packet bodies in hex+ascii; -s 0 ensures no snaplen truncation
tcpdump -nn -s 0 -X -i any port <port>
#tcpdump#debug#network#troubleshooting
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
#tcpdump#disk#monitoring#network
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'
#tcpdump#monitoring#network#observability
Re-filter a saved capture without re-running it; BPF applies on read
tcpdump -nn -r /tmp/cap.pcap 'port 443 and host <ip>'
#tcpdump#debug#tls#troubleshooting
Show DNS lookups with MAC addresses (-e) to map queries to clients on the LAN
tcpdump -nn -e -i any port 53
#tcpdump#dns#network#troubleshooting
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
#tshark#observability#debug#network
Reassemble stream index 0 into readable ascii; prefer tshark over wireshark on servers
tshark -r cap.pcap -q -z follow,tcp,ascii,0
#tshark#debug#network#troubleshooting
Rank TCP conversations by bytes/packets to find top talkers in a capture
tshark -r cap.pcap -q -z conv,tcp
#tshark#performance#observability#network
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'
#tshark#performance#monitoring#troubleshooting
Live top hot functions with caller chains; dwarf unwind works without frame pointers
perf top -g --call-graph dwarf
#perf#performance#debug#troubleshooting
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
#perf#performance#monitoring#troubleshooting
Turn perf.data into an interactive flame graph SVG (Brendan Gregg FlameGraph tools)
perf script | stackcollapse-perf.pl | flamegraph.pl > flame.svg
#perf#performance#observability#troubleshooting
Run with three -d for L1/LLC/TLB and stalled-cycle detail; reveals memory-bound vs CPU-bound
perf stat -d -d -d -- ./app
#perf#performance#monitoring#troubleshooting
Record context switches then show per-task wakeup latency; find runqueue starvation
perf sched record -- sleep 10 && perf sched latency --sort max
#perf#performance#kernel#troubleshooting
strace-like syscall trace with -s summary; lower overhead, no ptrace stop-the-world
perf trace -s -p <pid>
#perf#debug#performance#troubleshooting
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
#perf#kernel#debug#observability
Aggregate syscall counts/time across forks, sorted by time; pinpoints the costly call
strace -c -f -S time -p <pid>
#strace#performance#debug#troubleshooting
Show paths/sockets behind fds plus per-call duration and timestamps for file ops
strace -yy -T -tt -e trace=%file -p <pid>
#strace#debug#disk#troubleshooting
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>
#strace#debug#troubleshooting#disk
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>
#strace#debug#troubleshooting#ci
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>
#strace#debug#troubleshooting#kernel
Show which process owns a port; -nP skips DNS/service name lookups for speed
lsof -nP -i :<port>
#lsof#network#troubleshooting#debug
List every TCP listener with PID, no name resolution; modern: ss -ltnp
lsof -nP -iTCP -sTCP:LISTEN
#lsof#network#monitoring#troubleshooting
Find unlinked files still held open eating disk; df shows full but du does not
lsof +L1
#lsof#disk#troubleshooting#debug
Reveal processes blocking a 'device busy' umount; pass the mountpoint path
lsof /mnt/<name>
#lsof#disk#troubleshooting#debug
Kill whatever owns a port; -t prints bare PIDs, -r avoids running kill on empty input
lsof -t -i:<port> | xargs -r kill
#lsof#network#troubleshooting#debug
Spot sockets the app forgot to close; growing CLOSE_WAIT = fd/connection leak
lsof -nP -i -sTCP:CLOSE_WAIT
#lsof#network#performance#troubleshooting
Show only sockets talking to a specific peer host/port, both ends matched
lsof -nP -i @<host>:<port>
#lsof#network#monitoring#debug
Show only mapped executable and shared libs; -a ANDs the filters, great after a deploy
lsof -p <pid> -a -d txt,mem
#lsof#debug#troubleshooting#performance
Quick fd count to spot leaks vs ulimit -n; faster: ls /proc/<pid>/fd | wc -l
lsof -nP -p <pid> | wc -l
#lsof#performance#troubleshooting#debug
Strip headers/stats; show only the answer section for scripting/diffs
dig +noall +answer example.com
#dig#dns#troubleshooting
Query each authoritative NS directly; reveals SOA serial mismatches between them
dig +nssearch example.com
#dig#dns#troubleshooting
Dump full zone if AXFR is open; note: success on public NS is a misconfig
dig axfr @ns1.example.com example.com
#dig#dns#security
Show RRSIG records; check AD flag in flags line for validated answer
dig +dnssec +multi example.com @1.1.1.1
#dig#dns#dnssec#security
Follow delegation from root to authoritative, hiding RRSIG/DS clutter
dig +trace +nodnssec example.com
#dig#dns#troubleshooting
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)
#dig#dns#troubleshooting#debug
PTR for an IPv6 address; -x expands nibble format automatically
dig -x 2606:4700:4700::1111 +short
#dig#dns#network
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
#dig#dns#security
Show which CAs may issue certs; missing CAA lets any CA issue
dig +short CAA example.com
#dig#dns#tls#security
Get priority/weight/port/target for a service; used by AD, SIP, XMPP
dig +short SRV _sip._tcp.example.com
#dig#dns#network
Test TCP/53 reachability; +ttlunits prints TTL as 1h/30m not raw seconds
dig +tcp +ttlunits +noall +answer example.com @8.8.8.8
#dig#dns#network#troubleshooting
Catch syntax errors and missing records; run before rndc reload to avoid SERVFAIL
named-checkzone example.com /etc/bind/db.example.com
#bind#dns#troubleshooting
Clear cache, reload config without restart, verify; note: reload re-reads zones too
rndc flush && rndc reconfig && rndc status
#bind#dns#troubleshooting
Validate config syntax, then list current leases (expiry, MAC, IP, hostname)
dnsmasq --test && cat /var/lib/misc/dnsmasq.leases
#dnsmasq#dns#network#troubleshooting
Dump all cert fields: subject, issuer, validity, extensions, SANs, key usage
openssl x509 -in cert.pem -noout -text
#openssl#tls#security#debug
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
#openssl#monitoring#tls#ci
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
#openssl#tls#network#debug
Show only SAN entries; modern browsers ignore CN, so SAN is what matters
openssl x509 -in cert.pem -noout -ext subjectAltName
#openssl#tls#dns#security
Validate trust chain; note: -CAfile must hold intermediates+root in order
openssl verify -CAfile ca-chain.pem cert.pem
#openssl#tls#security#troubleshooting
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)
#openssl#tls#security#troubleshooting
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>"
#openssl#tls#security
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>"
#openssl#tls#security
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>
#openssl#tls#security
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
#openssl#tls#network#debug
Modern: Ed25519 keys are tiny and fast vs RSA; use for signing/mTLS
openssl genpkey -algorithm ed25519 -out ed25519.pem
#openssl#security#tls
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'
#openssl#tls#security#troubleshooting
Fail fast on errors, unset vars, pipe failures; split only on newline/tab
set -euo pipefail; IFS=$'\n\t'
#bash#troubleshooting#ci
Auto-remove mktemp dir on exit/signal; note: quote $tmp to survive spaces
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT INT TERM
#bash#security#troubleshooting
Process substitution compares two streams without temp files
diff <(kubectl get cm a -o yaml) <(kubectl get cm b -o yaml)
#bash#debug#k8s
mapfile -t strips newlines; handles spaces unlike for-loop word splitting
mapfile -t lines < file.txt; printf '%s\n' "${lines[@]}"
#bash#troubleshooting
basename, strip extension, and global replace without spawning sed/basename
f=/var/log/app.log.gz; echo "${f##*/}" "${f%.*}" "${f//log/LOG}"
#bash#performance
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]}"
#bash#debug
Run N parallel jobs safely with NUL separators for names with spaces
find . -name '*.log' -print0 | xargs -0 -P"$(nproc)" -n1 gzip
#bash#performance
Inspect exit code of every pipe stage; $? only reports the last command
curl -s "$url" | jq .data; echo "${PIPESTATUS[@]}"
#bash#debug#troubleshooting
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
#bash#ci
SIGTERM at 30s then SIGKILL after 5s grace; exit 124 means it was killed
timeout -k 5s 30s ./long_task.sh || echo "timed out: $?"
#bash#troubleshooting
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>&-
#bash#observability
zsh: list only regular files recursively, then mass-rename safely with zmv
setopt extendedglob; print -l **/*(.); autoload zmv; zmv '(*).txt' '$1.bak'
#zsh#troubleshooting
Preserve hardlinks, ACLs, xattrs, raw uid/gid for host migration; note: trailing slash matters
rsync -aHAXv --numeric-ids /src/ user@<host>:/dst/
#rsync#network#security#troubleshooting
Preview every change with itemize codes (>f, cd, *deleting) before touching files
rsync -ai --dry-run --delete /src/ /dst/
#rsync#debug#troubleshooting
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/
#rsync#network#performance
Time-Machine-style backup: unchanged files hardlink to prev, only deltas use new space
rsync -a --delete --link-dest=../prev /src/ ./$(date +%F)/
#rsync#disk#performance
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/
#rsync#network#troubleshooting
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/
#rsync#network#ci
Compare by checksum not mtime+size; delete-after avoids removing files until transfer succeeds
rsync -ac --delete-after /src/ /dst/
#rsync#troubleshooting#disk
Level-based incremental backups: snapshot.snar tracks state so only changed files are archived
tar -czg snapshot.snar -f backup-$(date +%F).tgz /data
#tar#disk#performance
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'
#tar#network#troubleshooting
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
#tar#monitoring#performance
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
#zstd#performance#disk
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
#zstd#performance#disk
Inspect a service account's jobs as root; note: -u needs root or sudo
crontab -l -u <name> 2>/dev/null || echo 'no crontab'
#cron#troubleshooting#security
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 -
#cron#gitops
Tag stdout+stderr into journald/syslog instead of mailing root
*/5 * * * * /opt/job.sh 2>&1 | /usr/bin/logger -t job
#cron#observability#monitoring
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
#cron#troubleshooting#secrets
List which scripts would execute without running them; debugging cron.daily
run-parts --test /etc/cron.daily
#cron#debug#troubleshooting
modern: transient OnCalendar timer with logs/retries; replaces a crontab line
systemd-run --on-calendar='*-*-* 03:00:00' --unit=backup /opt/backup.sh
#cron#gitops#observability
Schedule a single deferred command; inspect queue with atq, cancel with atrm
at now + 1 hour <<< 'systemctl restart nginx'
#cron#troubleshooting
Run only when load avg drops below 1.5; note: atd must be running
batch <<< '/opt/heavy-reindex.sh'
#cron#performance
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
#tmux#troubleshooting#monitoring
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
#tmux#debug#observability
Launch detached, named, logging session; reattach later with screen -r deploy
screen -L -Logfile /tmp/job.log -dmS deploy bash -c './deploy.sh'
#screen#troubleshooting#observability
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
#fio#disk#performance#troubleshooting
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
#fio#disk#performance#troubleshooting
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
#fio#disk#performance
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
#fio#disk#performance#troubleshooting
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
#fio#disk#performance
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
#smartctl#disk#monitoring#troubleshooting
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}'
#smartctl#disk#monitoring#troubleshooting
Full -x dump: health, attributes, error log, temp history; -d auto detects RAID/USB
smartctl -x -d auto /dev/sda | less
#smartctl#disk#troubleshooting#monitoring
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'
#nvme#disk#monitoring#troubleshooting
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'
#nvme#disk#troubleshooting#debug
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
#dd#disk#performance#troubleshooting
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
#dd#disk#troubleshooting#performance
Pull raw Prometheus metrics from the apiserver without a metrics stack
kubectl get --raw /metrics | grep apiserver_request_total
#kubectl#metrics#observability#performance
Verify etcd connectivity through the apiserver health endpoint
kubectl get --raw '/healthz/etcd?verbose'
#kubectl#etcd#troubleshooting#k8s
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}'
#kubectl#metrics#monitoring#performance
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
#kubectl#debug#troubleshooting#k8s
Dump the full nested field tree of a resource spec; great for hunting valid fields
kubectl explain deploy.spec --recursive | less
#kubectl#k8s#troubleshooting
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>
#kubectl#gitops#k8s
Show the last-applied-configuration annotation; diff intent vs live state
kubectl apply view-last-applied deploy/<name> -n <ns> -o yaml
#kubectl#gitops#troubleshooting
Cluster-wide Warning events newest last; fast triage of failing workloads
kubectl get events -A --field-selector type=Warning --sort-by=.lastTimestamp
#kubectl#troubleshooting#monitoring#debug
List pods in Failed phase across namespaces for cleanup or investigation
kubectl get pods -A --field-selector status.phase=Failed
#kubectl#troubleshooting#debug#k8s
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
#kubectl#ci#gitops#k8s
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
#kubectl#security#troubleshooting#k8s
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
#kubectl#troubleshooting#debug#monitoring
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}'
#kubectl#performance#monitoring#k8s
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>"}}}]'
#kubectl#secrets#gitops#k8s
Render just one manifest to inspect output; note: path is relative to chart root
helm template <name> ./chart --show-only templates/deployment.yaml
#helm#debug#k8s#troubleshooting
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
#helm#k8s#ci#troubleshooting
note: --reuse-values silently keeps stale overrides; --reset-values forces clean merge
helm upgrade --install <name> ./chart --reset-values -f values.yaml
#helm#troubleshooting#gitops#k8s
Dump rendered pre/post-install/upgrade hooks to debug failing job ordering
helm get hooks <rel> -n <ns>
#helm#debug#k8s#troubleshooting
Preview which revision a rollback targets before committing to it
helm history <rel> -n <ns> && helm rollback <rel> <rev> --dry-run -n <ns>
#helm#troubleshooting#k8s#gitops
update refreshes Chart.lock from repos; build fetches subcharts from existing lock
helm dependency update ./chart && helm dependency build ./chart
#helm#ci#k8s
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>
#helm#ci#k8s#gitops
Extract machine-readable deploy state for scripts and gate checks
helm status <rel> -n <ns> -o json | jq '.info.status, .info.last_deployed'
#helm#observability#ci#k8s
Patch rendered manifests via kustomize without forking the upstream chart
helm upgrade --install <name> ./chart --post-renderer ./kustomize-hook.sh -n <ns>
#helm#gitops#k8s
Vendor an OCI chart locally for inspection or air-gapped installs
helm pull oci://<host>/charts/<name> --version 1.2.3 --untar --untardir ./charts
#helm#security#ci#k8s
apply runs diff first and only syncs changed releases; idempotent gitops loop
helmfile -e prod diff && helmfile -e prod apply
#helmfile#gitops#k8s#ci
Sync a single labeled release from a large helmfile; modern: -l app=web,tier=fe
helmfile -e prod -l name=<name> apply
#helmfile#gitops#k8s#ci
Render helmCharts: block to manifests; note: needs helm in PATH
kustomize build --enable-helm ./overlay
#kustomize#gitops#k8s
Mixin reusable patches/resources via components: (Kustomize v4+)
cat <<'EOF' >> kustomization.yaml components: - ../../components/monitoring EOF
#kustomize#gitops#k8s
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
#kustomize#gitops#k8s
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
#kustomize#gitops#k8s
Pin by immutable digest; newName+digest also settable in images: block
kustomize edit set image app=registry.example.com/app@sha256:<id>
#kustomize#gitops#security#k8s
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
#kustomize#secrets#gitops#k8s
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
#gateway-api#tls#security#network
Teach kustomize CRD merge/list semantics so patches merge correctly
cat <<'EOF' >> kustomization.yaml openapi: path: crd-schema.json EOF
#kustomize#gitops#k8s
Inspect Accepted/ResolvedRefs status to debug why a route is not attached
kubectl describe httproute <name> -n <ns> | grep -A8 Conditions
#gateway-api#troubleshooting#debug#network
One-shot view of classes, gateways and routes across all namespaces
kubectl get gatewayclass,gateway,httproute -A
#gateway-api#network#k8s
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
#gateway-api#network#ci#k8s
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
#gateway-api#network#security#k8s
Dump full endpoint state: identity, policy enforcement, BPF maps; run inside cilium pod
cilium-dbg endpoint get <id> -o json | jq '.status.policy'
#cilium#debug#k8s#network
List service VIP-to-backend mappings in BPF; verify kube-proxy-free LB programming
cilium-dbg bpf lb list
#cilium#network#k8s#troubleshooting
Inspect BPF connection-tracking entries; spot stale/leaking flows on a node
cilium-dbg bpf ct list global | head
#cilium#debug#network#troubleshooting
Explain allow/deny verdict between two security identities; debug NetworkPolicy drops
cilium-dbg policy trace --src-identity <id> --dst-identity <id> --dport <port>
#cilium#security#debug#k8s
Full per-node health: datapath mode, IPAM, BPF maps, controllers; first stop on issues
cilium status --verbose
#cilium#monitoring#troubleshooting#k8s
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'
#cilium#observability#dns#network
Check cross-cluster connectivity and remote endpoint/identity sync health
cilium clustermesh status --wait
#cilium#network#troubleshooting#k8s
BPF NAT table cilium
List BPF masquerade/NAT entries; debug SNAT port exhaustion or egress source IP
cilium-dbg bpf nat list | head
#cilium#network#debug#troubleshooting
Show BGP session states and peer IPs from a node; Established means routes exchanged
calicoctl node status
#calico#network#troubleshooting#monitoring
List pools with CIDR, IPIP/VXLAN mode, NAT-outgoing; verify encapsulation settings
calicoctl get ippool -o wide
#calico#network#k8s#troubleshooting
Read live Felix dataplane config: BPF mode, log level, MTU, iptables backend
calicoctl get felixconfiguration default -o yaml
#calico#k8s#troubleshooting#performance
Show per-block IP utilization; find pod-IP exhaustion before scheduling fails
calicoctl ipam show --show-blocks
#calico#network#troubleshooting#k8s
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
#ingress-nginx#debug#troubleshooting#k8s
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
#ingress-nginx#monitoring#performance#observability
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'
#ingress-nginx#troubleshooting#network#debug
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"
#ingress-nginx#ci#gitops#network
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"
#ingress-nginx#security#performance#network
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'
#ingress-nginx#network#troubleshooting
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'
#ingress-nginx#k8s#troubleshooting
Trigger immediate reissue without waiting for the renewal window; watch a new CertificateRequest spawn
cmctl renew <name> -n <ns>
#cert-manager#tls#secrets#k8s
End-to-end view: Certificate, Request, Order, Challenge and the exact ACME failure reason
cmctl status certificate <name> -n <ns>
#cert-manager#tls#troubleshooting#debug
Decode the tls.crt and show issuer, SANs, validity without manual openssl x509 piping
cmctl inspect secret <name> -n <ns>
#cert-manager#tls#secrets#security
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
#cert-manager#tls#dns#cloud
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>
#cert-manager#tls#dns#troubleshooting
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'
#external-dns#dns#gitops#troubleshooting
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"}'
#metrics-server#monitoring#troubleshooting#k8s
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
#kubeadm#k8s#security
Generate a new token + ready-to-paste worker join line; default tokens expire in 24h
kubeadm token create --print-join-command
#kubeadm#k8s#secrets
List all control-plane cert/kubeconfig expiry dates; catch silent apiserver outages early
kubeadm certs check-expiration
#kubeadm#tls#troubleshooting
Renew every control-plane cert; note: restart static pods (mv manifests) for them to reload
kubeadm certs renew all && systemctl restart kubelet
#kubeadm#tls#troubleshooting
Preview available versions then upgrade control-plane; upgrade kubelet/kubectl separately after
kubeadm upgrade plan && kubeadm upgrade apply v1.30.2
#kubeadm#k8s#troubleshooting
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
#k3s#k8s#network
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>
#k3s#etcd#k8s
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 -
#k3s#k8s#secrets
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
#k3s#debug#troubleshooting
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#k8s#tls
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
#rke2#debug#k8s
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
#etcd#k8s#observability
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
#etcd#disk#troubleshooting
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
#etcd#k8s#observability
Rank pods cluster-wide by restart count to spot crash loops fast
kubectl get po -A --sort-by='.status.containerStatuses[0].restartCount' | tail -20
#k8s-debug#troubleshooting#k8s#observability
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
#k8s-debug#troubleshooting#performance#k8s
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
#k8s-debug#troubleshooting#k8s#performance
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'
#k8s-debug#troubleshooting#k8s#kernel
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'
#k8s-debug#troubleshooting#k8s#security
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
#k8s-debug#troubleshooting#k8s#disk
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
#k8s-debug#troubleshooting#k8s
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}'
#k8s-debug#monitoring#performance#k8s
Check per-CPU conntrack drops/insert_failed; nf_conntrack table exhaustion drops packets
kubectl debug node/<node> -it --image=nicolaka/netshoot -- conntrack -S
#k8s-debug#network#troubleshooting#kernel
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
#k8s-debug#dns#network#troubleshooting
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
#k8s-debug#troubleshooting#observability#k8s
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
#k8s-debug#troubleshooting#debug#k8s
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
#flux#gitops#k8s#cloud
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)
#flux#gitops#ci#cloud
Server-side dry-run showing exactly what Flux would change before applying
flux diff kustomization <name> --path ./overlays/prod
#flux#gitops#debug#k8s
List every object a kustomization owns, including nested kustomizations
flux tree kustomization <name>
#flux#gitops#k8s#troubleshooting
Render the final manifests offline with Flux substitutions, then validate server-side
flux build kustomization <name> --path ./ | kubectl apply --dry-run=server -f -
#flux#gitops#ci#debug
Show all ImageRepositories, policies and update automations across namespaces
flux get images all -A
#flux#gitops#monitoring#k8s
See which tag each policy selected and last scan results per repository
flux get image policy -A && flux get image repository -A
#flux#gitops#monitoring#troubleshooting
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
#flux#notifications#observability#gitops
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>
#flux#notifications#ci#gitops
Pull the latest commit now without touching dependent kustomizations
flux reconcile source git <name>
#flux#gitops#troubleshooting#k8s
Stream the reconcile event history for one object to diagnose drift or failures
flux events --for Kustomization/<name>
#flux#observability#debug#troubleshooting
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
#flux#gitops#k8s#troubleshooting
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
#argocd#gitops#k8s#troubleshooting
Set Kustomize/Helm parameter overrides via -p; modern: prefer Git-tracked overlays for audit
argocd app set <name> -p key=val -p env=prod
#argocd#gitops#k8s
Diff Argo-rendered manifests against live cluster state before syncing
argocd app manifests <name> | kubectl diff -f -
#argocd#gitops#troubleshooting#debug
List/get ApplicationSets and their generated child apps and generators
argocd appset list && argocd appset get <name> -o yaml
#argocd#gitops#k8s
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
#argocd#gitops#secrets#security
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
#argocd#gitops#k8s#troubleshooting
Cancel an in-progress sync stuck on a hook or pending resource
argocd app terminate-op <name>
#argocd#troubleshooting#debug#k8s
Trigger a Deployment rollout restart through Argo's resource actions
argocd app actions run <name> restart --kind Deployment --resource-name <id>
#argocd#k8s#troubleshooting
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 '*'
#argocd#gitops#ci#security
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
#argocd#gitops#k8s
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
#argocd#gitops#secrets#k8s
Sync only one resource by group:kind:name; isolates a fix without full app sync
argocd app sync <name> --resource apps:Deployment:<id>
#argocd#gitops#troubleshooting#k8s
Build/push multiple targets from one HCL file; parallel, DRY group definitions
docker buildx bake -f docker-bake.hcl --push
#docker#buildkit#ci#performance
Show platforms in a manifest list without pulling layers; verify arm64+amd64
docker buildx imagetools inspect <reg>/<name>:tag --format '{{json .Manifest}}'
#docker#buildkit#troubleshooting#cloud
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 .
#buildkit#ci#performance#cloud
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
#docker#buildkit#ci
Reuse package cache across builds without bloating layers; survives between runs
RUN --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
#buildkit#performance#ci
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
#buildkit#secrets#security
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
#buildkit#secrets#security#network
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> .
#docker#buildkit#secrets#security
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
#docker#network#security
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>
#docker#security#kernel
Stream live OOM events to catch memory-limited containers being killed
docker events --filter event=oom --filter type=container
#docker#monitoring#troubleshooting#performance
Analyze layer efficiency and fail the build if too much space is wasted
CI=true dive --lowestEfficiency 0.95 --highestWastedBytes 20MB <reg>/<name>:tag
#dive#ci#performance#observability
Emit a portable .service that recreates the container on start; note: Quadlet is the modern way
podman generate systemd --new --files --name <name>
#podman#systemd#gitops
Reverse-engineer a running pod into a K8s manifest for migration to a cluster
podman generate kube <pod> > pod.yaml
#podman#k8s#gitops
Spin up pods/services from a K8s manifest with no cluster; --replace re-applies cleanly
podman play kube pod.yaml --replace
#podman#k8s#troubleshooting
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
#podman#security#rootless#troubleshooting
Pull newer images and restart labeled containers; needs io.containers.autoupdate=registry label
podman auto-update --dry-run && systemctl --user start podman-auto-update
#podman#ci#gitops#security
Refresh OCI runtime and user-namespace config after a podman/kernel upgrade; fixes stale containers
podman system migrate
#podman#troubleshooting#kernel
Dump runtime info, cgroup path, mounts and pid for a CRI container kubectl can't show
crictl inspect <id> | jq '.info'
#crictl#k8s#debug#troubleshooting
Clean up orphaned NotReady pod sandboxes the kubelet failed to GC; node-level recovery
crictl rmp -f $(crictl pods -q --state NotReady)
#crictl#k8s#troubleshooting#debug
Reclaim disk by deleting images not referenced by any container; safe node disk-pressure fix
crictl rmi --prune
#crictl#k8s#disk#troubleshooting
containerd stores k8s images under the k8s.io namespace; default namespace looks empty
ctr -n k8s.io images ls
#containerd#k8s#troubleshooting
Show containerd tasks with pid/status when the kubelet or CRI layer is unresponsive
ctr -n k8s.io task ls
#containerd#k8s#debug#troubleshooting
Run docker-compose.yml directly on containerd, no Docker daemon; great for k8s-node parity
nerdctl --namespace k8s.io compose up -d
#nerdctl#containerd#k8s
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>
#skopeo#security#ci#cloud
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'
#skopeo#ci#security#observability
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])))
#prometheus#performance#observability#monitoring
alert when linear trend predicts disk full within 4h based on last 6h
predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[6h], 4*3600) < 0
#prometheus#disk#monitoring#troubleshooting
fires when no series match; catches a job that vanished from discovery entirely
absent(up{job="node"} == 1)
#prometheus#monitoring#troubleshooting#observability
extract/derive a new label via regex capture; useful for joins and tidy dashboards
label_replace(node_uname_info, "host", "$1", "nodename", "(.+)")
#prometheus#observability#monitoring
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])
#prometheus#performance#network#observability
without() keeps every label except instance; cleaner than listing many by() labels
sum without(instance) (rate(http_requests_total{code=~"5.."}[5m]))
#prometheus#observability#monitoring
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]))
#prometheus#gitops#observability#performance
lint before reload; run in CI to catch broken expr/yaml before deploy
promtool check rules rules.yml && promtool check config prometheus.yml
#prometheus#ci#gitops#troubleshooting
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])))'
#prometheus#debug#troubleshooting#performance
lists highest-cardinality metrics and label pairs; first stop for memory blowups
promtool tsdb analyze /prometheus --limit 20
#prometheus#performance#troubleshooting#observability
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'
#alertmanager#monitoring#troubleshooting#observability
shows which receiver a label set hits; validate routes before pushing config
amtool config routes test --config.file=alertmanager.yml severity=critical team=db
#alertmanager#ci#gitops#troubleshooting
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'
#victoriametrics#performance#troubleshooting#observability
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
#victoriametrics#disk#cloud#observability
Filter by substring, parse JSON, render only chosen fields. note: | json before line_format.
{app="api"} |= "error" | json | line_format "{{.level}} {{.msg}}"
#loki#logql#observability#debug
Logs/sec grouped by level over 5m window. modern: logfmt parser for key=value lines.
sum by (level) (rate({app="api"} | logfmt [5m]))
#loki#logql#rate#observability
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)
#loki#logql#performance#observability
Count regex-matched error lines per minute across a namespace. |~ is regex match.
sum(count_over_time({namespace="prod"} |~ "timeout|deadline exceeded" [1m]))
#loki#logql#regex#troubleshooting
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
#loki#logcli#debug#observability
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'
#loki#api#monitoring#observability
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"]]}]}'
#loki#api#troubleshooting#observability
Find error spans on a service slower than 2s. combine attribute, status and duration.
{ .service.name = "api" && status = error && duration > 2s }
#tempo#traceql#performance#troubleshooting
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'
#tempo#traceql#api#observability
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)}'
#tempo#api#debug#observability
Statically check collector pipeline before reload. catches bad receivers/processors/exporters.
otelcol validate --config=/etc/otelcol/config.yaml
#opentelemetry#otel#ci#troubleshooting
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
#opentelemetry#otel#observability#cloud
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}'
#opentelemetry#otel#api#debug
Stream live events flowing out of a transform for debugging VRL. modern: vector top for rates.
vector tap --outputs-of parse_logs
#vector#debug#observability#troubleshooting
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
#github-actions#ci#gitops
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')
#github-actions#ci#monitoring
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
#github-actions#debug#troubleshooting
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
#github-actions#ci#debug
Rerun only failed jobs github-actions
Retry just the failed jobs of a run, reusing prior successful results
gh run rerun <id> --failed
#github-actions#ci#troubleshooting
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>
#github-actions#performance#disk
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
#github-actions#security#cloud
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
#gitlab-ci#ci#cloud
Prune dead runners gitlab-ci
Verify configured runners and unregister ones GitLab no longer recognizes
gitlab-runner verify --delete
#gitlab-ci#troubleshooting#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
#gitlab-ci#ci#gitops
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
#gitlab-ci#ci#debug
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
#jenkins#ci#monitoring
Lint a Jenkinsfile server-side before commit to catch syntax errors early
curl -X POST -F "jenkinsfile=<Jenkinsfile" https://<host>/pipeline-model-converter/validate
#jenkins#ci#troubleshooting
Tail logs of the most recent PipelineRun across all its TaskRuns
tkn pipelinerun logs -f --last -n <ns>
#tekton#k8s#debug
Confirm active account, ARN and assumed role before running risky commands
aws sts get-caller-identity --query '{acct:Account,arn:Arn}' --output table
#aws#security#troubleshooting
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 /')
#aws#security#secrets
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
#aws#network#troubleshooting
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
#aws#disk#cloud
Generate a time-limited download URL without making the object public
aws s3 presign s3://<name>/path/file.tgz --expires-in 3600
#aws#security#cloud
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
#aws#k8s#gitops
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
#aws#security#ci
Open an interactive shell on an instance with no open port 22 or bastion
aws ssm start-session --target i-<id> --region <id>
#aws#security#network
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
#aws#observability#debug
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
#aws#security#troubleshooting
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'
#aws#secrets#security
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
#aws#performance#cloud
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
#aws#gitops#ci
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>
#aws#disk#cloud
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>
#gcloud#ci#secrets#cloud
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>
#gcloud#k8s#cloud
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"
#gcloud#network#cloud
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)"
#gcloud#security#cloud
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)'
#gcloud#observability#troubleshooting#cloud
Reach a VM with no public IP through Identity-Aware Proxy; no bastion needed
gcloud compute ssh <name> --zone <id> --tunnel-through-iap
#gcloud#network#security#cloud
Print latest Secret Manager version to stdout; pin a version in CI for repeatability
gcloud secrets versions access latest --secret=<name> --project <id>
#gcloud#secrets#ci#cloud
Mirror dir to GCS; -d deletes extras, modern replacement for gsutil rsync
gcloud storage rsync -r -d ./build gs://<name>/site
#gcloud#disk#cloud
Non-interactive auth for CI; modern: use --federated-token for OIDC, no secret
az login --service-principal -u <id> -p "$AZ_SECRET" --tenant <id>
#az#ci#secrets#cloud
Merge AKS context into kubeconfig; --admin bypasses Azure AD RBAC if enabled
az aks get-credentials -g <name> -n <cluster> --overwrite-existing
#az#k8s#cloud
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
#az#secrets#cloud
-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}"
#az#network#monitoring#cloud
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"]}'
#cloudflare#performance#network#cloud
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}'
#cloudflare#dns#network#cloud
Set default folder-id for the active profile; verify with config list
yc config set folder-id <id> && yc config list
#yc#cloud#iam
Isolate creds per env; use yc --profile prod or YC_PROFILE in CI
yc config profile create prod && yc config profile activate prod
#yc#cloud#ci
OAuth->IAM token, ~12h TTL; feed to API/Terraform via YC_TOKEN env
export YC_TOKEN=$(yc iam create-token)
#yc#iam#security#secrets
Create SA for pipelines; bind least-privilege roles separately
yc iam service-account create --name sa-ci --description 'CI deployer'
#yc#iam#ci#security
Authorized key JSON for non-interactive auth; note: rotate & vault it
yc iam key create --service-account-name sa-ci --output key.json
#yc#iam#secrets#ci
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
#yc#iam#security
Merge external endpoint into kubeconfig; drop --external for internal VPC
yc managed-kubernetes cluster get-credentials <name> --external --force
#yc#k8s#network
Tabulate cluster name/status/id for scripting and audits
yc managed-kubernetes cluster list --format json | jq -r '.[]|[.name,.status,.id]|@tsv'
#yc#k8s#monitoring
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
#yc#k8s#performance#cloud
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
#yc#network#vpc#cloud
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]'
#yc#network#security#vpc
Dump NLB listeners and target groups to debug routing
yc load-balancer network-load-balancer get <name> --format json | jq '.listeners,.attached_target_groups'
#yc#network#troubleshooting#cloud
Enumerate ALB instances and health status across folder
yc application-load-balancer load-balancer list --format json | jq -r '.[]|[.name,.status]|@tsv'
#yc#network#monitoring#cloud
Public zone; FQDN trailing dot required, then delegate NS at registrar
yc dns zone create --name myzone --zone example.com. --public-visibility
#yc#dns#network
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'
#yc#dns#network
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
#yc#cloud#ci#network
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
#yc#cloud#k8s
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)"'
#yc#cloud#troubleshooting
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>
#yc#cloud#secrets
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"
#yc#tls#security
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)"'
#yc#cloud#monitoring
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)"'
#yc#cloud#observability
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)"'
#yc#secrets#security
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'
#yc#cloud#disk
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)"'
#yc#cloud#disk
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}}]}'
#yc#cloud#disk
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
#yc#ci#security
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>
#yc#ci#cloud
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
#yc#ci#troubleshooting
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
#yc#cloud#ci
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)"'
#yc#observability#troubleshooting
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)"'
#yc#tls#security
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;
#postgres#performance#troubleshooting#monitoring
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>);
#postgres#troubleshooting#performance
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;
#postgres#performance#observability#troubleshooting
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
#postgres#performance#debug#disk
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;
#postgres#troubleshooting#performance#debug
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;
#postgres#monitoring#observability#troubleshooting
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;
#postgres#disk#monitoring
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;
#postgres#disk#performance#monitoring
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;
#postgres#performance#disk#troubleshooting
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;
#postgres#performance#monitoring#troubleshooting
Rebuild a bloated index online; note: must run outside a transaction
REINDEX INDEX CONCURRENTLY <name>; -- note: cannot run inside a transaction block
#postgres#performance#disk
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;
#postgres#performance#monitoring
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
#postgres#performance#disk#troubleshooting
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>
#postgres#performance#monitoring
Sample keyspace to find largest keys per type; note: estimates, runs SCAN not blocking
redis-cli --bigkeys
#redis#performance#troubleshooting#debug
Sample keys ranked by actual memory usage, not element count; finds RAM hogs
redis-cli --memkeys
#redis#performance#monitoring#debug
Bytes used by a single key incl overhead; SAMPLES 0 = exact for collections
redis-cli MEMORY USAGE <name> SAMPLES 0
#redis#performance#debug#monitoring
List 10 slowest commands with args and duration, then clear the log
redis-cli SLOWLOG GET 10; redis-cli SLOWLOG RESET
#redis#performance#troubleshooting#observability
Human-readable latency analysis with likely causes; pair with LATENCY HISTORY <event>
redis-cli LATENCY DOCTOR
#redis#performance#troubleshooting#observability
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
#redis#network#troubleshooting#debug
Verify slot coverage, node consistency and open slots across the cluster
redis-cli --cluster check <host>:<port>
#redis#troubleshooting#network#monitoring
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))'
#mongodb#monitoring#troubleshooting#observability
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)})'
#mongodb#troubleshooting#performance#debug
Show docs examined vs returned and index usage; COLLSCAN means missing index
mongosh --eval 'db.<name>.find({status:"active"}).explain("executionStats").executionStats'
#mongodb#performance#troubleshooting#debug
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))'
#mongodb#performance#disk#monitoring
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)'
#mongodb#performance#troubleshooting#observability
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"
#clickhouse#performance#troubleshooting#observability
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"
#clickhouse#troubleshooting#debug#monitoring
Lint rule syntax offline before applying; note: nonzero exit on error, use in CI gate
falco -r /etc/falco/falco_rules.yaml --validate
#falco#security#ci#k8s
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")'
#falco#security#observability#k8s
Pull and manage versioned rules/plugins via OCI; modern: replaces manual rule file copying
falcoctl artifact install falco-rules:latest && falcoctl artifact list
#falco#security#gitops#k8s
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}'
#falco#security#troubleshooting#debug
Discover filter fields for writing custom rule conditions and outputs
falco --list | grep -E 'k8s\.|container\.|proc\.' | sort
#falco#security#debug
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
#falco#security#k8s
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'
#kyverno#security#gitops#k8s
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
#kyverno#ci#security#gitops
Execute kyverno-test.yaml suites asserting resource pass/fail/skip; -d for detailed diff
kyverno test ./tests --remove-color -d
#kyverno#ci#troubleshooting
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
#kyverno#observability#security#troubleshooting
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
#kyverno#security#k8s#gitops
Enumerate ConstraintTemplates and every instantiated constraint kind across namespaces
kubectl get constrainttemplates && kubectl get constraints -A
#opa-gatekeeper#security#k8s#gitops
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}'
#opa-gatekeeper#security#observability#troubleshooting
Validate templates+constraints against fixtures with no cluster; modern: shift-left in CI
gator test -f policy/ && gator verify ./suite
#opa-gatekeeper#ci#security#troubleshooting
Sign by immutable digest, not tag; note: signing a tag is racy and insecure
cosign sign --key cosign.key <host>/<name>@sha256:<id>
#cosign#security#ci#k8s
Keyless signing with Fulcio/Rekor via OIDC identity; modern: default in cosign v2
COSIGN_EXPERIMENTAL=1 cosign sign <host>/<name>@sha256:<id>
#cosign#security#ci#observability
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 .
#cosign#security#troubleshooting#ci
Attach a signed CycloneDX SBOM attestation to an image digest
cosign attest --key cosign.key --predicate sbom.json --type cyclonedx <host>/<name>@sha256:<id>
#cosign#security#ci#observability
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 .
#cosign#security#troubleshooting#observability
Encrypt only values in place; note: keys stay readable so diffs stay reviewable
SOPS_AGE_RECIPIENTS=age1<id> sops -e -i secrets.yaml
#sops#secrets#security#gitops
Rotate data key to recipients in .sops.yaml without re-encrypting plaintext manually
sops updatekeys secrets.yaml
#sops#secrets#security#gitops
Inject decrypted secrets as env vars for one command; note: nothing hits disk
sops exec-env secrets.enc.yaml 'terraform apply'
#sops#secrets#ci#security
Set a single nested key without opening an editor; great for scripted rotation
sops --set '["db"]["password"] "s3cr3t"' secrets.enc.yaml
#sops#secrets#ci#troubleshooting
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
#age#secrets#security#tls
Update one field without rewriting the whole secret; note: kv patch needs KV-v2
vault kv patch -mount=secret app api_key=<id>
#vault#secrets#troubleshooting
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
#vault#secrets#security#troubleshooting
Show effective ACL verbs the current token has on a path; fast policy debugging
vault token capabilities database/creds/readonly
#vault#security#troubleshooting#observability
Revoke all leases under a prefix to kill leaked dynamic DB creds instantly
vault lease revoke -prefix database/creds/readonly
#vault#security#troubleshooting#secrets
Rename/refactor address without destroy; prefer moved{} block in newer TF
terraform state mv 'aws_instance.web' 'aws_instance.app'
#terraform#gitops#troubleshooting
Forget resource from state without deleting real infra; note: object keeps existing
terraform state rm 'aws_s3_bucket.legacy'
#terraform#troubleshooting#cloud
Dump all attributes of one resolved address for drift/debug investigation
terraform state show 'module.vpc.aws_subnet.private[0]'
#terraform#debug#troubleshooting
Filter managed addresses to find what TF tracks before surgery
terraform state list | grep -i 'aws_iam'
#terraform#troubleshooting#security
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
#terraform#gitops#cloud
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
#terraform#gitops#troubleshooting
Force destroy+recreate of one resource; replaces deprecated terraform taint
terraform apply -replace='aws_instance.web'
#terraform#troubleshooting#cloud
Limit plan to one address; note: -target is an escape hatch, can mask drift
terraform plan -target='module.db.aws_db_instance.main'
#terraform#troubleshooting#debug
Sync state to real infra without proposing changes; surfaces out-of-band drift
terraform plan -refresh-only
#terraform#monitoring#troubleshooting
Move state to a new backend; use -reconfigure to skip migration and reset
terraform init -migrate-state -backend-config=backend.hcl
#terraform#gitops#troubleshooting
Pipe machine-readable outputs into jq for scripting and downstream wiring
terraform output -json | jq -r '.endpoints.value[]'
#terraform#ci#observability
Capture provider/API debug to a file; use TRACE for the most verbose level
TF_LOG=DEBUG TF_LOG_PATH=tf.log terraform plan
#terraform#debug#troubleshooting
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
#ansible#vault#secrets#security
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
#ansible#vault#secrets#security
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
#ansible#vault#secrets#security
Render dynamic cloud inventory tree with host vars; verify plugin grouping before a run
ansible-inventory -i aws_ec2.yml --graph --vars
#ansible#cloud#troubleshooting#network
Materialize a dynamic inventory to static YAML for diffing or offline debugging
ansible-inventory -i aws_ec2.yml --list --yaml > resolved_inventory.yml
#ansible#cloud#troubleshooting
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
#ansible#cloud#gitops
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
#ansible#ci#troubleshooting
Apply the role to the test instance, then run assertions (testinfra/ansible verifiers)
molecule converge && molecule verify
#ansible#ci#monitoring
Re-run the role and fail if any task reports changed — catches non-idempotent tasks
molecule idempotence
#ansible#ci#troubleshooting
SSH into a live Molecule test container to inspect state mid-scenario before destroy
molecule login --host instance
#ansible#ci#debug#troubleshooting
Skip everything before a named task; resume a failed long playbook without redoing setup
ansible-playbook site.yml --start-at-task "Deploy app config"
#ansible#debug#troubleshooting
Preview execution plan: every task and resolved target host, without connecting
ansible-playbook site.yml --list-tasks --list-hosts -i prod
#ansible#debug#troubleshooting
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
#ansible#performance#observability
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>
#ansible#debug#troubleshooting
Per-thread CPU breakdown troubleshooting
Per-thread CPU%, find the hot TID inside a busy process for jstack/perf
pidstat -t -p <pid> 1
#troubleshooting#performance#cpu#debug
Hot thread live view troubleshooting
Live per-thread view; convert hot TID to hex (printf %x) to match jstack nid
top -H -p <pid>
#troubleshooting#performance#cpu#debug
Per-core CPU saturation troubleshooting
Per-core %usr/%sys/%iowait — spot a single saturated core vs balanced load
mpstat -P ALL 1
#troubleshooting#performance#cpu#monitoring
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
#troubleshooting#performance#cpu#debug
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
#troubleshooting#performance#debug#kernel
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
#troubleshooting#memory#debug#monitoring
Fast memory rollup troubleshooting
One-shot Rss/Pss/Swap totals without parsing full smaps; cheap on huge maps
cat /proc/<pid>/smaps_rollup
#troubleshooting#memory#debug#performance
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
#troubleshooting#memory#debug
Kernel slab top consumers troubleshooting
Sort slab caches by size; dentry/inode bloat explains kernel memory pressure
slabtop -o -s c | head -20
#troubleshooting#memory#kernel#performance
Reclaimable slab memory troubleshooting
Split slab into reclaimable vs unreclaimable; high SUnreclaim = real kernel leak
grep -E 'Slab|SReclaimable|SUnreclaim' /proc/meminfo
#troubleshooting#memory#kernel#debug
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
#troubleshooting#memory#oom#kernel
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
#troubleshooting#memory#oom#kernel
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'
#troubleshooting#memory#oom#k8s
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
#troubleshooting#disk#debug#performance
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)}'
#troubleshooting#disk#performance#monitoring
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
#troubleshooting#disk#performance#observability
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
#troubleshooting#network#kernel#performance
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
#troubleshooting#network#debug#kernel
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
#troubleshooting#network#performance#kernel
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
#troubleshooting#network#performance#debug
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>
#troubleshooting#network#dns#debug
Show actual src/iface for a dest; FAILED neigh entries = L2/ARP problem
ip route get <ip>; ip neigh show | grep -E 'FAILED|INCOMPLETE'
#troubleshooting#network#debug
TCP-SYN traceroute survives ICMP filtering; nc -zv confirms open port
traceroute -T -p 443 <host>; nc -zv <host> 443
#troubleshooting#network#security#debug
Pin host to a specific IP to test backend while keeping SNI/Host header
curl -sv --resolve <host>:443:<ip> https://<host>/healthz
#troubleshooting#network#dns#debug
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
#troubleshooting#k8s#dns#debug
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
#troubleshooting#k8s#dns#debug
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
#troubleshooting#k8s#dns#observability
Grade supported TLS versions/ciphers; flags weak/deprecated suites per port
nmap --script ssl-enum-ciphers -p 443 <host>
#troubleshooting#tls#security#network
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:'
#troubleshooting#tls#security#debug
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
#troubleshooting#tls#security#monitoring
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 .
#troubleshooting#security#secrets#api
Enumerate services/methods over reflection; -plaintext skips TLS for debug
grpcurl -plaintext <host>:<port> list; grpcurl -plaintext <host>:<port> describe <svc>
#troubleshooting#network#api#debug