Skip to content
Kubernetes tools · Chapter 16 of 20 Day 14: Your Own kubectl Plugins in Go

Day 14: Your Own kubectl Plugins in Go

Goal: Write a kubectl plugin in Go that understands kubectl’s flags, build it, call it through the plugin mechanism, test it with someone else’s permissions, and install it locally as a Krew package · Duration: approx. 90 min · Prerequisite: Day 13

Briefing

  • On Day 4 you saw: a kubectl plugin is any executable file in the PATH whose name starts with kubectl-. Your shell plugin kubectl-ungesund was one of these. Shell is enough for a lot. But as soon as you want to support flags like --context, -n or --as properly, work with types instead of text, or distribute one binary for many platforms, Go is the usual way.
  • Two libraries do the work:
    • client-go talks to the API server: types for all built-in resources, lists, watches.
    • cli-runtime provides genericclioptions.ConfigFlags: all of kubectl’s connection flags (--kubeconfig, --context, --namespace, --as …) with exactly the same behavior.
  • Krew installs plugins via a manifest (YAML) with a download address and checksum per platform. You can test a manifest locally before publishing it anywhere.
  • Today’s plugin answers a question from Day 9 without metrics-server and without Popeye: Which containers run without requests or limits? It exits with 1 if it finds any, so that it is useful in scripts and pipelines.
Building block Version
Go 1.27.4
k8s.io/client-go, k8s.io/cli-runtime, k8s.io/api v0.37.2 (matching Kubernetes 1.37)
github.com/spf13/cobra v1.10.2

Drill 1: Installing Go

Here, too, with a checksum. Go publishes it in machine-readable form:

ARCH=$(dpkg --print-architecture)
cd /tmp
curl -sLO https://go.dev/dl/go1.27.4.linux-${ARCH}.tar.gz
SUM=$(curl -s "https://go.dev/dl/?mode=json" | jq -r ".[0].files[] | select(.filename==\"go1.27.4.linux-${ARCH}.tar.gz\") | .sha256")
echo "$SUM  go1.27.4.linux-${ARCH}.tar.gz" | sha256sum -c
sudo rm -rf /usr/local/go
sudo tar -C /usr/local -xzf go1.27.4.linux-${ARCH}.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.bashrc
export PATH=$PATH:/usr/local/go/bin
go version

Expected:

go1.27.4.linux-amd64.tar.gz: OK
go version go1.27.4 linux/amd64

?mode=json only lists the current versions. If 1.27.4 is no longer the newest, .[0] returns a different version and the comparison fails. In that case, take the checksum from the download page.

Save your progress? Sign up for free

Drill 2: Writing the Plugin

The plugin is called kubectl-ohnelimits (withoutlimits):

mkdir -p ~/werkzeuge/tag14/kubectl-ohnelimits && cd ~/werkzeuge/tag14/kubectl-ohnelimits
go mod init example.com/kubectl-ohnelimits
cat > main.go <<'EOF'
package main

import (
    "context"
    "fmt"
    "os"
    "strings"
    "text/tabwriter"

    "github.com/spf13/cobra"
    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/cli-runtime/pkg/genericclioptions"
    "k8s.io/client-go/kubernetes"
)

func main() {
    flags := genericclioptions.NewConfigFlags(true)
    var alle bool

    cmd := &cobra.Command{
        Use:          "kubectl-ohnelimits",
        Short:        "Zeigt Container ohne CPU- oder Speicher-Requests und -Limits",
        SilenceUsage: true,
        RunE: func(cmd *cobra.Command, args []string) error {
            config, err := flags.ToRESTConfig()
            if err != nil {
                return err
            }
            client, err := kubernetes.NewForConfig(config)
            if err != nil {
                return err
            }
            ns, _, err := flags.ToRawKubeConfigLoader().Namespace()
            if err != nil {
                return err
            }
            if alle {
                ns = metav1.NamespaceAll
            }
            pods, err := client.CoreV1().Pods(ns).List(context.Background(), metav1.ListOptions{})
            if err != nil {
                return err
            }
            w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
            fmt.Fprintln(w, "NAMESPACE\tPOD\tCONTAINER\tFEHLT")
            treffer := 0
            for _, pod := range pods.Items {
                for _, c := range pod.Spec.Containers {
                    if fehlt := fehlend(c.Resources); fehlt != "" {
                        fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", pod.Namespace, pod.Name, c.Name, fehlt)
                        treffer++
                    }
                }
            }
            w.Flush()
            if treffer > 0 {
                os.Exit(1)
            }
            return nil
        },
    }
    cmd.Flags().BoolVarP(&alle, "all-namespaces", "A", false, "alle Namespaces")
    flags.AddFlags(cmd.Flags())
    if err := cmd.Execute(); err != nil {
        os.Exit(2)
    }
}

// fehlend nennt die Requests und Limits für CPU und Speicher, die nicht gesetzt sind.
func fehlend(r corev1.ResourceRequirements) string {
    var teile []string
    for _, name := range []corev1.ResourceName{corev1.ResourceCPU, corev1.ResourceMemory} {
        if _, ok := r.Requests[name]; !ok {
            teile = append(teile, "requests."+string(name))
        }
        if _, ok := r.Limits[name]; !ok {
            teile = append(teile, "limits."+string(name))
        }
    }
    return strings.Join(teile, ",")
}
EOF

Expected:

go: creating new go.mod: module example.com/kubectl-ohnelimits

What does it say?

  • The identifiers in the code are German: alle = all, treffer = hits, fehlend = missing, FEHLT = MISSING.
  • genericclioptions.NewConfigFlags(true) creates kubectl’s connection flags, and flags.AddFlags attaches them to the cobra command. Your plugin thus understands --context, -n, --as and all the others without you writing a single line for it.
  • flags.ToRESTConfig() builds the connection from them, just as kubectl would: kubeconfig, context, impersonation.
  • ToRawKubeConfigLoader().Namespace() returns the namespace from -n or, without -n, the one from the context. Without this line, your plugin would ignore the default namespace from Day 3 (kubens).
  • The rest is ordinary Go: list Pods, go through containers, collect missing values.
  • Exit codes: 0 = everything set, 1 = hits, 2 = error. This way, a script can tell “bad” from “broken”.

Dependencies in the version that matches the cluster, then build:

go get k8s.io/[email protected] k8s.io/[email protected] k8s.io/[email protected] k8s.io/[email protected] github.com/spf13/cobra
go mod tidy
go vet ./... && echo vet-ok
gofmt -l .
go build -o kubectl-ohnelimits .
ls -la kubectl-ohnelimits
grep -E "^go |k8s.io/(client-go|cli-runtime) |cobra " go.mod

Expected (excerpt; the first time, go get spends a few minutes downloading modules):

go: added k8s.io/apimachinery v0.37.2
go: added k8s.io/cli-runtime v0.37.2
go: added k8s.io/client-go v0.37.2
vet-ok
-rwxrwxr-x 1 ubuntu ubuntu 40291805 Nov 24 14:26 kubectl-ohnelimits
go 1.27.4
    github.com/spf13/cobra v1.10.2
    k8s.io/cli-runtime v0.37.2
    k8s.io/client-go v0.37.2

gofmt -l . prints nothing: the file is formatted correctly. 40 MB for a small program is normal with client-go; the library brings types for all resources. -ldflags="-s -w" removes debug information and saves just under a third here (28 MB).

Choose matching versions: client-go v0.37.x belongs to Kubernetes 1.37. Against a cluster one version older or newer, it usually works too; the rule is not to deviate by more than one minor version.

Save your progress? Sign up for free

Drill 3: Calling It Like kubectl

Put it into the PATH, and kubectl finds the plugin on its own:

install -m 755 kubectl-ohnelimits ~/.local/bin/
kubectl plugin list

Expected:

The following compatible plugins are available:

/home/ubuntu/.krew/bin/kubectl-access_matrix
/home/ubuntu/.krew/bin/kubectl-images
/home/ubuntu/.krew/bin/kubectl-krew
/home/ubuntu/.krew/bin/kubectl-neat
/home/ubuntu/.krew/bin/kubectl-resource_capacity
/home/ubuntu/.krew/bin/kubectl-tree
/home/ubuntu/.krew/bin/kubectl-view_secret
/home/ubuntu/.krew/bin/kubectl-who_can
/home/ubuntu/.local/bin/kubectl-ohnelimits
/home/ubuntu/.local/bin/kubectl-ungesund

The Krew plugins from Day 4, your shell plugin and the new one. Now the shop:

kubectl ohnelimits -n laden; echo "exit $?"

Expected (Pod names will differ):

NAMESPACE  POD                     CONTAINER  FEHLT
laden      api-7d5f77c79b-725kc    whoami     requests.cpu,limits.cpu,requests.memory,limits.memory
laden      api-7d5f77c79b-gjmtc    whoami     requests.cpu,limits.cpu,requests.memory,limits.memory
laden      cache-55b4555575-xkp72  redis      requests.cpu,limits.cpu,requests.memory,limits.memory
laden      netshoot                netshoot   requests.cpu,limits.cpu,requests.memory,limits.memory
laden      web-67649cfddb-6d48k    nginx      limits.cpu
laden      web-67649cfddb-fzrd6    nginx      limits.cpu
laden      web-67649cfddb-tggck    nginx      limits.cpu
laden      werkbank                werkbank   requests.cpu,limits.cpu,requests.memory,limits.memory
exit 1

The story of the last days in one table: kasse (checkout) is missing because it has had requests and limits since Day 9, lieferung (delivery) is missing because it was hardened on Day 10. web has everything except a CPU limit.

kubectl’s flags work because cli-runtime provides them. A different context and a different account:

kubectl ohnelimits --context kubedrill -n default; echo "exit $?"
kubectl ohnelimits -A --as=system:serviceaccount:laden:kasse; echo "exit $?"
kubectl ohnelimits -A --as=system:serviceaccount:headlamp:betrachter | wc -l; echo "exit ${PIPESTATUS[0]}"

Expected (the number of lines will differ):

NAMESPACE  POD  CONTAINER  FEHLT
exit 0
Error: pods is forbidden: User "system:serviceaccount:laden:kasse" cannot list resource "pods" in API group "" at the cluster scope
exit 2
39
exit 1

In the KubeDrill cluster, default is empty, hence exit 0. kasse may only read in its own namespace, hence exit 2 with the API server’s error message. betrachter (viewer) has view cluster-wide and sees everything. Your plugin does not check permissions itself; it passes the identity through, and the API server decides. Just like Headlamp on Day 6.

--help shows all flags, yours and kubectl’s:

kubectl ohnelimits --help | head -8

Expected:

Zeigt Container ohne CPU- oder Speicher-Requests und -Limits

Usage:
  kubectl-ohnelimits [flags]

Flags:
  -A, --all-namespaces                 alle Namespaces
      --as string                      Username to impersonate for the operation. User could be a regular user or a service account in a namespace.

Save your progress? Sign up for free

Drill 4: As a Krew Package

Krew installs from an archive that it downloads via a URL and verifies by SHA-256. For testing, you pass the archive directly; the URL in the manifest is then not used.

cd ~/werkzeuge/tag14
ARCH=$(dpkg --print-architecture)
rm ~/.local/bin/kubectl-ohnelimits
mkdir -p paket
cp kubectl-ohnelimits/kubectl-ohnelimits paket/
printf "Beispiel-Lizenz: MIT\n" > paket/LICENSE
tar czf ohnelimits-v0.1.0-linux-${ARCH}.tar.gz -C paket .
SHA=$(sha256sum ohnelimits-v0.1.0-linux-${ARCH}.tar.gz | cut -d" " -f1)
cat > ohnelimits.yaml <<EOF
apiVersion: krew.googlecontainertools.github.com/v1alpha2
kind: Plugin
metadata:
  name: ohnelimits
spec:
  version: v0.1.0
  homepage: https://example.com/kubectl-ohnelimits
  shortDescription: Zeigt Container ohne Requests und Limits
  description: |
    Listet alle Container eines Namespace, denen CPU- oder Speicher-Requests
    oder -Limits fehlen. Endet mit Exit-Code 1, wenn es Treffer gibt.
  platforms:
  - selector:
      matchLabels:
        os: linux
        arch: ${ARCH}
    uri: https://example.com/ohnelimits-v0.1.0-linux-${ARCH}.tar.gz
    sha256: $SHA
    bin: kubectl-ohnelimits
    files:
    - from: kubectl-ohnelimits
      to: .
    - from: LICENSE
      to: .
EOF
kubectl krew install --manifest=ohnelimits.yaml --archive=ohnelimits-v0.1.0-linux-${ARCH}.tar.gz
kubectl krew list
which kubectl-ohnelimits

Expected (excerpt):

 | Use this plugin:
 |  kubectl ohnelimits
 | Documentation:
 |  https://example.com/kubectl-ohnelimits
/
access-matrix
detached/ohnelimits
images
krew
neat
resource-capacity
tree
view-secret
who-can
/home/ubuntu/.krew/bin/kubectl-ohnelimits

detached/ohnelimits: Krew knows the plugin, but it does not come from any index. That is why kubectl krew upgrade leaves it alone. The EOF without quotation marks is intentional here: $SHA and ${ARCH} are supposed to be substituted into the file.

For a real release, you need one entry under platforms per platform and an archive at a real URL, usually a GitHub release. In Go, building for other platforms is a matter of an environment variable:

cd ~/werkzeuge/tag14/kubectl-ohnelimits
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o /tmp/kubectl-ohnelimits-arm64 .
file /tmp/kubectl-ohnelimits-arm64 | cut -c1-70

Expected:

/tmp/kubectl-ohnelimits-arm64: ELF 64-bit LSB executable, ARM aarch64,

In practice, GoReleaser takes care of building for all platforms, packaging and checksums, and krew-release-bot opens a pull request against the central Krew index after each release.

Save your progress? Sign up for free

Exercise: How Good Is the Plugin?

Call the plugin for lager (warehouse) and look at the result critically:

kubectl ohnelimits -n lager; echo "exit $?"

Expected (Pod names will differ):

NAMESPACE  POD                      CONTAINER  FEHLT
lager      inventur-29925480-g95bc  inventur   requests.cpu,limits.cpu,requests.memory,limits.memory
lager      inventur-29925490-fhgt4  inventur   requests.cpu,limits.cpu,requests.memory,limits.memory
lager      inventur-29925500-qllgk  inventur   requests.cpu,limits.cpu,requests.memory,limits.memory
lager      packer-5867bb6b7d-g8gdf  packer     requests.cpu,limits.cpu,requests.memory,limits.memory

What is wrong with it?

Solution

The three inventur Pods are finished (Completed); they are the retained runs of the CronJob. They no longer occupy any resources; for the question “who runs without limits?”, they are noise. The real problem is the CronJob’s template, and it shows up three times. A better plugin skips finished Pods. (An even better one checks Deployments, StatefulSets and CronJobs instead of Pods; that is the extension for later.)

Save your progress? Sign up for free

Challenge

Change the plugin so that it skips Pods in the phase Succeeded or Failed. Rebuild it, check it against lager, and finally uninstall the Krew version.

Solution

Three lines at the beginning of the Pod loop:

cd ~/werkzeuge/tag14/kubectl-ohnelimits
cp main.go main.go.orig
python3 - <<'EOF'
p = "main.go"
s = open(p).read()
s = s.replace("""           for _, pod := range pods.Items {
""", """            for _, pod := range pods.Items {
                if pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {
                    continue
                }
""")
open(p, "w").write(s)
EOF
diff -u main.go.orig main.go | tail -n +3
gofmt -l .
go build -o kubectl-ohnelimits . && ./kubectl-ohnelimits -n lager; echo "exit $?"
kubectl krew uninstall ohnelimits

Expected (the two diff header lines with timestamps cut off):

@@ -46,6 +46,9 @@
            fmt.Fprintln(w, "NAMESPACE\tPOD\tCONTAINER\tFEHLT")
            treffer := 0
            for _, pod := range pods.Items {
+               if pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {
+                   continue
+               }
                for _, c := range pod.Spec.Containers {
                    if fehlt := fehlend(c.Resources); fehlt != "" {
                        fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", pod.Namespace, pod.Name, c.Name, fehlt)
NAMESPACE  POD                      CONTAINER  FEHLT
lager      packer-5867bb6b7d-g8gdf  packer     requests.cpu,limits.cpu,requests.memory,limits.memory
exit 1
Uninstalled plugin: ohnelimits

Only the packer remains. The phase is in the Pod’s status, not in the spec; corev1 provides the constants for it, which rules out typos in strings. That is one of the reasons for Go instead of shell.

Save your progress? Sign up for free

Checkpoint

go version
ls ~/werkzeuge/tag14/kubectl-ohnelimits/
kubectl plugin list 2>/dev/null | grep -c ohnelimits

Expected:

go version go1.27.4 linux/amd64
go.mod  go.sum  kubectl-ohnelimits  main.go  main.go.orig
0

The plugin is built but no longer installed. (grep -c exits with exit code 1 at 0.)

Interview Note

  • How do kubectl plugins work? Any executable file kubectl-<name> in the PATH; kubectl calls it with the remaining arguments. Hyphens in the command become underscores in the file name (kubectl view-secret → kubectl-view_secret).
  • Why cli-runtime? So that --context, -n, --as and kubeconfig resolution work exactly as in kubectl. A homemade rebuild is never quite the same.
  • How do you distribute a plugin? An archive per platform, SHA-256, a Krew manifest; GoReleaser and krew-release-bot automate this.

Enterprise Note

  • Internal plugins belong in a custom Krew index (a Git repo with manifests, kubectl krew index add firma <url>). That way, everyone installs the same vetted versions.
  • A plugin runs with the full permissions of the kubeconfig. Internal plugins are therefore subject to the same rules as any software: review, signed releases, fixed versions.
  • For recurring checks like this one, a plugin is the entry point. If the rule should be enforced instead of just reported, it belongs in the cluster as a policy (Kyverno, Gatekeeper, ValidatingAdmissionPolicy).

Contents

More