如何打开YAML文件,更改某些内容并将其保存回Go中?

I need to change some values in YAML file from Go code. In my case, I need to change values.yaml file from Helm chart. Since that file can change, I do not structure of the whole file in advance (for example developers added new YAML sections in it in various projects). I just know how section that I want to change looks like.

I understand there is YAML library in Go (https://github.com/go-yaml/yaml). It will not do the job, because it assumes I know in advance structure of the file that I need to change. All examples are something like: 1. create struct 2. unmarshal YAML to struct 3. change 4. marshal and save back

It is not working for me since I do not know exact format of file, hence I cannot do step 1, create struct.

This is part of YAML file I am trying to change:

image:
  repository: nginx
  tag: stable
  pullPolicy: IfNotPresent

I understand this can be done with help of interface{}, but I do not understand how. Assuming that I understand struct, marshal/unmarshal YAML files, can someone provide code that will: 1. Load YAML file that has at least 20 entries in it and is of unknown structure 2. Change only 1 entry (in my case I want to change tag number for image section) 3. Save it back.

Thanks a lot !

Something like this should work:

data, err := ioutil.ReadFile(file)
var v interface{}
err = yaml.Unmarshal(data, &v)
img, ok := v.["image"].(map[interface{}]interface{})
if ok {
   img["tag"] = "somevalue"
}

The yaml library I use unmarshals into map[interface{}]interface{}. You need to add the necessary error checking, type assertions, etc.

When done, you can yaml.Marshal(v) and write the result.