集群配置管理

k8s的配置文件默认会存放在~/.kube/config中,其内容如下:
image.png
地址:https://github.com/kubernetes/client-go/blob/master/examples/create-update-delete-deployment/main.go

  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Note: the example only works with the code within the same release/branch.
  14. package main
  15. import (
  16. "bufio"
  17. "context"
  18. "flag"
  19. "fmt"
  20. "os"
  21. "path/filepath"
  22. appsv1 "k8s.io/api/apps/v1"
  23. apiv1 "k8s.io/api/core/v1"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/client-go/kubernetes"
  26. "k8s.io/client-go/tools/clientcmd"
  27. "k8s.io/client-go/util/homedir"
  28. "k8s.io/client-go/util/retry"
  29. //
  30. // Uncomment to load all auth plugins
  31. // _ "k8s.io/client-go/plugin/pkg/client/auth"
  32. //
  33. // Or uncomment to load specific auth plugins
  34. // _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
  35. // _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
  36. // _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
  37. // _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
  38. )
  39. func main() {
  40. var kubeconfig *string
  41. if home := homedir.HomeDir(); home != "" {
  42. kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
  43. } else {
  44. kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
  45. }
  46. flag.Parse()
  47. config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
  48. if err != nil {
  49. panic(err)
  50. }
  51. clientset, err := kubernetes.NewForConfig(config)
  52. if err != nil {
  53. panic(err)
  54. }
  55. deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)
  56. deployment := &appsv1.Deployment{
  57. ObjectMeta: metav1.ObjectMeta{
  58. Name: "demo-deployment",
  59. },
  60. Spec: appsv1.DeploymentSpec{
  61. Replicas: int32Ptr(2),
  62. Selector: &metav1.LabelSelector{
  63. MatchLabels: map[string]string{
  64. "app": "demo",
  65. },
  66. },
  67. Template: apiv1.PodTemplateSpec{
  68. ObjectMeta: metav1.ObjectMeta{
  69. Labels: map[string]string{
  70. "app": "demo",
  71. },
  72. },
  73. Spec: apiv1.PodSpec{
  74. Containers: []apiv1.Container{
  75. {
  76. Name: "web",
  77. Image: "nginx:1.12",
  78. Ports: []apiv1.ContainerPort{
  79. {
  80. Name: "http",
  81. Protocol: apiv1.ProtocolTCP,
  82. ContainerPort: 80,
  83. },
  84. },
  85. },
  86. },
  87. },
  88. },
  89. },
  90. }
  91. // Create Deployment
  92. fmt.Println("Creating deployment...")
  93. result, err := deploymentsClient.Create(context.TODO(), deployment, metav1.CreateOptions{})
  94. if err != nil {
  95. panic(err)
  96. }
  97. fmt.Printf("Created deployment %q.\n", result.GetObjectMeta().GetName())
  98. // Update Deployment
  99. prompt()
  100. fmt.Println("Updating deployment...")
  101. // You have two options to Update() this Deployment:
  102. //
  103. // 1. Modify the "deployment" variable and call: Update(deployment).
  104. // This works like the "kubectl replace" command and it overwrites/loses changes
  105. // made by other clients between you Create() and Update() the object.
  106. // 2. Modify the "result" returned by Get() and retry Update(result) until
  107. // you no longer get a conflict error. This way, you can preserve changes made
  108. // by other clients between Create() and Update(). This is implemented below
  109. // using the retry utility package included with client-go. (RECOMMENDED)
  110. //
  111. // More Info:
  112. // https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
  113. retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
  114. // Retrieve the latest version of Deployment before attempting update
  115. // RetryOnConflict uses exponential backoff to avoid exhausting the apiserver
  116. result, getErr := deploymentsClient.Get(context.TODO(), "demo-deployment", metav1.GetOptions{})
  117. if getErr != nil {
  118. panic(fmt.Errorf("Failed to get latest version of Deployment: %v", getErr))
  119. }
  120. result.Spec.Replicas = int32Ptr(1) // reduce replica count
  121. result.Spec.Template.Spec.Containers[0].Image = "nginx:1.13" // change nginx version
  122. _, updateErr := deploymentsClient.Update(context.TODO(), result, metav1.UpdateOptions{})
  123. return updateErr
  124. })
  125. if retryErr != nil {
  126. panic(fmt.Errorf("Update failed: %v", retryErr))
  127. }
  128. fmt.Println("Updated deployment...")
  129. // List Deployments
  130. prompt()
  131. fmt.Printf("Listing deployments in namespace %q:\n", apiv1.NamespaceDefault)
  132. list, err := deploymentsClient.List(context.TODO(), metav1.ListOptions{})
  133. if err != nil {
  134. panic(err)
  135. }
  136. for _, d := range list.Items {
  137. fmt.Printf(" * %s (%d replicas)\n", d.Name, *d.Spec.Replicas)
  138. }
  139. // Delete Deployment
  140. prompt()
  141. fmt.Println("Deleting deployment...")
  142. deletePolicy := metav1.DeletePropagationForeground
  143. if err := deploymentsClient.Delete(context.TODO(), "demo-deployment", metav1.DeleteOptions{
  144. PropagationPolicy: &deletePolicy,
  145. }); err != nil {
  146. panic(err)
  147. }
  148. fmt.Println("Deleted deployment.")
  149. }
  150. func prompt() {
  151. fmt.Printf("-> Press Return key to continue.")
  152. scanner := bufio.NewScanner(os.Stdin)
  153. for scanner.Scan() {
  154. break
  155. }
  156. if err := scanner.Err(); err != nil {
  157. panic(err)
  158. }
  159. fmt.Println()
  160. }
  161. func int32Ptr(i int32) *int32 { return &i }