Custom Kubectl Output with Go-template

Zhimin Wen
3 min readSep 20, 2023
Image by René Vlak from Pixabay

I have a local registry for the OpenShift Cluster. We just did some migration and retired the old registry. However some images were missed out leading to some of the Pods not running properly. The issue was not so obvious as the default image pull policy for most of the pods was set as IfNotPresent. When the pod is being refreshed the problem starts to pop out.

As it is a big namespace, we need some automation to detect if the image presents in the new registry. If not, then populate it into the new registry from the old one.

Get all the images with go-template

We could use some shell techniques to list all the images, but soon its getting hairy. Let's use the go-template to customize the output of kubectl.

Again I am using magefiles to automate these. The function for getting all the images in the namespace is listed as below,

func (CheckImage) T01_list_images() {
cmd := `oc -n ibm-common-services get pod -o go-template='
{{- printf "pod containerType image" }}
{{- range $pod := .items }}
{{- range .spec.containers }}
{{ $ }} container {{ .image }}
{{- end }}

{{- range .spec.initContainers }}
{{ $ }} initContainer {{ .image }}
{{- end }}
{{- end }}
' | tee images.txt

We have the go-template as a multi lines template wrapped in a pair of single quote. First use the printf function to print a title line. Then for each pod item, loop through the .containers and the .initContainers to print out its image name. For each line of the image, we print the pod name and the type of the container before the image.

A sample output for the first few lines are listed as below,

pod containerType image
auth-idp-7945455cb9-pmvnv container
auth-idp-7945455cb9-pmvnv container
auth-idp-7945455cb9-pmvnv container
auth-idp-7945455cb9-pmvnv container…