K8s Go client convert objects to kubectl resource yamls

12/8/2018

I'm not sure if the title is the correct terminology..But I basically want to use the go-client and get kubectl compliant objects (yamls).

i.e a deployment resource would be:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.15.4
        ports:
        - containerPort: 80

I can get deployments from my k8s cluster via go-client like such:

    Deployments, err := clientset.AppsV1().Deployments().List(metav1.ListOptions{})
    //and then loop through each deployment:
    for _, deploy := range Deployments.Items{
     //deploy is type v1.Deployment
    }

if I was to marshal deployment and save to file, the struct is:

type Deployment struct {
    v1.TypeMeta    `json:",inline"`
    v1.ObjectMeta  `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
    Spec              DeploymentSpec    `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
    Status            DeploymentStatus  `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

obviously much different from what kubectl file is expecting.

(Though i can use go-client deployment.create(obj) to create that deployment).

If I wanted to create a kubectl valid resource, I could create a custom struct that adheres to that type, and then manually fill in the values.

Is there any way to do this automatically? or some helper functions that is there currently?

in essence i want to convert the v1.Deployment struct to the generic kubectl yaml resource.

-- nate
kubectl
kubernetes
kubernetes-go-client

1 Answer

12/8/2018

I think, you can simply Marshal the struct and get the yaml.

I used "github.com/ghodss/yaml" for struct marshaling. Please include this in import.

Deployments, err := clientset.AppsV1().Deployments().List(metav1.ListOptions{})
//and then loop through each deployment:
for _, deploy := range Deployments.Items{
    y, err := yaml.Marshal(deploy)
    if err != nil {
       panic(err)
    }
    fmt.Println("deployment print in yaml: ", string(y))
}

Hope it'll help.

-- Abu Hanifa
Source: StackOverflow