【问题标题】:Parse yaml config map data from k8s从 k8s 解析 yaml 配置映射数据
【发布时间】:2021-01-10 14:55:47
【问题描述】:

我正在使用以下代码来获取 k8s config map 数据。

这段代码可以正常工作,但是我不确定解组,是否有点冗长,是否有可靠的方法来实现这一点?

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

【问题讨论】:

  • "cleaner" 总是一种观点,这会导致不好的问题。你能把你的要求缩小一点吗?这段代码的违规部分到底是什么?
  • @UlrichEckhardt - 我考虑了更健壮的代码,因为我需要在 prod 中运行它,我得到了一个我现在正在检查的答案

标签: azure go kubernetes yaml


【解决方案1】:

一些修改建议:

// 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")
  }

}


【讨论】:

  • 谢谢!,您说“否则可能会发生错误”您指的是哪种错误?
  • @PeterSO 添加了一个示例案例。 map[string]string 将在嵌套的 yaml 文件中失败。
  • 我现在正在尝试,当我尝试执行 appVersion := strings.ReplaceAll(cmData[“rzr”], ".", "-") 时出现错误,您知道吗?
  • 错误是:Cannot use 'cmData["rzr"]' (type interface{}) as type string
  • @PeterSO 你想得到哪个apiVersion?您的 configMap 在数据字段中有一个键 rzr 吗?将 configMap 的 yaml 添加到问题正文中。
猜你喜欢
  • 2017-02-16
  • 2012-02-16
  • 2020-10-22
  • 2020-02-16
  • 2017-04-08
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
  • 1970-01-01
相关资源
最近更新 更多