使用client-go工具调用kubernetesAPI接口的教程详解(v1.17版本)_...

使用client-go工具调用kubernetesAPI接口的教程详解(v1.17版本)_...

2023年6月30日发(作者:)

使⽤client-go⼯具调⽤kubernetesAPI接⼝的教程详解(v1.17版本)⽬录说明效果实现1、拉取⼯具源码2、创建⽬录结构查询代码实例创建deployment资源更新deployment类型服务删除deployment类型服务说明可以调取k8s API 接⼝的⼯具有很多,这⾥我就介绍下client-go这个⼯具是由kubernetes官⽅指定维护的,⼤家可以放⼼使⽤效果运⾏完成后,可以直接获取k8s集群信息等实现1、拉取⼯具源码总结:⼀定要拉取跟集群对应版本的⼯具源码,⽐如我这⾥集群是1.17版本,那我就拉取17版本go get /client-go@v0.17.0我是1.17版本的集群,所有依赖⽂件放在这了,可以直接使⽤2、创建⽬录结构集群的⾓⾊配置⽂件(默认在/root/.kube/config)kube/config查询代码实例查询pod信息查看ferry命名空间下pod的信息,pod名字、pod的IPvim age mainimport ( "fmt" metav1 "/apimachinery/pkg/apis/meta/v1" "/client-go/kubernetes" "/client-go/tools/clientcmd")func main() { config, err := onfigFromFlags("", "kube/config") if err != nil { panic(err) } client, _ := Config(config) pods ,err := 1().Pods("ferry").List(tions{}) if err != nil { n(err) return } for _,v := range { (" 命名空间是:%vn pod名字:%vn IP:%vnn",ace,,) }}⾃动关联依赖go mod tidy运⾏结果$ go run 命名空间是:ferry pod名字:ferry-backend-7949596679-h8lxb IP:10.42.1.14 命名空间是:ferry pod名字:ferry-mysql-8db8d49f7-6psbv IP:10.42.1.11查询⼀个pod是否在⼀个命名空间下package mainimport ( "context" "fmt" "/apimachinery/pkg/api/errors" metav1 "/apimachinery/pkg/apis/meta/v1" "/client-go/kubernetes" "/client-go/tools/clientcmd" "time")func main() { config, err := onfigFromFlags("", "kube/config") if err != nil { panic(err) } clientset, err := Config(config) if err != nil { panic(()) } for { // get pods in all the namespaces by omitting namespace // Or specify namespace to get pods in particular namespace pods, err := 1().Pods("").List((), tions{}) if err != nil { panic(()) } ("There are %d pods in the clustern", len()) // Examples for error handling: // - Use helper ound() // - And/or cast to StatusError and use its properties e _, err = 1().Pods("default").Get((), "nginx-74959fc858-cp48w", ions{}) if ound(err) { ("Pod nginx-74959fc858-cp48w not found in default namespacen") } else if statusError, isStatus := err.(*Error); isStatus { ("Error getting pod %vn", e) } else if err != nil { panic(()) } else { ("Found nginx-74959fc858-cp48w pod in default namespacen") } (3 * ) }}运⾏结果$ go run e are 22 pods in the clusterFound nginx-74959fc858-cp48w pod in default namespaceThere are 22 pods in the clusterFound nginx-74959fc858-cp48w pod in default namespaceThere are 22 pods in the clusterFound nginx-74959fc858-cp48w pod in default namespaceThere are 23 pods in the clusterFound nginx-74959fc858-cp48w pod in default namespaceThere are 22 pods in the clusterFound nginx-74959fc858-cp48w pod in default namespaceThere are 22 pods in the clusterFound nginx-74959fc858-cp48w pod in default namespaceThere are 21 pods in the cluster在集群种⼿动删除了这个podPod nginx-74959fc858-cp48w not found in default namespaceThere are 21 pods in the clusterPod nginx-74959fc858-cp48w not found in default namespace查询deployment服务类型信息查询default命名空间下的deployment服务信息,服务名字、服务副本数package mainimport ( "fmt" metav1 "/apimachinery/pkg/apis/meta/v1" "/client-go/kubernetes" "/client-go/tools/clientcmd")func main() { config, err := onfigFromFlags("", "kube/config") if err != nil { panic(err) } client, _ := Config(config) deploymentList, err := 1().Deployments("default").List(tions{}) if err != nil { n(err) return } for _,v := range { (" 命名空间是:%vn deployment服务名字:%vn 副本个数:%vnn",ace,,as) }}运⾏结果$ go run 命名空间是:default deployment服务名字:nginx 副本个数:2创建deployment资源复制⼀个config⽂件到当前⽬录下创建⼀个deployment类型的nginx服务vim age mainimport ( "context" "flag" "fmt" "path/filepath" appsv1 "/api/apps/v1" apiv1 "/api/core/v1" metav1 "/apimachinery/pkg/apis/meta/v1" "/client-go/kubernetes" "/client-go/tools/clientcmd" "/client-go/util/homedir" // // Uncomment to load all auth plugins // _ "/client-go/plugin/pkg/client/auth" // // Or uncomment to load specific auth plugins // _ "/client-go/plugin/pkg/client/auth/azure" // _ "/client-go/plugin/pkg/client/auth/gcp" // _ "/client-go/plugin/pkg/client/auth/oidc" // _ "/client-go/plugin/pkg/client/auth/openstack")func main() { var kubeconfig *string if home := r(); home != "" { kubeconfig = ("kubeconfig", ("config"), "(optional) absolute path to the kubeconfig file") } else { kubeconfig = ("kubeconfig", "", "absolute path to the kubeconfig file") } () config, err := onfigFromFlags("", *kubeconfig) if err != nil { panic(err) } clientset, err := Config(config) if err != nil { panic(err) } deploymentsClient := 1().Deployments(aceDefault) deployment := &ment{ ObjectMeta: Meta{ Name: "nginx-deployment", }, Spec: mentSpec{ Replicas: int32Ptr(2), Selector: &elector{ MatchLabels: map[string]string{ "app": "nginx", }, }, Template: plateSpec{ ObjectMeta: Meta{ Labels: map[string]string{ "app": "nginx", }, }, Spec: c{ Containers: []ner{ { Name: "web", Image: "nginx:1.12", Ports: []nerPort{ { Name: "http", Protocol: olTCP, ContainerPort: 80, }, }, }, }, }, }, }, } // Create Deployment n("Creating ") result, err := ((), deployment, Options{}) if err != nil { panic(err) } ("Created deployment %q.n", ectMeta().GetName())}运⾏结果$ go run ting Created deployment "nginx-deployment".更新deployment类型服务package mainimport ( "context" "flag" "fmt" "path/filepath" apiv1 "/api/core/v1" metav1 "/apimachinery/pkg/apis/meta/v1" "/client-go/kubernetes" "/client-go/tools/clientcmd" "/client-go/util/homedir" "/client-go/util/retry" // // Uncomment to load all auth plugins // _ "/client-go/plugin/pkg/client/auth" // // Or uncomment to load specific auth plugins // _ "/client-go/plugin/pkg/client/auth/azure" // _ "/client-go/plugin/pkg/client/auth/gcp" // _ "/client-go/plugin/pkg/client/auth/oidc" // _ "/client-go/plugin/pkg/client/auth/openstack")func main() { var kubeconfig *string if home := r(); home != "" { kubeconfig = ("kubeconfig", ("config"), "(optional) absolute path to the kubeconfig file") } else { kubeconfig = ("kubeconfig", "", "absolute path to the kubeconfig file") } () config, err := onfigFromFlags("", *kubeconfig) if err != nil { panic(err) } clientset, err := Config(config) if err != nil { panic(err) } deploymentsClient := 1().Deployments(aceDefault) retryErr := nConflict(tRetry, func() error { // Retrieve the latest version of Deployment before attempting update // RetryOnConflict uses exponential backoff to avoid exhausting the apiserver result, getErr := ((), "nginx-deployment", ions{}) if getErr != nil { panic(("Failed to get latest version of Deployment: %v", getErr)) } as = int32Ptr(1) // reduce replica count ners[0].Image = "nginx:1.13" // change nginx version _, updateErr := ((), result, Options{}) return updateErr }) if retryErr != nil { panic(("Update failed: %v", retryErr)) } n("Updated deployment nginx")}func int32Ptr(i int32) *int32 { return &i }运⾏结果$ go run ted deployment nginx删除deployment类型服务删除上⾯创建的nginx-deployment资源,删除之前添加了确认语句package mainimport ( "bufio" "context" "flag" "fmt" "os" "path/filepath" apiv1 "/api/core/v1" metav1 "/apimachinery/pkg/apis/meta/v1" "/client-go/kubernetes" "/client-go/tools/clientcmd" "/client-go/util/homedir" // // Uncomment to load all auth plugins // _ "/client-go/plugin/pkg/client/auth" // // Or uncomment to load specific auth plugins // _ "/client-go/plugin/pkg/client/auth/azure" // _ "/client-go/plugin/pkg/client/auth/gcp" // _ "/client-go/plugin/pkg/client/auth/oidc" // _ "/client-go/plugin/pkg/client/auth/openstack")func main() { var kubeconfig *string if home := r(); home != "" { kubeconfig = ("kubeconfig", ( "config"), "(optional) absolute path to the kubeconfig file") } else { kubeconfig = ("kubeconfig", "", "absolute path to the kubeconfig file") } () config, err := onfigFromFlags("", *kubeconfig) if err != nil { panic(err) } clientset, err := Config(config) if err != nil { panic(err) } deploymentsClient := 1().Deployments(aceDefault) prompt() n("Deleting ") deletePolicy := PropagationForeground if err := ((), "nginx-deployment", Options{ PropagationPolicy: &deletePolicy, }); err != nil { panic(err) } n("Deleted deployment.")}func prompt() { ("-> Press Return key to continue, will delete!") scanner := nner() for () { break } if err := (); err != nil { panic(err) } n()}func int32Ptr(i int32) *int32 { return &i }运⾏结果$ go run -> Press Return key to continue, will delete! 这⾥点击回车后继续删除资源Deleting Deleted deployment.到此这篇关于使⽤client-go⼯具调kubernetes API接⼝(v1.17版本)的⽂章就介绍到这了,更多相关client-go调⽤kubernetes API内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1688055780a72119.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信