在Kubernetes中,client-go库是一个用于与Kubernetes API服务器交互的Go语言客户端。以下是一个使用client-go创建和删除Pods的简单示例:
package main
import (
"context"
"flag"
"fmt"
"path/filepath"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
func main() {
var kubeconfig *string
if home := homedir.HomeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err)
}
// 创建Pod
podClient := clientset.CoreV1().Pods("default")
pod := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "demo-pod",
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "demo-container",
Image: "nginx",
},
},
},
}
fmt.Println("Creating pod...")
_, err = podClient.Create(context.TODO(), pod, metav1.CreateOptions{})
if err != nil {
panic(err)
}
fmt.Println("Pod created")
// 删除Pod
fmt.Println("Deleting pod...")
deletePolicy := metav1.DeletePropagationForeground
err = podClient.Delete(context.TODO(), "demo-pod", metav1.DeleteOptions{
PropagationPolicy: &deletePolicy,
})
if err != nil {
panic(err)
}
fmt.Println("Pod deleted")
}
这段代码首先解析kubeconfig文件的路径,然后使用提供的配置信息创建一个Kubernetes客户端。接下来,它展示了如何创建一个简单的Pod和如何删除它。这是一个基本的例子,展示了如何使用client-go库与Kubernetes集群交互。