Using go-templates to get insights into a Kubernetes cluster
Sometimes you need information of your cluster state or properties and need to iterate through many resources like all deployments or so.
You can use different tools to get an insight.
But beside of hoping that the tool has the correct plugin or feature, there is also a more ’elegant’ way for this. Elegant means in this context: Customized to your needs.
Using go-templates to retrieve information
With go-templates you can use your kubectl output to show it in a way you like.
You can think of a filtering out properties on conditions or show them in a formatted way. Let’s check an example.
Imagine that you want to get the CPU limits of all your Deployments in the cluster.
You can take the output of this command:
kubectl get deployments -o yaml
… and maybe you could grep it or use awk. But this is not such an easy way and you’d loose your command if you don’t store into a bash file.
Example of a go-template
However you can use go-templates for exactly this use cases! You could filter the resources with or without a set CPU limit, group and show them.
For this you can store a go-template into a file with the ending .gotemplate. For this example store the following code as deployments-limits.gotemplate.
{{- range .items -}}
{{ $name := .metadata.name }}
{{- range .spec.template.spec.containers -}}
{{$name}} {{": "}} {{ .resources.limits.cpu }} {{"\n"}}
{{- end -}}
{{- end -}}
Passing the go-template to kubectl
Afterwards you pass it to your kubectl command like this:
kubectl get deployments --all-namespaces -o go-template-file=./deployments-limits.gotemplate
And now you should have a better and faster access to this properties.
I’ll not give an extensive introduction and tutorial for this and link some very good resources at the end of the article (especially this one).
Maybe you and your team can also create a repository with go-templates and use it to share and make your work easier?
Resources
Red Hat - Customizing OC Output with go-templates