diff --git a/pkg/project/project.go b/pkg/project/project.go index 4408970d..ad92bfad 100644 --- a/pkg/project/project.go +++ b/pkg/project/project.go @@ -188,7 +188,7 @@ func (f *project) dealVarsFiles(p *kkprojectv1.Play, basePlaybook string) error // combine map node if node.Content[0].Kind == yaml.MappingNode { // skip empty file - p.Vars = *variable.CombineMappingNode(node.Content[0], &p.Vars) + p.Vars = *variable.CombineMappingNode(&p.Vars, node.Content[0]) } } @@ -234,7 +234,7 @@ func (f *project) dealRoles(p kkprojectv1.Play, basePlaybook string) error { // combine map node if node.Content[0].Kind == yaml.MappingNode { // skip empty file - p.Roles[i].Vars = *variable.CombineMappingNode(node.Content[0], &p.Roles[i].Vars) + p.Roles[i].Vars = *variable.CombineMappingNode(&p.Roles[i].Vars, node.Content[0]) } } } diff --git a/pkg/variable/helper.go b/pkg/variable/helper.go index 8a56bfba..c5c33018 100644 --- a/pkg/variable/helper.go +++ b/pkg/variable/helper.go @@ -37,9 +37,9 @@ import ( ) // CombineMappingNode combines two yaml.Node objects representing mapping nodes. -// If b is nil or zero, returns a. -// If both a and b are mapping nodes, appends a's content to b. -// Returns b in all other cases. +// If a is nil or zero, returns b. +// If both a and b are mapping nodes, appends b's content to a. +// Returns a in all other cases. // // Parameters: // - a: First yaml.Node to combine @@ -48,15 +48,15 @@ import ( // Returns: // - Combined yaml.Node, with b taking precedence func CombineMappingNode(a, b *yaml.Node) *yaml.Node { - if b == nil || b.IsZero() { - return a + if a == nil || a.IsZero() { + return b } if a.Kind == yaml.MappingNode && b.Kind == yaml.MappingNode { - b.Content = append(b.Content, a.Content...) + a.Content = append(a.Content, b.Content...) } - return b + return a } // CombineVariables merge multiple variables into one variable. diff --git a/pkg/variable/yaml.go b/pkg/variable/yaml.go index 51713292..d4c4c870 100644 --- a/pkg/variable/yaml.go +++ b/pkg/variable/yaml.go @@ -176,6 +176,10 @@ func handleMap(current reflect.Value, key string, isLast bool, value any, rKey := reflect.ValueOf(key) existing := current.MapIndex(rKey) if isLast { + if existing.IsValid() && !isNil(existing) { + // skip + return current, nil + } if value == nil { current.SetMapIndex(rKey, reflect.Zero(reflect.TypeOf((*any)(nil)).Elem())) } else { @@ -229,6 +233,11 @@ func handleSlice(current reflect.Value, val string, isLast bool, value any, } // Handle setting the final value if isLast { + existingItem := current.Index(index) + if existingItem.IsValid() && !isNil(existingItem) { + // skip + return current, nil + } if value == nil { current.Index(index).Set(reflect.Zero(reflect.TypeOf((*any)(nil)).Elem())) } else {