用dynamic的客户端对deployment做增删改查验证!(学习)

    1. /*
    2. Copyright 2019 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. apiv1 "k8s.io/api/core/v1"
    23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    24. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    25. "k8s.io/apimachinery/pkg/runtime/schema"
    26. "k8s.io/client-go/dynamic"
    27. "k8s.io/client-go/tools/clientcmd"
    28. "k8s.io/client-go/util/homedir"
    29. "k8s.io/client-go/util/retry"
    30. //
    31. // Uncomment to load all auth plugins
    32. // _ "k8s.io/client-go/plugin/pkg/client/auth"
    33. //
    34. // Or uncomment to load specific auth plugins
    35. // _ "k8s.io/client-go/plugin/pkg/client/auth/azure"
    36. // _ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
    37. // _ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
    38. // _ "k8s.io/client-go/plugin/pkg/client/auth/openstack"
    39. )
    40. func main() {
    41. var kubeconfig *string
    42. if home := homedir.HomeDir(); home != "" {
    43. kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
    44. } else {
    45. kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
    46. }
    47. flag.Parse()
    48. namespace := "default"
    49. config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    50. if err != nil {
    51. panic(err)
    52. }
    53. client, err := dynamic.NewForConfig(config)
    54. if err != nil {
    55. panic(err)
    56. }
    57. deploymentRes := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}
    58. deployment := &unstructured.Unstructured{
    59. Object: map[string]interface{}{
    60. "apiVersion": "apps/v1",
    61. "kind": "Deployment",
    62. "metadata": map[string]interface{}{
    63. "name": "demo-deployment",
    64. },
    65. "spec": map[string]interface{}{
    66. "replicas": 2,
    67. "selector": map[string]interface{}{
    68. "matchLabels": map[string]interface{}{
    69. "app": "demo",
    70. },
    71. },
    72. "template": map[string]interface{}{
    73. "metadata": map[string]interface{}{
    74. "labels": map[string]interface{}{
    75. "app": "demo",
    76. },
    77. },
    78. "spec": map[string]interface{}{
    79. "containers": []map[string]interface{}{
    80. {
    81. "name": "web",
    82. "image": "nginx:1.12",
    83. "ports": []map[string]interface{}{
    84. {
    85. "name": "http",
    86. "protocol": "TCP",
    87. "containerPort": 80,
    88. },
    89. },
    90. },
    91. },
    92. },
    93. },
    94. },
    95. },
    96. }
    97. // Create Deployment
    98. fmt.Println("Creating deployment...")
    99. result, err := client.Resource(deploymentRes).Namespace(namespace).Create(context.TODO(), deployment, metav1.CreateOptions{})
    100. if err != nil {
    101. panic(err)
    102. }
    103. fmt.Printf("Created deployment %q.\n", result.GetName())
    104. // Update Deployment
    105. prompt()
    106. fmt.Println("Updating deployment...")
    107. // You have two options to Update() this Deployment:
    108. //
    109. // 1. Modify the "deployment" variable and call: Update(deployment).
    110. // This works like the "kubectl replace" command and it overwrites/loses changes
    111. // made by other clients between you Create() and Update() the object.
    112. // 2. Modify the "result" returned by Get() and retry Update(result) until
    113. // you no longer get a conflict error. This way, you can preserve changes made
    114. // by other clients between Create() and Update(). This is implemented below
    115. // using the retry utility package included with client-go. (RECOMMENDED)
    116. //
    117. // More Info:
    118. // https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
    119. retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
    120. // Retrieve the latest version of Deployment before attempting update
    121. // RetryOnConflict uses exponential backoff to avoid exhausting the apiserver
    122. result, getErr := client.Resource(deploymentRes).Namespace(namespace).Get(context.TODO(), "demo-deployment", metav1.GetOptions{})
    123. if getErr != nil {
    124. panic(fmt.Errorf("failed to get latest version of Deployment: %v", getErr))
    125. }
    126. // update replicas to 1
    127. if err := unstructured.SetNestedField(result.Object, int64(1), "spec", "replicas"); err != nil {
    128. panic(fmt.Errorf("failed to set replica value: %v", err))
    129. }
    130. // extract spec containers
    131. containers, found, err := unstructured.NestedSlice(result.Object, "spec", "template", "spec", "containers")
    132. if err != nil || !found || containers == nil {
    133. panic(fmt.Errorf("deployment containers not found or error in spec: %v", err))
    134. }
    135. // update container[0] image
    136. if err := unstructured.SetNestedField(containers[0].(map[string]interface{}), "nginx:1.13", "image"); err != nil {
    137. panic(err)
    138. }
    139. if err := unstructured.SetNestedField(result.Object, containers, "spec", "template", "spec", "containers"); err != nil {
    140. panic(err)
    141. }
    142. _, updateErr := client.Resource(deploymentRes).Namespace(namespace).Update(context.TODO(), result, metav1.UpdateOptions{})
    143. return updateErr
    144. })
    145. if retryErr != nil {
    146. panic(fmt.Errorf("update failed: %v", retryErr))
    147. }
    148. fmt.Println("Updated deployment...")
    149. // List Deployments
    150. prompt()
    151. fmt.Printf("Listing deployments in namespace %q:\n", apiv1.NamespaceDefault)
    152. list, err := client.Resource(deploymentRes).Namespace(namespace).List(context.TODO(), metav1.ListOptions{})
    153. if err != nil {
    154. panic(err)
    155. }
    156. for _, d := range list.Items {
    157. replicas, found, err := unstructured.NestedInt64(d.Object, "spec", "replicas")
    158. if err != nil || !found {
    159. fmt.Printf("Replicas not found for deployment %s: error=%s", d.GetName(), err)
    160. continue
    161. }
    162. fmt.Printf(" * %s (%d replicas)\n", d.GetName(), replicas)
    163. }
    164. // Delete Deployment
    165. prompt()
    166. fmt.Println("Deleting deployment...")
    167. deletePolicy := metav1.DeletePropagationForeground
    168. deleteOptions := metav1.DeleteOptions{
    169. PropagationPolicy: &deletePolicy,
    170. }
    171. if err := client.Resource(deploymentRes).Namespace(namespace).Delete(context.TODO(), "demo-deployment", deleteOptions); err != nil {
    172. panic(err)
    173. }
    174. fmt.Println("Deleted deployment.")
    175. }
    176. func prompt() {
    177. fmt.Printf("-> Press Return key to continue.")
    178. scanner := bufio.NewScanner(os.Stdin)
    179. for scanner.Scan() {
    180. break
    181. }
    182. if err := scanner.Err(); err != nil {
    183. panic(err)
    184. }
    185. fmt.Println()
    186. }