Skip to content

Instantly share code, notes, and snippets.

@nownabe
Created August 22, 2018 13:38
Show Gist options
  • Save nownabe/4345d9b68f323ba30905c9dfe3460006 to your computer and use it in GitHub Desktop.
Save nownabe/4345d9b68f323ba30905c9dfe3460006 to your computer and use it in GitHub Desktop.
Deserialize Kubernetes objects in Go
apiVersion: apps/v1
kind: Deployment
metadata:
namespace: my-namespace
name: memcached
spec:
replicas: 1
selector:
matchLabels:
app: memcached
template:
metadata:
labels:
app: memcached
spec:
securityContext:
fsGroup: 61000
runAsGroup: 61000
runAsUser: 61000
containers:
- name: memcached
image: memcached:1.5.10
securityContext:
allowPrivilegeEscalation: false
privileged: false
resources:
reuqests:
memory: 8Gi
cpu: 1000m
limits:
memory: 8Gi
cpu: 1000m
ports:
- containerPort: 11211
name: memcached
livenessProbe:
tcpSocket:
port: 11211
initialDelaySeconds: 30
timeoutSeconds: 5
readinessProbe:
tcpSocket:
port: 11211
initialDelaySeconds: 5
timeoutSeconds: 1
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"])
}
apiVersion: v1
kind: Namespace
metadata:
name: my-namespace
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment