support option for adding managed-by label

This commit is contained in:
Jingfang Liu
2020-06-04 11:37:56 -07:00
parent 952a2ebbf4
commit 4b117c4736
4 changed files with 66 additions and 1 deletions

View File

@@ -198,7 +198,7 @@ build-kustomize-api: $(builtinplugins)
.PHONY: test-unit-kustomize-api
test-unit-kustomize-api: build-kustomize-api
cd api; go test ./...
cd api; go test ./... -ldflags "-X sigs.k8s.io/kustomize/api/provenance.version=v444.333.222"
.PHONY: test-unit-kustomize-plugins
test-unit-kustomize-plugins:

View File

@@ -4,6 +4,8 @@
package krusty
import (
"fmt"
"sigs.k8s.io/kustomize/api/builtins"
"sigs.k8s.io/kustomize/api/filesys"
"sigs.k8s.io/kustomize/api/internal/k8sdeps/transformer"
@@ -12,11 +14,16 @@ import (
"sigs.k8s.io/kustomize/api/k8sdeps/kunstruct"
"sigs.k8s.io/kustomize/api/k8sdeps/validator"
fLdr "sigs.k8s.io/kustomize/api/loader"
"sigs.k8s.io/kustomize/api/provenance"
"sigs.k8s.io/kustomize/api/resmap"
"sigs.k8s.io/kustomize/api/resource"
"sigs.k8s.io/kustomize/api/types"
)
const (
managedbyLabelKey = "app.kubernetes.io/managed-by"
)
// Kustomizer performs kustomizations. It's meant to behave
// similarly to the kustomize CLI, and can be used instead of
// performing an exec to a kustomize CLI subprocess.
@@ -78,5 +85,15 @@ func (b *Kustomizer) Run(path string) (resmap.ResMap, error) {
if b.options.DoLegacyResourceSort {
builtins.NewLegacyOrderTransformerPlugin().Transform(m)
}
if b.options.AddManagedbyLabel {
t := builtins.LabelTransformerPlugin{
Labels: map[string]string{managedbyLabelKey: fmt.Sprintf("kustomize-%s", provenance.GetProvenance().Version)},
FieldSpecs: []types.FieldSpec{{
Path: "metadata/labels",
CreateIfNotPresent: true,
}},
}
t.Transform(m)
}
return m, nil
}

View File

@@ -0,0 +1,43 @@
// Copyright 2020 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package krusty_test
import (
"testing"
kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
)
func TestAddManagedbyLabel(t *testing.T) {
th := kusttest_test.MakeHarness(t)
th.WriteF("/app/service.yaml", `
apiVersion: v1
kind: Service
metadata:
name: myService
spec:
ports:
- port: 7002
`)
th.WriteK("/app", `
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- service.yaml
`)
options := th.MakeDefaultOptions()
options.AddManagedbyLabel = true
m := th.Run("/app", options)
th.AssertActualEqualsExpected(m, `
apiVersion: v1
kind: Service
metadata:
labels:
app.kubernetes.io/managed-by: kustomize-v444.333.222
name: myService
spec:
ports:
- port: 7002
`)
}

View File

@@ -18,6 +18,11 @@ type Options struct {
// order as specified by the kustomization file(s).
DoLegacyResourceSort bool
// When true, a label
// app.kubernetes.io/managed-by: kustomize-<version>
// is added to all the resources in the build out.
AddManagedbyLabel bool
// Restrictions on what can be loaded from the file system.
// See type definition.
LoadRestrictions types.LoadRestrictions