PeterSO
PeterSO

Reputation: 25

Parse yaml config map data from k8s

I'm using the following code to get k8s config map data.

This code is working however I’m not sure regarding the unmarshal, is it a bit verbose, is there a robust way to achieve this?

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”], ".", "-")

This is the config map vs-manifest

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

Upvotes: 2

Views: 1900

Answers (1)

Kamol Hasan
Kamol Hasan

Reputation: 13486

Some modification suggestions:

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

}


Upvotes: 1

Related Questions