Created
November 6, 2022 22:28
-
-
Save viveksyngh/96d4583deeb3717de5280ce0a2832749 to your computer and use it in GitHub Desktop.
K8S Object encode/decode using sigs.k8s.io/yaml package
This file contains hidden or 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" | |
| corev1 "k8s.io/api/core/v1" | |
| metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
| "sigs.k8s.io/yaml" | |
| ) | |
| func main() { | |
| // Marshal a ConfigMap object to YAML. | |
| cm1 := corev1.ConfigMap{ | |
| ObjectMeta: metav1.ObjectMeta{ | |
| Name: "test-configmap", | |
| Namespace: "test-namespace", | |
| }, | |
| Data: map[string]string{ | |
| "key": "value", | |
| }, | |
| } | |
| y, err := yaml.Marshal(cm1) | |
| if err != nil { | |
| fmt.Printf("err: %v\n", err) | |
| return | |
| } | |
| fmt.Println("Encoded YAML:") | |
| fmt.Println(string(y)) | |
| y1 := ` | |
| kind: ConfigMap | |
| apiVersion: v1 | |
| metadata: | |
| name: test-configmap | |
| namespace: test-namespace | |
| data: | |
| key: value | |
| ` | |
| // Unmarshal the YAML back into another ConfigMap object. | |
| var cm2 corev1.ConfigMap | |
| err = yaml.Unmarshal([]byte(y1), &cm2) | |
| if err != nil { | |
| fmt.Printf("err: %v\n", err) | |
| return | |
| } | |
| fmt.Println("Decoded Object from YAML:") | |
| fmt.Println(cm2) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment