Kubectl tips and tricks

I think one big topic would be about using --output='jsonpath=...', vs --output='json' | jq ....

Personally, I find jq much more user-friendly, but jsonpath is so much more portable - just copy the script and no need to make sure you have jq installed… What do people think?

5 Likes

Some good aliases can be found here too.

I use a couple similar to kcns and kex fairly regularly.

I also have alias kc='kubectl --namespace ${KUBE_NAMESPACE:-default} ' so I can export a namespace easily in a shell and not always have to type it. For me, kcns sets that variable

3 Likes

Thanks for all the hardwork - we are loving these tips and tricks on TGIK!

4 Likes

This might be obvious for some, but I was very excited when I learned about kubectl explain. It explains resources and/or the fields of their configuration (e.g. kubectl explain resource.field.field).

8 Likes

I use autohot keys to shorten the commands in kubernetes

I forgot to mention! Sometime last year I wrote kubeplay. It is intended for interactive scripting, like a REPL basically.

Personally, I find kubectl to tedious, and gluing it with shell scripts can be even more tedious.

Currently, kubeplay uses Ruby syntax (via mruby embedded in a Go program), but I am keen to explore other options. I am also not a fan of pseaudo-graphical interactive console apps, so this more of a pure REPL based on a proper language :slight_smile:

Take a look and let me know if you would be keen to use it, I would love to put more time into it!

3 Likes

Ok this might sounds very stupid, but here some alias I use for kubectl:

alias k='kubectl'
alias watch='watch '
alias pods='k get pods'
alias spods='k get pods -n kube-system'
alias deployments='k get deployments'
alias sdeployments='k get deployments -n kube-system'
alias ds='k get ds'
alias sds='k get ds -n kube-system'
alias logs='k logs'
alias slogs='k logs -n kube-system'

In general I think the best aliases are the one you build for yourself and that make your life easier every day… and I really can’t live without my “spods”.

EDIT: Also, hi!

2 Likes

Hi all :slight_smile:

I find this combo very helpful, a fuzzy finder fzf + kubectl + some bash/zsh function.

Examples:
exec into a pod

kx () {
	local pod=($(kubectl get pods --all-namespaces -owide | fzf | awk '{print $1, $2}'))
	local cmd=${@:-"bash"}

	echo kubectl exec -it --namespace $pod[1] $pod[2] $cmd
	kubectl exec -it --namespace $pod[1] $pod[2] $cmd
}

logs

kl () {
	local pod=($(kubectl get pods --all-namespaces -owide | fzf | awk '{print $1, $2}'))
	local attr=${@:-""}

	echo kubectl logs -f $attr --namespace $pod[1] $pod[2]
	kubectl logs -f $attr --namespace $pod[1] $pod[2]
}
8 Likes

Earlier this year I gave a talk at a Kubernetes meetup around this topic, might be of interest as well: http://mhausenblas.info/kubectl-in-action/

4 Likes

I’m learning how to make custom resources and custom controllers, and I’ve ended up making a kubectl custom plugin for the k8s.io/sample-controller’s Foo resource:


The nice thing about kubectl custom plugins is that you can write them in any language you want.

6 Likes

I have been happy with complete-alias for Bash. In addition to stuff like k=kubectl, it works well for things like gco='git checkout'.

1 Like

The most important tip I would like to share with all

kubectl [...] --v=8 to display detail req/rsp during your call

5 Likes

Run a shell in a new pod (to examine the kubernetes environment from the inside):

alias kshell='kubectl run -it shell --image giantswarm/tiny-tools --restart Never --rm -- sh'

--restart Never” ensures that only a pod resource is created (instead of a deployment, replicaset and pod)
--rm” ensures the pod is deleted when you exit the shell

Of course, if you have existing pods, it may be easier to just run kubectl exec ... sh in one of them (but the container might not have tools like dig, ping, curl, …)

7 Likes

If somebody needs the same as kubectx and kubens for kubecfg see my forked version =>

#dump kubernetes manifests to json
#Ex usage: "kdump -e default -o staging" will export the cluster state to "./staging.json" excluding the "kube-system" and "default" namespaces.

kdumpusage() { echo "Usage: $0 [-e namespace  to exclude from backups] [-o name]" 1>&2; }

function kdump () {
	while getopts ":e:o:" i; do
	    case "${i}" in
	        e)
	            e=${OPTARG}
	            ;;
	        o)
	            o=${OPTARG}
	            ;;
	        *)
	            kdumpusage
	            ;;
	    esac
	done
	shift $((OPTIND-1))

	if [ -z "${e}" ] || [ -z "${o}" ]; then
	    kdumpusage
	fi

	for ns in $(kubectl get ns --no-headers | cut -d " " -f1); do
	  if { [ "$ns" != "kube-system" ]; }; then
	  kubectl --namespace="${ns}" get --export -o=json svc,rc,rs,deployments,cm,secrets,ds,statefulsets,ing,pv,pvc | \
	jq '.items[] |
	    select(.type!="kubernetes.io/service-account-token") |
	    del(
	        .spec.clusterIP,
	        .metadata.uid,
	        .metadata.selfLink,
	        .metadata.resourceVersion,
	        .metadata.creationTimestamp,
	        .metadata.generation,
	        .status,
	        .spec.template.spec.securityContext,
	        .spec.template.spec.dnsPolicy,
	        .spec.template.spec.terminationGracePeriodSeconds,
	        .spec.template.spec.restartPolicy
	    )' >> "./$o.json"
	  fi
	done
}

# quickly terminate stuck pods
function kfp () {
	for ns in $(kubectl get ns --no-headers | cut -d " " -f1); do
		kubectl get pods --namespace="${ns}" | grep 'CrashLoopBackOff\|Error\|Terminating\|ImagePullBackOff\|Pending\|ErrImagePull\|Unknown' | cut -d " " -f 1 | xargs -n 1 kubectl delete pod --namespace="${ns}" --grace-period=0 --force
	done
}
1 Like

A cople of months ago I write a little article ( in Spanish ) to have some tools ready on the terminal, maybe could be interesting for someone:

A small go tool to merge kubernetes contexts to your ~/.kube/config is k8s-ctx-import

For example: cat <kubeconfig> | k8s-ctx-import to import <kubeconfig>'s active context to your kubeconfig in $KUBECONFIG

1 Like

in the jx binary from Jenkins X we added a bunch of handy sub commands for switching namespaces/contexts visually or via CLI arguments

e.g. to switch namespaces just type:

jx ns

and you are prompted with a list of namespaces to choose from. To switch contexts:

the next one is Jenkins X specific - it requires Jenkins X Environment CRDs - but can switch between environments via:

jx env

this then prompts you with your environments (say Dev, Staging, Production without having to worry what the physical namespaces are etc)

jx ctx

the command I love the most though is sometimes you want to switch contexts/namespaces in just 1 shell only (e.g. to tinker on some production cluster). To do that use

jx shell

Then the context updates and the prompt changes to show the new context/namespace - but all other shells stay on the same namespace/context! Then just exit to get back to the global shared context. Super handy

A couple more:

jx rsh

opens a remote shell giving a list of the pods to pick from. You can supply a filter if you prefer (such as a deployment name).

jx log

As above tails the log of the latest pod from a picked list of pods or takes a deployment filter name. Its handy as the log rolls over to the next pod as pods rollover or restart etc

3 Likes

Yes I do and it works, and autocompletion works too.
The only thing is it does not work with the ‘watch’ command (watch k get pods). In this case I use ‘watch kubectl get pods’.

I even have the alias g=gcloud, because I am on GCP

Thanks

1 Like