dpsu84620 2017-11-04 23:48
浏览 1041

client-go:将kubernetes json文件解析为k8s结构

i would like to parse kubernetes manifest file (json/yaml) and be able to convert them to k8s structures (to later on manipulate them)

I know there is the NewYAMLOrJSONDecoder().Decode() function (https://github.com/kubernetes/apimachinery/blob/master/pkg/util/yaml/decoder.go) to read a json/yaml file, but the next step is: how to convert them to k8s structure/type?

i.e. if I read a yaml file with a Namespace object, how to convert it to a core/v1/namespace interface for example

Regards,

  • 写回答

2条回答 默认 最新

  • donglu8334 2017-11-05 15:53
    关注

    This question is very similar to How to deserialize Kubernetes YAML file, but this question is a bit outdated, since the package names changed.

    Also it doesn't directly use the go client, which means there might be another solution to this.

    Here is a example:

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

    Notes

    • the .../install packages are important, since they define which types can get decoded
    • it's able to decode JSON, YAML and probably also all other supported file types
    • not sure where the difference between UniversalDecoder and UniversalDeserializer is
    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备