Often used commands

Kubernetes API

Common Naming Convention

Follow an APPNAME-RESOURCE-TYPE convention consistent with Helm when naming resources. For example:

$RESOURCE (e.g. app-configurator)
$APPNAME-$RESOURCE (e.g. myhiway-app-configurator)
$APPNAME-$RESOURCE-$TYPE (e.g. myhiway-app-configurator-secret)

APPNAME=name-of-application (e.g. myhiway)
RESOURCE=name-of-kube-resource (e.g. app-configurator)
TYPE=cm, configmap
TYPE=cronjob
TYPE=daemonset
TYPE=deployment
TYPE=endpoint
TYPE=event
TYPE=ing, ingress
TYPE=namespace
TYPE=node
TYPE=pv, persistentvolume
TYPE=pvc, persistentvolumeclaim
TYPE=pod
TYPE=pdb, poddisruptionbudget
TYPE=rs, replicaset
TYPE=sa, serviceaccount
TYPE=secretproviderclass
TYPE=secret
TYPE=svc, service
TYPE=statefulset
TYPE=sc, storageclass

Many TYPE names have shortcuts and can be used without the plural 's' where shown. And the RESOURCE variables in the commands below can represent different strings depending on what specificity the context needs.

CONTAINER=name-of-container-inside-of-pod
CONDITION=evicted, error, or crash
FILENAME=name-of-file
STRING=search-string

Often used flags

-c, --container
-n, --namespace,
-A, --all-namespaces
-l (show label, requires a resource)
--show-labels (show labels for all resource)
-o, --output (there are many output shapes => wide, json, jsonpath, yaml, go-template, etc.)
-w, --watch
-it, --stdin --tty

See the watch command on MacOS for a broader watch utility , e.g. watch 'kubectl get all

get

Display one or many resources.
kubectl get $TYPE
kubectl get $TYPE -w
kubectl get $TYPE -o wide
kubectl get $TYPE -o json

Get all resources.
kubectl get all
kubectl get cm,daemonset,deployment,job,ing,pvc,pdb,pod,rs,secret,statefulset,svc

NAMESPACE=the-wheel
kubectl api-resources --verbs=list --namespaced -o name | xargs -n1 kubectl get --show-kind --ignore-not-found "$@" -n $NAMESPACE
kubectl api-resources --verbs=list --namespaced -o name | xargs -n1 kubectl get --show-kind --ignore-not-found -nl -n $NAMESPACE | grep $APPNAME

Get all resources - by filter.
kubectl get configmap,daemonset,deployment,job,ing,pvc,pdb,pod,replicaset,secret,statefulset,svc | grep solr

Get a resource.
RESOURCE=thewheel-app-configurator-67cd4dd5f-j9s24
TYPE=pod
kubectl get $TYPE $RESOURCE
+ kubectl get pod thewheel-app-configurator-67cd4dd5f-j9s24

RESOURCE=thewheel-app-configurator-secret
TYPE=secret
kubectl get $TYPE $RESOURCE
+ kubectl get secret thewheel-app-configurator-secret

$TYPE $RESOURCE can also be expressed as $TYPE/$RESOURCE, e.g. kubectl get pod foo => kubectl get pod/foo

Get a resource - filter by regex.
RESOURCE=thewheel-app-configurator
TYPE=secret
kubectl get $TYPE $(kubectl get $TYPE | grep $RESOURCE | awk '{print $1}')
+ kubectl get secret thewheel-app-configurator-secret

Get a resource - filter by label selector.
kubectl get $TYPE --show-labels
kubectl get $TYPE --show-labels | grep $RESOURCE
kubectl get pod -l app=$RESOURCE
kubectl get pod -l app=$RESOURCE --no-headers -o name
kubectl get pod -l app=$RESOURCE --no-headers -o name | awk -F '/' '{print $2}'

Get events - sort by time desc.
kubectl get events --sort-by=.metadata.creationTimestamp

Get secrets - base64 decoded.
kubectl get secret $RESOURCE -o json | jq '.data | map_values(@base64d)'

Get secrets - base64 decoded as file.
kubectl get secret $RESOURCE -o json | '.data | map_values(@base64d)' > ~/filename.json

Get secrets - base64 encoded.
kubectl get secret $APPNAME-$RESOURCE-$TYPE -o go-template='{{.data.bootstrapPassword|base64decode}}{{"\n"}}'

Get value from resource manifest by following json path.
kubectl get $TYPE $APPNAME-$RESOURCE-$TYPE -o jsonpath={.spec.template.spec.containers[0].name}

Get all containers inside a Pod.
kubectl get pod <podname> -o jsonpath='{.spec.containers[*].name}*' $RESOURCE $CONTAINER

delete

Delete resources by filenames, stdin, resources and names, or by resources and label selector.
kubectl delete $TYPE $RESOURCE
kubectl delete $TYPE $(kubectl get $TYPE | grep $STRING | awk '{print $1}')

Forcefully kill a pod named (be careful with this!).
kubectl delete pod $RESOURCE --force --grace-period 0

Delete all evicted, erroring, or crashed pods.
kubectl get pod -n default | grep prod | grep $CONDITION | awk '{print $1}' | xargs kubectl delete pod -n default

describe

Show details of a specific resource or group of resources.
kubectl describe $TYPE $APPNAME-$RESOURCE-$TYPE
kubectl describe $TYPE $(kubectl get $TYPE | grep $STRING | awk '{print $1}')

cp

Copy files and directories to and from containers.

PODNAME=(e.g. thewheel-app-configurator-67cd4dd5f-j9s24)
DESTINATION_PATH=(e.g. /var/www/wp-content-mount)
SOURCE_PATH=(e.g. ./data/wp-content/plugins)
kubectl cp $SOURCE_PATH $PODNAME:$DESTINATION_PATH

exec

Open console shell in single container pod.
kubectl exec -it $RESOURCE -- /bin/sh

Containers can have a variety of shells, e.g. bash, sh, bin/bash, bin/sh, dash

Open console shell in one of multiple containers in pod.
kubectl exec -it $RESOURCE -c $CONTAINER -- /bin/bash
kubectl exec -it $(kubectl get $TYPE | grep $STRING | awk '{print $1}') -- /bin/sh

Run commands directly in a container.
kubectl exec -it $RESOURCE -- mysql -uwordpress -phard2find --database=blog < ./data/blog.sql
kubectl exec -it $RESOURCE -- chown -R 33:33 /var/www/wp-content-mount

logs

Print the logs for a container in a pod.
kubectl logs $RESOURCE

Follow log.
kubectl logs -f $RESOURCE
kubectl logs -f $(kubectl get pod | grep $STRING | awk '{print $1}')

Follow log in a specific container.
kubectl logs -f -l "$STRING" -c $RESOURCE

Find specific text or results in log.
kubectl logs -f $(kubectl get pod | grep $STRING | awk '{print $1}') | grep -i 'we are authenticated'
kubectl logs -f $(kubectl get pods | grep transformer | awk '{print $1}') | grep 'ingester = ' | awk '{print $4 $5 $6}' | sort -u

port-forward

Forward one or more local ports to a pod port.
kubectl port-forward $RESOURCE 8080:80
kubectl port-forward pod/$RESOURCE 8080:80
kubectl port-forward pod/$(kubectl get pods | grep $STRING| awk '{print $1}') 8080:80
kubectl port-forward service/$RESOURCE 8080:80

Preserve existing environment variables.
sudo -E kubectl port-forward service/$RESOURCE 8080:80

Port-forward local port to server.
ssh -L 6443:localhost:6443 fusiondev1

Manage cronjobs/jobs


Create job from cronjob
kubectl create job --from=cronjob/$RESOURCE manual-$RESOURCE-job
kubectl delete job $(kubectl get job | grep manual | awk '{print $1}') && kubectl create job --from=cronjob/$RESOURCE manual-$RESOURCE-job

Show status of all jobs
kubectl get job -o json | jq -r '.items[] | .metadata.name + ":" + (.status.conditions[] | select(.status == "True") .type + ":" + .status)' | grep $STRING

CRUD type operations


apply

Apply a configuration to a resource by filename or stdin - performs a diff and only applies changes if the resource already exists.
kubectl apply -f $FILENAME

create

Create a resource from a file or from stdin.
kubectl create -f $FILENAME

patch

Update field(s) of a resource using strategic merge patch.
kubectl patch $TYPE $RESOURCE

replace

Replace a resource by filename or stdin.

rollout

Manage the rollout of a resource.
kubectl rollout restart $TYPE $RESOURCE

Cluster/node maintenance


NODE=server-name

Show what pods are on what nodes?
for pod in $(kubectl get pods | grep thewheel | awk '{print $1}'); do echo $pod; kubectl describe pod $pod | grep 'Node:'; done

for pod in $(kubectl get pods -l app=$RESOURCE --no-headers -o name | awk -F '/' '{print $2}'); do echo -n "Checking $pod .... "; kubectl exec "$pod" -- bash -c "ps aux | grep -v grep | grep enable-ssl-passthrough=true" > /dev/null 2>&1 && echo "Good" || echo "Bad"; done

config

kubectl config use-context k3d-k3s-default
kubectl config set-context --current --namespace=team-a

cluster info

kubectl cluster-info

top

Get node resource consumption.
kubectl top node

cordon

Mark node as unschedulable.
kubectl cordon ...

drain

Drain node in preparation for maintenance.
kubectl drain $NODE

uncordon

Mark node as schedulable.
kubectl uncordon ...

proxy

Proxy to a node.
See kubectl proxy

Cluster/node info


api-resources

Print the supported API resources on the server.

api-versions

Print the supported API versions on the server, in the form of "group/version".

completion

Output shell completion code for the specified shell (bash or zsh).

diff

Diff live version against would-be applied version.

explain

Documentation of resources.

top

Display Resource (CPU/Memory/Storage) usage.

version

Print the client and server version information.

Kubectl Aliases


Shorten kubectl commands by creating a file with a starter set of aliases that leverage bash-completion.

On a Mac, install bash-completion with brew install bash-completion, depending on your version of bash.

vim ~/.kubectl_aliases

# KUBECTL - ALIASES 
alias k='kubectl'
alias kd='kubectl describe '
alias kg='kubectl get '
alias kdl='kubectl delete '
alias kex='kubectl exec -it '
alias klo='kubectl logs -f '

alias kgoy='kubectl get -o yaml '

alias cro='cronjob'
alias dep='deployment'
alias sec='secret'
alias spc='secretproviderclass'

# KUBECTL - EXPAND COMMAND ON USE
[ -f ~/.kubectl_aliases ] && source ~/.kubectl_aliases
function kubectl() { echo "+ kubectl $@">&2; command kubectl $@; }

# KUBECTL - ENABLE AUTOCOMPLETION
[[ -r "/usr/local/etc/profile.d/bash_completion.sh" ]] && . "/usr/local/etc/profile.d/bash_completion.sh"
source <(kubectl completion bash)

Spaces at the ends are important, and some shortcuts are not needed because they already exist

Examples:

kg pod
+ kubectl get pod

kdl pod $RESOURCE
+ kubectl delete pod $RESOURCE

kgoy pod $RESOURCE
+ kubectl get -o yaml pod $RESOURCE

kex $(kg pod | grep $RESOURCE | '{print $1}') -- /bin/sh
+ kubectl exec -it $(kubectl get cronjob | grep $RESOURCE | awk '{print $1}') -- /bin/sh