From acaa56455720355efb84fbcf3c3a416e5339e52a Mon Sep 17 00:00:00 2001 From: Matt Hook Date: Thu, 2 May 2024 14:28:07 +1200 Subject: [PATCH] fix(kube): correctly extract namespace from namespace manifest [EE-6555] (#11675) Co-authored-by: Prabhat Khera --- api/kubernetes/yaml.go | 23 +++++++++++++++++++---- api/kubernetes/yaml_test.go | 2 +- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/api/kubernetes/yaml.go b/api/kubernetes/yaml.go index 2e7e785fb..1bde934e9 100644 --- a/api/kubernetes/yaml.go +++ b/api/kubernetes/yaml.go @@ -125,12 +125,27 @@ func GetNamespace(manifestYaml []byte) (string, error) { return "", errors.Wrap(err, "failed to unmarshal yaml manifest when obtaining namespace") } - if _, ok := m["metadata"]; ok { - if namespace, ok := m["metadata"].(map[string]interface{})["namespace"]; ok { - return namespace.(string), nil - } + kind, ok := m["kind"].(string) + if !ok { + return "", errors.New("invalid kubernetes manifest, missing 'kind' field") } + if _, ok := m["metadata"]; ok { + var namespace interface{} + var ok bool + if strings.EqualFold(kind, "namespace") { + namespace, ok = m["metadata"].(map[string]interface{})["name"] + } else { + namespace, ok = m["metadata"].(map[string]interface{})["namespace"] + } + + if ok { + if v, ok := namespace.(string); ok { + return v, nil + } + return "", errors.New("invalid kubernetes manifest, 'namespace' field is not a string") + } + } return "", nil } diff --git a/api/kubernetes/yaml_test.go b/api/kubernetes/yaml_test.go index 48ca95373..80deef978 100644 --- a/api/kubernetes/yaml_test.go +++ b/api/kubernetes/yaml_test.go @@ -648,7 +648,7 @@ func Test_GetNamespace(t *testing.T) { input: `apiVersion: v1 kind: Namespace metadata: - namespace: test-namespace + name: test-namespace `, want: "test-namespace", },