diff --git a/api/krusty/kustomizer.go b/api/krusty/kustomizer.go index c5dda8a1b0..846b5f05f5 100644 --- a/api/krusty/kustomizer.go +++ b/api/krusty/kustomizer.go @@ -5,6 +5,7 @@ package krusty import ( "fmt" + "log" "path/filepath" "sigs.k8s.io/kustomize/api/internal/builtins" @@ -18,6 +19,7 @@ import ( "sigs.k8s.io/kustomize/api/types" "sigs.k8s.io/kustomize/kyaml/filesys" "sigs.k8s.io/kustomize/kyaml/openapi" + "sigs.k8s.io/kustomize/kyaml/resid" ) // Kustomizer performs kustomizations. @@ -89,12 +91,41 @@ func (b *Kustomizer) Run( if err != nil { return nil, err } - if b.options.DoLegacyResourceSort { - err = builtins.NewLegacyOrderTransformerPlugin().Transform(m) + // Sort order can be defined in two places: + // - (new) kustomization file + // - (old) CLI flag + // + // We want the kustomization file to take precedence over the CLI flag. + // Eventually, we may want to move away from having a CLI flag altogether: + // https://github.com/kubernetes-sigs/kustomize/issues/3947 + + // Case 1: Sort order set in kustomization file AND in CLI flag. + if b.options.SortModeSetExplicitly && kt.Kustomization().SortOptions != nil { + log.Println("Warning: Sorting order is set both in 'kustomization.yaml'" + + " ('sortOptions') and in a CLI flag ('--reorder'). Using the" + + " kustomization file over the CLI flag.") + } + + // Case 2: Sort order set in CLI flag only or not at all. + if b.options.DoLegacyResourceSort && kt.Kustomization().SortOptions == nil { + pl := &builtins.SortOrderTransformerPlugin{ + SortOptions: &types.SortOptions{ + Order: types.LegacySortOrder, + LegacySortOptions: &types.LegacySortOptions{ + OrderFirst: resid.OrderFirst, + OrderLast: resid.OrderLast, + }, + }, + } + err = pl.Transform(m) if err != nil { return nil, err } } + + // Case 3: Sort order set only in kustomization file. No need to do + // anything else here. + if b.options.AddManagedbyLabel { t := builtins.LabelTransformerPlugin{ Labels: map[string]string{