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 }}
{{ $pod.metadata.name }} container {{ .image }}
{{- end }}

{{- range .spec.initContainers }}
{{ $pod.metadata.name }} initContainer {{ .image }}
{{- end }}
{{- end }}
' | tee images.txt
`
bastion().Execute(cmd)
}

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 icr.io/cpopen/cpfs/audit-syslog-service@sha256:44db7b7635017de18531a56ab0733f5ac0e41ea3a1f2e1c946dcfc7151c34a1b
auth-idp-7945455cb9-pmvnv container icr.io/cpopen/cpfs/icp-platform-auth@sha256:70fb04976f6ca8ca4e3c968f087e3d4ebce73adc7fae14ab39a7c95341e74966
auth-idp-7945455cb9-pmvnv container icr.io/cpopen/cpfs/icp-identity-provider@sha256:e1f766ec47fc5a0be0fd0072cfc913eb4238bf6aa44ea9482578fbf246aa0ec5
auth-idp-7945455cb9-pmvnv container…

--

--