mirror of
https://github.com/kyverno/kyverno.git
synced 2025-03-06 07:57:07 +00:00
* fix: load policy and add tests Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> * fix callers Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com>
44 lines
1.2 KiB
Go
44 lines
1.2 KiB
Go
package yaml
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
|
"k8s.io/apimachinery/pkg/util/yaml"
|
|
"sigs.k8s.io/controller-runtime/pkg/log"
|
|
)
|
|
|
|
// GetPolicy extracts policies from YAML bytes
|
|
func GetPolicy(bytes []byte) (policies []kyvernov1.PolicyInterface, err error) {
|
|
documents, err := SplitDocuments(bytes)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, thisPolicyBytes := range documents {
|
|
policyBytes, err := yaml.ToJSON(thisPolicyBytes)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to convert to JSON: %v", err)
|
|
}
|
|
policy := &kyvernov1.ClusterPolicy{}
|
|
if err := json.Unmarshal(policyBytes, policy); err != nil {
|
|
return nil, fmt.Errorf("failed to decode policy: %v", err)
|
|
}
|
|
if policy.TypeMeta.Kind == "" {
|
|
log.Log.V(3).Info("skipping file as policy.TypeMeta.Kind not found")
|
|
continue
|
|
}
|
|
if policy.TypeMeta.Kind != "ClusterPolicy" && policy.TypeMeta.Kind != "Policy" {
|
|
return nil, fmt.Errorf("resource %s/%s is not a Policy or a ClusterPolicy", policy.Kind, policy.Name)
|
|
}
|
|
if policy.Kind == "Policy" {
|
|
if policy.Namespace == "" {
|
|
policy.Namespace = "default"
|
|
}
|
|
} else {
|
|
policy.Namespace = ""
|
|
}
|
|
policies = append(policies, policy)
|
|
}
|
|
return policies, nil
|
|
}
|