Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion cmd/clusters-service/pkg/templates/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,14 @@ func InNamespace(ns string) RenderOptFunc {
// InjectLabels is a render option that updates the object metadata with the desired labels
func InjectLabels(labels map[string]string) RenderOptFunc {
return func(uns *unstructured.Unstructured) error {
uns.SetLabels(labels)
existing := uns.GetLabels()
if existing == nil {
existing = map[string]string{}
}
for k, v := range labels {
existing[k] = v
}
uns.SetLabels(existing)
return nil
}
}
Expand Down
40 changes: 40 additions & 0 deletions cmd/clusters-service/pkg/templates/render_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -587,3 +587,43 @@ func writeMultiDoc(t *testing.T, objs [][]byte) string {
}
return out.String()
}

func TestInjectLabels(t *testing.T) {
raw := []byte(`
apiVersion: cluster.x-k8s.io/v1alpha3
kind: Cluster
metadata:
name: testing
namespace: new-namespace
labels:
com.example/testing: tested
---
apiVersion: controlplane.cluster.x-k8s.io/v1alpha4
kind: KubeadmControlPlane
metadata:
name: testing-control-plane
labels:
com.example/other: tested
spec:
replicas: 5`)
updated, err := processUnstructured(raw, InjectLabels(map[string]string{
"new-label": "test-label",
}))
if err != nil {
t.Fatal(err)
}

want := `apiVersion: cluster.x-k8s.io/v1alpha3
kind: Cluster
metadata:
labels:
com.example/testing: tested
new-label: test-label
name: testing
namespace: new-namespace
`

if diff := cmp.Diff(want, string(updated)); diff != "" {
t.Fatalf("rendering with option failed:\n%s", diff)
}
}