Last active
          November 6, 2022 21:58 
        
      - 
      
- 
        Save viveksyngh/749e80c34f5633bbe479e1b668d98029 to your computer and use it in GitHub Desktop. 
    K8S Object encode/decode using gopokgs.in/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" | |
| "gopkg.in/yaml.v3" | |
| corev1 "k8s.io/api/core/v1" | |
| metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
| ) | |
| 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