Quantcast
Channel: scripting – Matthias Friedrich's Blog
Viewing all articles
Browse latest Browse all 16

Using Kubectl Printers and Plugins

$
0
0

Even though we have plenty of metrics and dashboards at work, I use the kubectl command line tool a lot for looking at resources and for troubleshooting. Because the defaults don’t always display the information that I need, I often use the kubectl printer mechanisms. In many cases, this is flexible enough so that I don’t have to write a custom script against the Kubernetes API.

You have probably used the “-o” switch with the “wide” or “json” printers, but there are more powerful ones available. For example, it’s possible to specify a list of columns:

kubectl get pods -o custom-columns='NAMESPACE:.metadata.namespace,POD:.metadata.name,CONTAINER:.spec.containers[*].name'

In this example, we have a three-column display that selects some fields from the underlying resource representation.

The go-template printer is even more flexible – you can use Go’s templaing language for formatting the output. The language takes some getting used to, but if you work a lot with Go-based tools (i.e. Prometheus’ Alertmanager), you will come across it sooner or later. In the following example, we loop over all results and display the resource kind and name, separated by a slash:

kubectl get pods -o go-template='{{ range .items }}{{ printf "%s/%s\n" .kind .metadata.name }}{{ end }}'

Instead of specifying columns or go templates on the command line, you can instead put them into a file and reference them using the “custom-columns-file” or “go-template-file” printers. My preferred approach is using kubectl plugins though.

A kubectl plugin doesn’t have to be registered in any way. It is just an executable that you put on your $PATH that follows a naming convention. You can list all available plugins like this:

$ kubectl plugin list
The following kubectl-compatible plugins are available:

/home/matthias/bin/kubectl-report-nodes
/home/matthias/bin/kubectl-report-pods
/home/matthias/bin/kubectl-report-resources
$

My plugins are just simple wrappers around existing kubectl commands. This one for example displays the CPU and memory requests and limits:

#! /bin/sh

COLUMNS="NAMESPACE:.metadata.namespace,POD:.metadata.name,CONTAINER:.spec.containers[*].name"
COLUMNS="$COLUMNS,REQ_CPU:.spec.containers[*].resources.requests.cpu,LIM_CPU:.spec.containers[*].resources.limits.cpu"
COLUMNS="$COLUMNS,REQ_MEM:.spec.containers[*].resources.requests.memory,LIM_CPU:.spec.containers[*].resources.limits.memory"

kubectl get pods -o custom-columns="$COLUMNS" "$@"

This is very similar to a shell alias – you can pass additional kubectl command line switches to select pods, for example by using the --namespace or --all-namespaces switches.

 


Viewing all articles
Browse latest Browse all 16

Latest Images

Trending Articles





Latest Images