Skip to content

Instantly share code, notes, and snippets.

@thetechnick
Created August 24, 2023 19:41
Show Gist options
  • Save thetechnick/20407334a6dde3f75b58e59f02802ab9 to your computer and use it in GitHub Desktop.
Save thetechnick/20407334a6dde3f75b58e59f02802ab9 to your computer and use it in GitHub Desktop.
Kube real server-side apply with deletion...
package main
import (
"context"
"encoding/json"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)
var scheme = runtime.NewScheme()
func main() {
corev1.AddToScheme(scheme)
err := run()
if err != nil {
panic(err)
}
}
func run() error {
restConfig := ctrl.GetConfigOrDie()
c, err := client.New(restConfig, client.Options{})
if err != nil {
return err
}
ctx := context.Background()
return update(ctx, c)
}
func create(ctx context.Context, c client.Client) error {
cm := &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "ConfigMap",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "default",
},
Data: map[string]string{
"test": "test",
},
}
patch, err := json.Marshal(cm)
if err != nil {
return err
}
if err := c.Patch(ctx, cm, client.RawPatch(types.ApplyPatchType, patch), client.FieldOwner("test")); err != nil {
return err
}
return nil
}
func update(ctx context.Context, c client.Client) error {
cm := &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "ConfigMap",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "default",
},
Data: map[string]string{
// "test": "test",
},
}
patch, err := json.Marshal(cm)
if err != nil {
return err
}
if err := c.Patch(ctx, cm, client.RawPatch(types.ApplyPatchType, patch), client.FieldOwner("test")); err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment