Kubectl Cheat Sheet
Useful commands list.
General
Overview
https://kubernetes.io/docs/reference/kubectl/overview/
Install
curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl
chmod +rx ./kubectl
sudo mv ./kubectl /usr/local/binEnable autocomplete
sudo apt-get install bash-completion
source /usr/share/bash-completion/bash_completion
echo 'source <(kubectl completion bash)' >>~/.bashrc
sudo su -
kubectl completion bash >/etc/bash_completion.d/kubectlEnable autocomplete for an alias.
alias k=kubectl
source <(kubectl completion bash | sed 's/kubectl/k/g')References
https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion
Explain components
Run kubectl from inside a container
TTY connect to your container and make sure kubectl is installed.
Import your Kubernetes config
When you are connected to a container deployed in Kubernetes cluster, it already has access to Kubernetes config and certificates, you only need to import them:
At this point you should have the file ~/.kube/config.
Generate kubeconfig from ServiceAccount
Cluster management
Get cluster name
Get cluster endpoints
List all API resources
Logs
Get logs from a previous restart pod:
Namespaces
Force delete namespace (hanging on "Terminating")
If the namespace is not deleted, check its manifest:
Check if it has any finalizers, for example:
Edit it:
And delete the finalizers block.
If it does not work, export namespace manifest to a file.
Edit the file, on finalizers block, remove "kubernetes" (or any other existing finalizer).
Nodes
Get nodes
Permission
can-i
Pods
Connect to pod TTY
The right way
List your pods:
Locate the one you want access, get its name, and run:
If your namespace has only one pod, your use only one command:
Workaround
If by any reason you could not use kubectl exec (for example, if your container does not allow root auth), then SSH to your K8s worker node which is hosting your pod.
Locate the container you want to connect to:
Then connect to it:
Force delete pod
Never force pod deletion unless it is really necessary
If you have a pod which is referenced by a Replica Set that does not exist and you are stuck, force pod deletion.
References
Get pods, filter by label, print pod name and its namespace
kubectl get pods -Ao jsonpath='{range .items[?(@.metadata.labels.app=="my-ubuntu")]}{@.metadata.name}{" "}{@.metadata.namespace}{"\n"}{end}'
RBAC
(Cluster)RoleBindings and the ServiceAccount(s) they reference with
Resources
List pods resource limits
Last updated