Skip to content

Instantly share code, notes, and snippets.

@stek29
Created June 11, 2022 03:01
Show Gist options
  • Save stek29/d37b93d088ca0c05f4c385cb870571ea to your computer and use it in GitHub Desktop.
Save stek29/d37b93d088ca0c05f4c385cb870571ea to your computer and use it in GitHub Desktop.
decode kubernetes internal etcd encoding to YAMLs
package main
import (
"fmt"
"io/ioutil"
"os"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/client-go/kubernetes/scheme"
)
func decode(data []byte) (runtime.Object, error) {
codec := serializer.NewCodecFactory(scheme.Scheme)
decoder := codec.UniversalDeserializer()
object, err := runtime.Decode(decoder, data)
if err != nil {
return nil, err
}
return object, nil
}
func encode(object runtime.Object) ([]byte, error) {
encoder := json.NewYAMLSerializer(json.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)
data, err := runtime.Encode(encoder, object)
if err != nil {
return nil, err
}
return data, nil
}
func main() {
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "ERR: cant read stdin: %v\n", err)
os.Exit(1)
}
obj, err := decode(data)
if err != nil {
fmt.Fprintf(os.Stderr, "ERR: cant decode: %v\n", err)
os.Exit(1)
}
fmt.Printf("GVK: %v\n", obj.GetObjectKind().GroupVersionKind())
fmt.Printf("%+v\n", obj)
fmt.Printf("as yaml:\n---\n")
enc, err := encode(obj)
if err != nil {
fmt.Fprintf(os.Stderr, "ERR: cant encode: %v\n", err)
os.Exit(1)
}
fmt.Println(string(enc))
}
@stek29
Copy link
Author

stek29 commented Jul 1, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment