Skip to content

Instantly share code, notes, and snippets.

@daemon1024
Created May 9, 2022 11:54
Show Gist options
  • Save daemon1024/3f94841e6ef12e39195e054b8a76a92a to your computer and use it in GitHub Desktop.
Save daemon1024/3f94841e6ef12e39195e054b8a76a92a to your computer and use it in GitHub Desktop.
package main
// Based on https://github.com/iximiuz/client-go-examples/blob/939aded807a4f42731dc18c0a5cd71f5e99b1886/crud-typed-simple/main.go
// and https://raw.githubusercontent.com/rancher/local-path-provisioner/v0.0.22/deploy/local-path-storage.yaml
import (
"context"
"fmt"
"os"
"path"
"reflect"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
home, err := os.UserHomeDir()
if err != nil {
panic(err)
}
config, err := clientcmd.BuildConfigFromFlags("", path.Join(home, ".kube/config"))
if err != nil {
panic(err.Error())
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
namespace := "default"
cm := corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "my-config-map",
Namespace: namespace,
},
Data: map[string]string{
"conf.json": `{
"nodePathMap":[
{
"node":"DEFAULT_PATH_FOR_NON_LISTED_NODES",
"paths":["/opt/local-path-provisioner"]
}
]
}`,
"setup": `#!/bin/sh
set -eu
mkdir -m 0777 -p "$VOL_DIR"`,
"teardown": `#!/bin/sh
set -eu
rm -rf "$VOL_DIR"`,
"helperPod.yaml": `apiVersion: v1
kind: Pod
metadata:
name: helper-pod
spec:
containers:
- name: helper-pod
image: busybox
imagePullPolicy: IfNotPresent`,
},
}
// Create
created, err := client.
CoreV1().
ConfigMaps(namespace).
Create(
context.Background(),
&cm,
metav1.CreateOptions{},
)
if err != nil {
panic(err.Error())
}
fmt.Printf("Created ConfigMap %s/%s\n", namespace, created.GetName())
if !reflect.DeepEqual(created.Data, cm.Data) {
panic("Created ConfigMap has unexpected data")
}
// Read
read, err := client.
CoreV1().
ConfigMaps(namespace).
Get(
context.Background(),
created.GetName(),
metav1.GetOptions{},
)
if err != nil {
panic(err.Error())
}
fmt.Printf("Read ConfigMap %s/%s\n", namespace, read.Data["conf.json"])
fmt.Print("Continue?")
fmt.Scanf("%c")
// Delete
err = client.
CoreV1().
ConfigMaps(namespace).
Delete(
context.Background(),
created.GetName(),
metav1.DeleteOptions{},
)
if err != nil {
panic(err.Error())
}
fmt.Printf("Deleted ConfigMap %s/%s\n", namespace, created.GetName())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment