k8s源码学习-client-go创建pod

网友投稿 266 2022-09-11

k8s源码学习-client-go创建pod

在kube-system命名空间下创建test-busybox pod

测试环境:Mac+minikube

源码参考:​​ github源码地址​​

package mainimport ( "context" "fmt" "path/filepath" "flag" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" corev1 "k8s.io/api/core/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() // 使用kubeconfig中的当前上下文,加载配置文件 config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) if err != nil { panic(err.Error()) } // 创建clientset clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } //pod模版 newPod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "test-busybox", }, Spec: corev1.PodSpec{ Containers: []corev1.Container{ {Name: "busybox", Image: "busybox:latest", Command: []string{"sleep", "1000"}}, }, }, } //创建pod pod, err := clientset.CoreV1().Pods("kube-system").Create(context.Background(), newPod, metav1.CreateOptions{}) if err != nil { panic(err) } fmt.Printf("Created pod %q.\n", pod.GetObjectMeta().GetName())}

✗ go run main.go Created pod "test-busybox".✗ kubectl get pod -n kube-system | grep test-busyboxtest-busybox 1/1 Running 0 66s

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:线上k8s集群利用服务拓扑流量路由策略来设置定向流量?
下一篇:试了千遍万遍,展示再营销还是做不好?戳这里!
相关文章

 发表评论

暂时没有评论,来抢沙发吧~