我有以下代码,我想将yaml转换为客户端go数据结构并从中获取对象名称
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)
}
返回结果应该是testnginx,但为空
$ ./decode-k8s-exercise
""
不知道为什么。谢谢
答案 0 :(得分:4)
问题出在yaml中。 name
字段应该是metadata
内的一个属性,但是它们当前处于同一级别。如果您在空格上缩进该名称,则该名称应起作用(稍后对template
也是如此)。 relicas
也应放在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
`