Reading and writing k8s resource as YAML in golang

Harsh Jain
2 min readJun 1, 2020

--

I am writing this article as none other is available on this topic. The information is very scattered and often requires digging into code of k8s libraries. I am gonna be using Q/A style for this article.

How to read k8s resource from file? The intuitive and easy way is try to use interface{} and unmarshal YAML in it.

Last step will not working. obj is of type interface{} and conversion to complex type such as pod is not possible. Other than that, we haven’t defined function to convert interface{} to pod or other k8s resource.

Since, the above approach doesn’t works let’s look at how k8s deals with this. Refer client-go#issue-193.

Boom! This works as it is using the codec scheme defined for k8s resource.

But this only works for native k8s resource, what if you are working with CRDs? Their codec is not directly available so we have to manually add that to scheme.

Now that we are able to unmarshal k8s objects into proper types. How to write them back as YAML? Easy but wrong way is to directly marshal as YAML and write to a file.

This will save the k8s resource as YAML. But output will have runtime fields which k8s cluster uses to manage resources. Applying it to cluster, results in error. It will look like below having typemeta, objectmeta and selflink which are runtime properties.

Solution: nothing direct. So, let’s look at how kubectl prints the resource. Those aren’t declaration of runtime objects.

So, after digging in code, I found that k8s.io/kubectl uses k8s.io/cli-runtime which has the printers. Printers output resources in pre-apply format.

--

--