Skip to content

Commit 8f892a0

Browse files
committed
fix: avoid nameclashes by considering the filepath
Signed-off-by: Nico Braun <rainbowstack@gmail.com>
1 parent d9ba9b2 commit 8f892a0

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

functions/go/gatekeeper/main.go

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,21 @@ import (
1919
"fmt"
2020
"io/ioutil"
2121
"os"
22+
"strings"
2223

2324
"github.com/GoogleContainerTools/kpt-functions-catalog/functions/go/gatekeeper/generated"
2425
"github.com/spf13/cobra"
2526
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2627
"sigs.k8s.io/kustomize/kyaml/fn/framework"
2728
"sigs.k8s.io/kustomize/kyaml/kio"
29+
"sigs.k8s.io/kustomize/kyaml/kio/kioutil"
2830
k8syaml "sigs.k8s.io/yaml"
2931
)
3032

3133
const (
32-
stdin = "/dev/stdin"
33-
stdout = "/dev/stdout"
34+
stdin = "/dev/stdin"
35+
stdout = "/dev/stdout"
36+
nullByte = "\x00"
3437
)
3538

3639
type GatekeeperProcessor struct {
@@ -59,6 +62,15 @@ func (gkp *GatekeeperProcessor) Process(resourceList *framework.ResourceList) er
5962
return err
6063
}
6164

65+
// add the filepath to the objects name in sanitized form. this is done
66+
// to get unique identifier in case the same resource is defined in
67+
// different files. Usually this happens when running the function
68+
// across packages
69+
if !isTemplate(un) && !isConstraint(un) {
70+
un.SetName(fmt.Sprintf("%s%s%s", un.GetName(), nullByte,
71+
strings.ReplaceAll(item.GetAnnotations()[kioutil.PathAnnotation], "/", nullByte)))
72+
}
73+
6274
objects = append(objects, un)
6375
}
6476

@@ -74,6 +86,19 @@ func (gkp *GatekeeperProcessor) Process(resourceList *framework.ResourceList) er
7486
},
7587
}
7688
}
89+
90+
// unwrap the null-byte filename hack again
91+
if result != nil {
92+
for i, item := range result.Items {
93+
parts := strings.SplitN(item.ResourceRef.Name, nullByte, 2)
94+
item.ResourceRef.Name = parts[0]
95+
if len(parts) == 2 {
96+
item.Field.Path = strings.ReplaceAll(parts[1], nullByte, "/")
97+
}
98+
result.Items[i] = item
99+
}
100+
}
101+
77102
resourceList.Result = result
78103
if resultContainsError(result) {
79104
return result
@@ -198,3 +223,13 @@ func resultContainsError(result *framework.Result) bool {
198223
}
199224
return false
200225
}
226+
227+
func isTemplate(u *unstructured.Unstructured) bool {
228+
gvk := u.GroupVersionKind()
229+
return gvk.Kind == "ConstraintTemplate"
230+
}
231+
232+
func isConstraint(u *unstructured.Unstructured) bool {
233+
gvk := u.GroupVersionKind()
234+
return gvk.Group == "constraints.gatekeeper.sh"
235+
}

0 commit comments

Comments
 (0)