golang两种解析k8s资源yaml文件的方式(带---分隔符))

万州客 · · 1859 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

网上找了几种方案,糅合在一起,再自己作一下---分隔符的split切分,就可以随意解析出我们需要的yaml里的资源定义啦。引处,我感兴趣的是Deployment~

需要关注的点:gopkg.in/yaml.v3这种方式自定义能力强,在只需要自己感兴趣的资源时,非常有用。yaml_k8s这种方式比较标准,也不用自定义结构,但和k8s的API版本相关,非严谨或是版本统一的情况,推荐使用。

代码送上:

package main

import (
    "encoding/json"
    "fmt"
    "os"
    "strings"

    apps_v1 "k8s.io/api/apps/v1"
    yaml_k8s "k8s.io/apimachinery/pkg/util/yaml"

    yaml_v3 "gopkg.in/yaml.v3"
)

func main() {
    type Deployment struct {
        Kind     string `yaml:"kind"`
        Metadata struct {
            Name      string `yaml:"name"`
            Namespace string `yaml:"namespace"`
        }
    }
    data := `
---
apiVersion: v1
kind: Service
metadata:
  name: hello-spring-service-nodeport
spec:
  ports:
    - port: 8899
      targetPort: 8899
      protocol: TCP
  type: NodePort
  selector:
    name: hello-spring
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: hello-spring
  namespace: ck
spec:
  replicas: 1
  selector:
    matchLabels:
      name: hello-spring
  template:
    metadata:
      labels:
        name: hello-spring
    spec:
      containers:
        - name: hello-spring
          image: 192.168.1.111:8089/tmp/hello-spring:v0.1
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 8899
---
apiVersion: v1
kind: Service
metadata:
  name: hello-spring-service-nodeport
spec:
  ports:
    - port: 8899
      targetPort: 8899
      protocol: TCP
  type: NodePort
  selector:
    name: hello-spring
`
    dataArr := strings.Split(data, "---")
    for _, value := range dataArr {
        var deployment Deployment
        err := yaml_v3.Unmarshal([]byte(value), &deployment)
        if err != nil {
            fmt.Printf("Failed to unmarshall: %v", err)
            os.Exit(1)
        }

        if deployment.Kind == "Deployment" {
            fmt.Printf("Marshalled deployment=%+v\n", deployment)
            fmt.Printf("Marshalled deployment=%+v\n", deployment.Kind)
            fmt.Printf("Marshalled deployment=%+v\n", deployment.Metadata.Name)
            fmt.Printf("Marshalled deployment=%+v\n", deployment.Metadata.Namespace)
            fmt.Printf("===========================================\n")
        }

        // YAML转JSON
        deployJson, err := yaml_k8s.ToJSON([]byte(value))
        if err != nil {
            fmt.Println(err)
        }

        // JSON转struct
        var deploymentK8s apps_v1.Deployment
        err = json.Unmarshal(deployJson, &deploymentK8s)
        if err != nil {
            fmt.Println(err)
        }
        if deploymentK8s.Kind == "Deployment" {
            fmt.Printf("Marshalled deployment=%+v\n", deploymentK8s)
            fmt.Printf("Marshalled deployment=%+v\n", deploymentK8s.Kind)
            fmt.Printf("Marshalled deployment=%+v\n", deploymentK8s.Name)
            fmt.Printf("Marshalled deployment=%+v\n", deploymentK8s.Namespace)
            fmt.Printf("===========================================\n")
        }

    }

}

过程如图:


LiteIDE编辑器

结果如下:

D:/test/wincmd/wincmd.exe  [D:/test/wincmd]
Marshalled deployment={Kind:Deployment Metadata:{Name:hello-spring Namespace:ck}}
Marshalled deployment=Deployment
Marshalled deployment=hello-spring
Marshalled deployment=ck
===========================================
Marshalled deployment={TypeMeta:{Kind:Deployment APIVersion:apps/v1} ObjectMeta:{Name:hello-spring GenerateName: Namespace:ck SelfLink: UID: ResourceVersion: Generation:0 CreationTimestamp:0001-01-01 00:00:00 +0000 UTC DeletionTimestamp:<nil> DeletionGracePeriodSeconds:<nil> Labels:map[] Annotations:map[] OwnerReferences:[] Finalizers:[] ClusterName: ManagedFields:[]} Spec:{Replicas:0xc00021744c Selector:&LabelSelector{MatchLabels:map[string]string{name: hello-spring,},MatchExpressions:[]LabelSelectorRequirement{},} Template:{ObjectMeta:{Name: GenerateName: Namespace: SelfLink: UID: ResourceVersion: Generation:0 CreationTimestamp:0001-01-01 00:00:00 +0000 UTC DeletionTimestamp:<nil> DeletionGracePeriodSeconds:<nil> Labels:map[name:hello-spring] Annotations:map[] OwnerReferences:[] Finalizers:[] ClusterName: ManagedFields:[]} Spec:{Volumes:[] InitContainers:[] Containers:[{Name:hello-spring Image:192.168.1.111:8089/tmp/hello-spring:v0.1 Command:[] Args:[] WorkingDir: Ports:[{Name: HostPort:0 ContainerPort:8899 Protocol: HostIP:}] EnvFrom:[] Env:[] Resources:{Limits:map[] Requests:map[]} VolumeMounts:[] VolumeDevices:[] LivenessProbe:nil ReadinessProbe:nil StartupProbe:nil Lifecycle:nil TerminationMessagePath: TerminationMessagePolicy: ImagePullPolicy:IfNotPresent SecurityContext:nil Stdin:false StdinOnce:false TTY:false}] EphemeralContainers:[] RestartPolicy: TerminationGracePeriodSeconds:<nil> ActiveDeadlineSeconds:<nil> DNSPolicy: NodeSelector:map[] ServiceAccountName: DeprecatedServiceAccount: AutomountServiceAccountToken:<nil> NodeName: HostNetwork:false HostPID:false HostIPC:false ShareProcessNamespace:<nil> SecurityContext:nil ImagePullSecrets:[] Hostname: Subdomain: Affinity:nil SchedulerName: Tolerations:[] HostAliases:[] PriorityClassName: Priority:<nil> DNSConfig:nil ReadinessGates:[] RuntimeClassName:<nil> EnableServiceLinks:<nil> PreemptionPolicy:<nil> Overhead:map[] TopologySpreadConstraints:[]}} Strategy:{Type: RollingUpdate:nil} MinReadySeconds:0 RevisionHistoryLimit:<nil> Paused:false ProgressDeadlineSeconds:<nil>} Status:{ObservedGeneration:0 Replicas:0 UpdatedReplicas:0 ReadyReplicas:0 AvailableReplicas:0 UnavailableReplicas:0 Conditions:[] CollisionCount:<nil>}}
Marshalled deployment=Deployment
Marshalled deployment=hello-spring
Marshalled deployment=ck
===========================================
成功: 进程退出代码 0.

参考URL:

  • 关了浏览器就忘了·~~~~.

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:万州客

查看原文:golang两种解析k8s资源yaml文件的方式(带---分隔符))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1859 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传