发布时间:2024-12-23 01:33:59
go get -u k8s.io/client-go
go get -u k8s.io/client-go/tools/clientcmd
package main
import (
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
// 加载kubeconfig文件
kubeconfig := "/path/to/kubeconfig"
config, _ := clientcmd.BuildConfigFromFlags("", kubeconfig)
// 创建Kubernetes客户端
clientset, _ := kubernetes.NewForConfig(config)
// 使用clientset进行后续操作...
}
package main
import (
"fmt"
"bytes"
"os/exec"
)
func main() {
// 构建kubectl命令
command := exec.Command("kubectl", "get", "pods")
// 执行kubectl命令
var output bytes.Buffer
command.Stdout = &output
command.Run()
// 输出命令结果
fmt.Println(output.String())
}
package main
import (
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/api/core/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func main() {
// 加载kubeconfig文件
kubeconfig := "/path/to/kubeconfig"
config, _ := clientcmd.BuildConfigFromFlags("", kubeconfig)
// 创建Kubernetes客户端
clientset, _ := kubernetes.NewForConfig(config)
// 创建一个新的Pod对象
pod := &v1.Pod{
ObjectMeta: meta_v1.ObjectMeta{
Name: "my-pod",
Namespace: "default",
},
Spec: v1.PodSpec{
Containers: []v1.Container{
{
Name: "my-container",
Image: "nginx:latest",
},
},
},
}
// 调用Kubernetes API创建Pod
clientset.CoreV1().Pods("default").Create(pod)
}