<p>I'm looking into writing a tool that generates Kubernetes definitions programatically for our project.</p>

<p>I've found that the API types in Kubernetes can be found in <code>k8s.io/kubernetes/pkg/api</code>. I would like to output YAML based on these types.</p>

<p>Given an object like this:</p>

<pre><code>ns := &amp;api.Namespace{
    ObjectMeta: api.ObjectMeta{
        Name: "test",
    },
}
</code></pre>

<p>What's the best way to generate the YAML output expected by <code>kubectl create</code>?</p>

<p>Found it, for future reference, here's what you might want to do:</p>

<pre><code>package main

import (
    "os"

    "k8s.io/kubernetes/pkg/api/unversioned"
    "k8s.io/kubernetes/pkg/api/v1"
    "k8s.io/kubernetes/pkg/runtime/serializer/json"
)

func main() {
    ns := &amp;v1.Namespace{
        TypeMeta: unversioned.TypeMeta{
            Kind:       "Namespace",
            APIVersion: "v1",
        },

        ObjectMeta: v1.ObjectMeta{
            Name: "test",
        },
    }

    e := json.NewYAMLSerializer(json.DefaultMetaFactory, nil, nil)

    err := e.EncodeToStream(ns, os.Stdout)
    if err != nil {
        panic(err)
    }
}
</code></pre>

<p>This might not be the best practice (better suggestions welcome), but it does the job.</p>
