diff --git a/pkg/utils/yaml_utils/yaml_utils.go b/pkg/utils/yaml_utils/yaml_utils.go index 2a490f903..cff63871e 100644 --- a/pkg/utils/yaml_utils/yaml_utils.go +++ b/pkg/utils/yaml_utils/yaml_utils.go @@ -15,6 +15,13 @@ func UpdateYamlValue(yamlBytes []byte, path []string, value string) ([]byte, err return nil, fmt.Errorf("failed to parse YAML: %w", err) } + // Empty document: need to create the top-level map ourselves + if len(node.Content) == 0 { + node.Content = append(node.Content, &yaml.Node{ + Kind: yaml.MappingNode, + }) + } + body := node.Content[0] updateYamlNode(body, path, value) diff --git a/pkg/utils/yaml_utils/yaml_utils_test.go b/pkg/utils/yaml_utils/yaml_utils_test.go index ff39cbe3f..fa861b1b8 100644 --- a/pkg/utils/yaml_utils/yaml_utils_test.go +++ b/pkg/utils/yaml_utils/yaml_utils_test.go @@ -31,6 +31,14 @@ func TestUpdateYamlValue(t *testing.T) { expectedOut: "foo: bar\nfoo2: baz\n", expectedErr: "", }, + { + name: "add new key and value when document was empty", + in: "", + path: []string{"foo"}, + value: "bar", + expectedOut: "foo: bar\n", + expectedErr: "", + }, { name: "preserve inline comment", in: "foo: bar # my comment\n",