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

标签 azure go kubernetes yaml

我使用以下代码来获取 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/

相关文章:

ios - 将 Xamarin iOS 提交到 Apple AppStoreConnect TestFlight 后获取 'ITMS-90338: Non-public API usage' 和 'ITMS-90809: Deprecated API Usage'

azure - ARM 中存储队列的专用端点

node.js - Azure 服务应用程序中未定义环境变量

postgresql - Google Go 数据存储接口(interface)

go - 当(HTTP)通过将 io.Reader 从 os.Open 传递到 http.Post 来发布本地文件时,Content-Length 为零

go - Rethinkdb,去 : Ensure Table and Index in one ReQL statement

asp.net-mvc - 无法在 MVC 应用程序中配置 Redis 缓存

azure - 在 kubernetes 集群上部署 Cassandra

kubernetes - 我可以在 GKE 上使用本地 SSD 在 Pod 内进行快速的临时存储吗?

azure - Kubernetes UDP 负载均衡服务