Skip to content

Instantly share code, notes, and snippets.

@ProximaB
Forked from pydevops/kubectl.md
Created October 27, 2020 11:15
Show Gist options
  • Save ProximaB/906833e0225f1643673f92fcf2acdb84 to your computer and use it in GitHub Desktop.
Save ProximaB/906833e0225f1643673f92fcf2acdb84 to your computer and use it in GitHub Desktop.
k8s kubectl cheat sheet

reference

cheatsheet

cool gear to have

imperative

debug

context, namespace

 get current context: kubectl config view -o=jsonpath='{.current-context}'
 get all contexts:  kubectl config get-contexts -o=name | sort -n
 get namesapce:  kubectl get namespaces -o=jsonpath='{range .items[*].metadata.name}{@}{"\n"}{end}'
 
kubectl config use-context <cluster_name_in_kubeconfig>
kubectl --context <context>

## set the namespace for the current context
kubectl config set-context gke_sandbox-co_us-west1-a_cka --namespace=kube-system
kubectl config set-context --current --namespace=kube-system

API

# Print the supported API group and its versions on the server, in the form of "group/version"
k api-versions | sort 

# find out what is under the api group

k api-resources --api-group apps
NAME                  SHORTNAMES   APIGROUP   NAMESPACED   KIND
controllerrevisions                apps       true         ControllerRevision
daemonsets            ds           apps       true         DaemonSet
deployments           deploy       apps       true         Deployment
replicasets           rs           apps       true         ReplicaSet
statefulsets          sts          apps       true         StatefulSet

k api-resources --api-group extensions
NAME                  SHORTNAMES   APIGROUP     NAMESPACED   KIND
daemonsets            ds           extensions   true         DaemonSet
deployments           deploy       extensions   true         Deployment
ingresses             ing          extensions   true         Ingress
networkpolicies       netpol       extensions   true         NetworkPolicy
podsecuritypolicies   psp          extensions   false        PodSecurityPolicy
replicasets           rs           extensions   true         ReplicaSet

k api-resources --api-group=batch
NAME       SHORTNAMES   APIGROUP   NAMESPACED   KIND
cronjobs   cj           batch      true         CronJob
jobs                    batch      true         Job

k api-resources --api-group=networking.k8s.io
NAME              SHORTNAMES   APIGROUP            NAMESPACED   KIND
ingresses         ing          networking.k8s.io   true         Ingress
networkpolicies   netpol       networking.k8s.io   true         NetworkPolicy

kubectl api-resources --sort-by=name 
kubectl api-resources --sort-by=kind

k explain --api-version=apps/v1beta1 deployment --recursive
k explain --api-version=apps/v1beta2 deployment --recursive
k explain --api-version=apps/v1 deployment --recursive

# for each "group/version" in the output above except for "api/v1"
kubectl get --raw /apis/group/version |  jq -r '.resources[].kind'

kubectl get --raw /apis/apps/v1 | jq . -C | less -R

list resources under a specific api version.

This is due to API deprecations

kubectl get deployments.v1.apps

secret

echo $(kubectl get secret/terraform -o jsonpath="{.data['terraform\.json']}" | base64 --decode)

Play with jid and jq


grace=$(kubectl get po cassandra-0 -o=jsonpath=‘{.spec.terminationGracePeriodSeconds}’) 
grace=$(kubectl get sts -l component=elasticsearch,role=data -o jsonpath='{..terminationGracePeriodSeconds}'

kubectl get svc -l component=elasticsearch,role=client -o jsonpath='{..ip}'
kubectl get pods -o jsonpath="{..image}"
kubectl get pods -o jsonpath="{.items[*].spec.containers[*].image}"
kubectl get pods -o jsonpath='{.items[*].status.podIP}'
kubectl get nodes -o jsonpath='{.items[*].spec.podCIDR}' | tr " " "\n"
kubectl get nodes -o json | jq '.items[] | .spec'
kubectl get no -o go-template='{{range .items}}{{.spec.podCIDR}}{{"\n"}}{{end}}'
kubectl get pods -o jsonpath='{range .items[*]}{"\n"}{.metadata.name}{":\t"}{range .spec.containers[*]}{.image}{", "}{end}{end}'
kubectl get pods -o go-template --template="{{range .items}}{{range .spec.containers}}{{.image}} {{end}}{{end}}"

kubectl get pods --all-namespaces -o jsonpath="{..image}" |\
tr -s '[[:space:]]' '\n' |\
sort |\
uniq -c

custom-columns

k get po -A -o=custom-columns='DATA:spec.containers[*].image'
kubectl get pv --sort-by=.spec.capacity.storage -o=custom-columns="NAME:.metadata.name,CAPACITY:.spec.capacity.storage"
k get deployment -o custom-columns='IMAGE:.spec.template.spec.containers[*].image,LABEL:.spec.template.metadata.labels.k8s-app' -n kube-system

sort-by

kubectl get po --sort-by=.spec.nodeName -o wide
kubectl get po --sort-by=".metadata.creationTimestamp"

Get the TCP LB port and IP

  EXT_IP="$(kubectl get svc hello-server -o=jsonpath='{.status.loadBalancer.ingress[0].ip}')"
  EXT_PORT=$(kubectl --namespace default get service hello-server -o=jsonpath='{.spec.ports[0].port}')
  echo "$EXT_IP:$EXT_PORT"
  [ "$(curl -s -o /dev/null -w '%{http_code}' "$EXT_IP:$EXT_PORT"/)" -eq 200 ] || exit 1

deployment

rollout

kubectl rollout pause deployment/hello
kubectl rollout status deployment/hello
# check the versions on pods
kubectl get pods -o jsonpath --template='{range .items[*]}{.metadata.name}{"\t"}{"\t"}{.spec.containers[0].image}{"\n"}{end}'
kubectl rollout resume deployment/hello
# roll back
kubectl rollout undo deployment/hello

find top resource hungry pod

# cpu
k top pods --sort-by=cpu
kubectl top pods -A | sort -rn -k 3
# memory
kubectl top pods -A | sort -rn -k 4
# top 1
kubectl top pod | grep -v NAME | sort -k 3 -nr | awk -F ' ' 'NR==1{print $1}'

rbac

k auth can-i get crd
k auth can-i get crd --as system:serviceaccount:default:deployer
k auth can-i '*' '*' --all-namespaces

# with krew plugins
k access-matrix --sa default:deployer
k rbac-lookup deployer -o wide
k rbac-lookup -k user
k rbac-lookup -k group
k rbac-lookup -k serviceaccount
k who-can create customresourcedefinition
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment