Skip to content

Instantly share code, notes, and snippets.

@bcho
Created March 18, 2019 15:26
Show Gist options
  • Save bcho/42ab6e4c3554bbdb4849288e6fa1b6fd to your computer and use it in GitHub Desktop.
Save bcho/42ab6e4c3554bbdb4849288e6fa1b6fd to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"path/filepath"
"time"
apiv1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
const ns = "demo"
func main() {
clientset := mustNewClientFromOutside()
listPods(clientset)
deletePod := deployPod(clientset)
listPods(clientset)
time.Sleep(5 * time.Second)
deletePod()
listPods(clientset)
}
func listPods(clientset *kubernetes.Clientset) {
pods, err := clientset.CoreV1().Pods(ns).List(metav1.ListOptions{})
noerror(err)
for _, pod := range pods.Items {
fmt.Printf("%s\n", pod.Name)
}
}
func deployPod(clientset *kubernetes.Clientset) func() {
podClient := clientset.CoreV1().Pods(ns)
pod, err := podClient.Create(&apiv1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "test-pod",
},
Spec: apiv1.PodSpec{
Containers: []apiv1.Container{
{
Name: "test-pod-container",
Image: "b4fun/counter:2018062103",
},
},
},
})
noerror(err)
fmt.Printf("created pod: %s\n", pod.Name)
return func() {
noerror(podClient.Delete(pod.Name, nil))
}
}
func mustNewClientFromOutside() *kubernetes.Clientset {
homedir := os.Getenv("HOME")
kubeconfig := filepath.Join(homedir, ".kube", "config")
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
noerror(err)
clientset, err := kubernetes.NewForConfig(config)
noerror(err)
return clientset
}
func noerror(err error) {
if err != nil {
panic(err)
}
}
func int32Ptr(i int32) *int32 { return &i }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment