-
-
Save kevincantu/4d82a7bc24fe5ff7422138ff9b5e9cdd to your computer and use it in GitHub Desktop.
Deserialize Kubernetes objects in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
appsv1 "k8s.io/api/apps/v1" | |
corev1 "k8s.io/api/core/v1" | |
"k8s.io/apimachinery/pkg/runtime" | |
"k8s.io/apimachinery/pkg/runtime/serializer" | |
) | |
func main() { | |
// https://godoc.org/k8s.io/apimachinery/pkg/runtime#Scheme | |
scheme := runtime.NewScheme() | |
// https://godoc.org/k8s.io/apimachinery/pkg/runtime/serializer#CodecFactory | |
codecFactory := serializer.NewCodecFactory(scheme) | |
// https://godoc.org/k8s.io/apimachinery/pkg/runtime#Decoder | |
deserializer := codecFactory.UniversalDeserializer() | |
namespaceYAML, err := ioutil.ReadFile("namespace.yaml") | |
if err != nil { | |
panic(err) | |
} | |
namespaceObject, _, err := deserializer.Decode(namespaceYAML, nil, &corev1.Namespace{}) | |
if err != nil { | |
panic(err) | |
} | |
namespace := namespaceObject.(*corev1.Namespace) | |
fmt.Println("==== namespace.yaml ====") | |
fmt.Printf("Name: %s\n", namespace.ObjectMeta.GetName()) | |
fmt.Println() | |
deploymentYAML, err := ioutil.ReadFile("deployment.yaml") | |
if err != nil { | |
panic(err) | |
} | |
deploymentObject, _, err := deserializer.Decode(deploymentYAML, nil, &appsv1.Deployment{}) | |
if err != nil { | |
panic(err) | |
} | |
deployment := deploymentObject.(*appsv1.Deployment) | |
fmt.Println("==== deployment.yaml ====") | |
fmt.Printf("Namespace: %s\n", deployment.ObjectMeta.GetNamespace()) | |
fmt.Printf("Resources: %+v\n", deployment.Spec.Template.Spec.Containers[0].Resources.Limits["cpu"]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment