Skip to content

Instantly share code, notes, and snippets.

@lawrencejones
Created November 16, 2019 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lawrencejones/cfbd66c47354ac5badcd2c100b46a5e6 to your computer and use it in GitHub Desktop.
Save lawrencejones/cfbd66c47354ac5badcd2c100b46a5e6 to your computer and use it in GitHub Desktop.
Example of validated manifest
package manifest
import (
"fmt"
"github.com/stretchr/objx"
)
// Manifest describes a single Kubernetes manifest. Manifests should only ever be
// constructed using the NewManifest method, to ensure the resource is well-formed.
type Manifest struct {
manifest
}
func NewManifest(obj map[string]interface{}) (Manifest, error) {
if isValid(obj) {
return Manifest{manifest(obj)}, nil
}
return Manifest{}, fmt.Errorf("could not construct Manifest from invalid kubernetes object")
}
// isValid attempts to infer whether the given object is a valid kubernetes resource by
// verifying the presence of apiVersion, kind and metadata.name. These three fields are
// required for kubernetes to accept any resource.
//
// In future, it might be a good idea to allow users to opt their object out of being
// interpreted as a kubernetes resource, perhaps with a field like `exclude: true`. For
// now, any object within the jsonnet output that quacks like a kubernetes resource will
// be provided to the kubernetes API.
func isValid(obj objx.Map) bool {
return obj.Get("apiVersion").IsStr() && obj.Get("apiVersion").Str() != "" &&
obj.Get("kind").IsStr() && obj.Get("kind").Str() != "" &&
obj.Get("metadata.name").IsStr() && obj.Get("metadata.name").Str() != ""
}
type manifest map[string]interface{}
func (m manifest) APIVersion() string {
return m["apiVersion"].(string)
}
func (m manifest) Kind() string {
return m["kind"].(string)
}
func (m manifest) Name() string {
return m["metadata"].(map[string]interface{})["name"].(string)
}
func (m manifest) Namespace() string {
return m["metadata"].(map[string]interface{})["namespace"].(string)
}
func (m manifest) KindName() string {
return fmt.Sprintf("%s/%s", m.Kind(), m.Name())
}
func (m manifest) GroupVersionKindName() string {
return fmt.Sprintf("%s/%s/%s", m.APIVersion(), m.Kind(), m.Name())
}
func (m manifest) Get(key string) *objx.Value {
return m.Objx().Get(key)
}
func (m manifest) Set(key string, value interface{}) manifest {
return manifest(m.Objx().Set(key, value))
}
func (m manifest) Objx() objx.Map {
return objx.New((map[string]interface{})(m))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment