Tangible Bytes

A Web Developer’s Blog

Kubectrl Output Using Gotemplate

kubecrtl is the kubernetes swiss army knife - as well as being able to manipulate kubernetes it gives access to loads of data

But to make use of that data we need to format it - and one of the more powerful ways of doing this is using gotemplates

the help page just says

    Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].

which isn’t on it’s own terribly helpful

What I have found useful is first of all to get the data in YAML format as this is for me the easiest to visually interpret

Then I can see what variables are available, where there is an array and I want all values I’ll need to use the range keyword

For example to get all hosts for all ingresses for a cluster

FIrst I see what the data looks like

kubectl get ingresses --all-namespaces -o yaml 

I can see that there is an array of items, each item has a spec which has and array of rules and each rule has a host

In this case I don’t much care which item has which host - I just want the list of hosts, one per line

I need to iterate over the items and iterate over the spec.rules for each item

kubectl get ingresses --all-namespaces -o template='{{range .items}}{{range .spec.rules }}{{ .host }}