|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + "k8s.io/apimachinery/pkg/api/errors" |
| 9 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 10 | + "k8s.io/apimachinery/pkg/runtime/schema" |
| 11 | + "k8s.io/client-go/dynamic" |
| 12 | + "k8s.io/client-go/tools/clientcmd" |
| 13 | +) |
| 14 | + |
| 15 | +func main() { |
| 16 | + configLoader := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( |
| 17 | + clientcmd.NewDefaultClientConfigLoadingRules(), |
| 18 | + &clientcmd.ConfigOverrides{}, |
| 19 | + ) |
| 20 | + |
| 21 | + namespace, _, err := configLoader.Namespace() |
| 22 | + if err != nil { |
| 23 | + panic(err) |
| 24 | + } |
| 25 | + |
| 26 | + cfg, err := configLoader.ClientConfig() |
| 27 | + if err != nil { |
| 28 | + panic(err) |
| 29 | + } |
| 30 | + |
| 31 | + dc, err := dynamic.NewForConfig(cfg) |
| 32 | + if err != nil { |
| 33 | + panic(err) |
| 34 | + } |
| 35 | + |
| 36 | + // identify out custom resource |
| 37 | + gvr := schema.GroupVersionResource{ |
| 38 | + Group: "webapp.my.domain", |
| 39 | + Version: "v1", |
| 40 | + Resource: "guestbooks", |
| 41 | + } |
| 42 | + // retrieve the resource of kind Pizza named 'margherita' |
| 43 | + res, err := dc.Resource(gvr). |
| 44 | + Namespace(namespace). |
| 45 | + Get(context.TODO(), "guestbook-sample", metav1.GetOptions{}) |
| 46 | + if err != nil { |
| 47 | + if errors.IsNotFound(err) { |
| 48 | + return |
| 49 | + } |
| 50 | + panic(err) |
| 51 | + } |
| 52 | + data, _ := json.Marshal(res) |
| 53 | + fmt.Println(string(data)) |
| 54 | + |
| 55 | + // grab the status if exists |
| 56 | + status, ok := res.Object["status"] |
| 57 | + if !ok { |
| 58 | + // otherwise create it |
| 59 | + status = make(map[string]interface{}) |
| 60 | + } |
| 61 | + |
| 62 | + // change the 'margherita' price |
| 63 | + status.(map[string]interface{})["cost"] = 6.50 |
| 64 | + res.Object["status"] = status |
| 65 | + |
| 66 | + // update the 'margherita' custom resource with the new price |
| 67 | + _, err = dc.Resource(gvr).Namespace(namespace).Update(context.TODO(), res, metav1.UpdateOptions{}) |
| 68 | + if err != nil { |
| 69 | + panic(err) |
| 70 | + } |
| 71 | +} |
0 commit comments