// Package decoder provides common functionality for parsing raw data containing // K8s resources into structs that can then be applied via the K8s API. // // A common use case is reading embedded manifest bundles or manifest files from // disk (represented as byte[]) and applying them, similar to `kubectl apply` package decoder import ( "bytes" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" yamlutil "k8s.io/apimachinery/pkg/util/yaml" ) // DecodeYAML decodes data containing a multi-doc YAML file into an array // of K8s resources, which can be applied to the K8s API via client-go func DecodeYAML(d []byte) ([]*unstructured.Unstructured, error) { var manifests []*unstructured.Unstructured // setup decoder for our multidoc YAML file, so we can output individual decoder := yamlutil.NewYAMLToJSONDecoder(bytes.NewReader(d)) for { // read a document from our multidoc yaml file var rawObj runtime.RawExtension if err := decoder.Decode(&rawObj); err != nil { break } // decode using unstructured JSON scheme obj := &unstructured.Unstructured{} if rawObj.Size() == 0 { continue } if err := obj.UnmarshalJSON(rawObj.Raw); err != nil { return nil, err } // add usable unstructured.Unstructured object to our array of // manifests manifests = append(manifests, obj) } return manifests, nil }