gpt4 book ai didi

azure - 从 k8s 解析 yaml 配置映射数据

转载 作者:行者123 更新时间:2023-12-03 10:09:15 24 4
gpt4 key购买 nike

我使用以下代码来获取 k8s 配置映射数据。

这段代码正在工作,但是我不确定关于解码,它是否有点冗长,是否有一个可靠的方法来实现这一点?

cm, e := c.Kubernetes.CoreV1().ConfigMaps(“ns1”).Get(“vs-manifest”, metav1.GetOptions{})
if e != nil {
return errors.New(“error “occurred”)

}

//here I want to get the data
var cmData map[string]string
e = yaml.Unmarshal([]byte(cm.Data["cm1.yaml"]), &cmData)
if err != nil{
return errors.New(“error “occurred”)
}

//here i need to read rzr field
appVersion := strings.ReplaceAll(cmData[“rzr”], ".", "-")

这是配置映射vs-manifest

apiVersion: v1
kind: ConfigMap
metadata:
name: vs-manifest
namespace: ns1
data:
cm1.yaml: |
version: 1.5
repo: milestones
rzr: 1.0005.044

最佳答案

一些修改建议:

// Once you have the configMap, check whether cm1.yaml file exist or not?

var cmFile string
if value, ok:= cm.Data["cm1.yaml"]; ok {
cmFile = value
}

// while unmarshal-ing yaml files, use map[string]interface
// otherwise error may occur.
// Case:
//| a:
//| b: value
//| c:
//| d: value2

cmData := make(map[string]interface{})
err := yaml.Unmarshal([]byte(cmFile), cmData)
if err != nil {
return errors.New("error occurred")
}

var apiVersion string
// Check whether the "rzr" exist or not
if value, ok := cmData["rzr"]; ok {
// convert the value from interface to string
// using type assertion.
stringValue, valid := value.(string)
// if successfully converted to string
if valid {
apiVersion = strings.ReplaceAll(stringValue, ".", "-")
} else {
return errors.New("failed to convert")
}

}


关于azure - 从 k8s 解析 yaml 配置映射数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65654611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com