Deserialize Kubernetes YAML file

0 votes

How can I deserialize a Kubernetes YAML file into an Go struct? I took a look into the kubectlcode, but somehow I get an error for every YAML file:

no kind "Deployment" is registered for version "apps/v1beta1"

This is an MWE:

package main
import (
    "fmt"
    "k8s.io/client-go/pkg/api"
)
var service = `
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: my-nginx
spec:
  replicas: 2
  template:
    metadata:
      labels:
        run: my-nginx
    spec:
      containers:
      - name: my-nginx
        image: nginx
        ports:
        - containerPort: 80
`
func main() {
    decode := api.Codecs.UniversalDecoder().Decode
    //decode := api.Codecs.UniversalDeserializer().Decode
    obj, _, err := decode([]byte(service), nil, nil)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", obj)
}

I am using client version 2.0.0. The glide.yaml looks like this:

package: test/stackoverflow
import:
- package: k8s.io/client-go
  version: ^2.0.0

Sep 4, 2018 in Kubernetes by Hannah
• 14,070 points
355 views

1 answer to this question.

0 votes

You need to import _ "k8s.io/client-go/pkg/apis/extensions/install" otherwise the schema is empty

The complete working example is:

$ go get -u github.com/golang/dep/cmd/dep
$ dep init
$ go run main.go

main.go:

package main
import (
    "fmt"
    "k8s.io/client-go/pkg/api"
    _ "k8s.io/client-go/pkg/api/install"
    _ "k8s.io/client-go/pkg/apis/extensions/install"
)
var deployment = `
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: my-nginx
spec:
replicas: 2
template:
  metadata:
    labels:
      run: my-nginx
  spec:
    containers:
    - name: my-nginx
      image: nginx
      ports:
      - containerPort: 80
`
func main() {
    // decode := api.Codecs.UniversalDecoder().Decode
    decode := api.Codecs.UniversalDeserializer().Decode
    obj, _, err := decode([]byte(deployment), nil, nil)
    if err != nil {
        fmt.Printf("%#v", err)
    }

    fmt.Printf("%#v\n", obj)
}
answered Sep 4, 2018 by Kalgi
• 40,460 points

Related Questions In Kubernetes

0 votes
3 answers

Using multiple commands in a kubernetes yaml file

Try something like this: containers: - name: ...READ MORE

answered Apr 23 in Kubernetes by lyza
4,895 views
0 votes
1 answer
+1 vote
4 answers
0 votes
1 answer

Set volume mount user group and file permissions in kubernetes

There's a setting in Pod Security Context ...READ MORE

answered Jan 16 in Kubernetes by ajs3033
• 7,280 points
1,889 views
0 votes
1 answer
0 votes
3 answers

Error while joining cluster with node

Hi Kalgi after following above steps it ...READ MORE

answered Jan 17 in Others by anonymous
2,172 views
0 votes
1 answer
0 votes
1 answer

Define pod yaml dynamically-jenkins pipeline Kubernetes

Try using jinja template engine and python ...READ MORE

answered Aug 28, 2018 in Kubernetes by Kalgi
• 40,460 points
158 views
0 votes
1 answer