Kubectl - writing your own plugin

Sat 28 March 2020 by admin

Kubectl is an entrypoint for maintaing k8s clusters, you can find a lot useful switches to extract data. For example to get all containers images, just use:

$ kubectl get pods --all-namespaces -o go-template --template="{{range .items}}{{range .spec.containers}}{{printf \"%s\n\" .image}}{{end}}{{end}}"

Lots of switches to remember, to deal with it easy just write another shell alias, like the ones in project kubectl-aliases or... write your own plugin. With kubectl is pretty simple, you don't have to contribute to project, just write your own piece of code name it as kubectl_<yourplugin> and put it in shell PATH. Kubectl will search it when you type:

$ kubectl <yourplugin>

don't believe ? look at plugin.go it search for plugins ;) To accomplish this task and end with kubectl images switch:

$ ls -l kubectl-images
-rwxr-xr-x  1 wit  staff  365 Mar 26 14:55 kubectl-images
$ cat kubectl-images
#!/usr/bin/env bash

if [[ $1 == "list" ]]; then
    kubectl get pods --all-namespaces -o go-template \
            --template="{{range .items}}{{range .spec.containers}}{{printf \"%s\n\" .image}}{{end}}{{end}}"
    exit 0
fi

if [[ "$1" == "version" ]]; then
    echo "v0.0.1"
    exit 0
fi

cat << EOF
get all image list in all namespaces
usage: list|version
EOF
$ kubectl images list
quay.io/jetstack/cert-manager-controller:v0.12.0
...

It works with kubectl since v1.12, more info on Extend kubectl with plugins


Comments