Why decode return result is empty

5/4/2019

I have below code, I would like to convert yaml to client go data structure and get the object name from it

package main

import (
  "fmt"

  "k8s.io/api/extensions/v1beta1"
  "k8s.io/client-go/kubernetes/scheme"
)

var yml = `
apiVersion: extensions/v1beta1
kind: Deployment
metadata: 
name: testnginx
replicas: 1
spec: 
template:
  metadata:
    labels:
      run: testnginx
  spec:
    containers:
    - image: nginx
      name: testnginx
      ports:
      - containerPort: 8080
`

func main() {
    decode := scheme.Codecs.UniversalDeserializer().Decode

    obj, _, err := decode([]byte(yml), nil, nil)
    if err != nil {
        fmt.Printf("%#v", err)
    }

  //fmt.Printf("%#v\n", obj)
  deployment := obj.(*v1beta1.Deployment)

    fmt.Printf("%#v\n", deployment.ObjectMeta.Name)
}

The return result supposes to be testnginx but it is empty

$ ./decode-k8s-exercise 
""

Not sure why. thanks

-- Honord
go
kubernetes

1 Answer

5/4/2019

The problem is in the yaml. The name field should be an attribute inside metadata but they are currently at the same level. If you space indent the name then it should work (the same applies to template later on). relicas should also be inside spec:

var yml = `
apiVersion: extensions/v1beta1
kind: Deployment
metadata: 
  name: testnginx
spec:
  replicas: 1
  template:
    metadata:
      labels:
        run: testnginx
    spec:
      containers:
      - image: nginx
        name: testnginx
        ports:
        - containerPort: 8080
`
-- Iain Duncan
Source: StackOverflow