// import the required packages import ( "context" "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/util/retry" ) // create a kubernetes client config, err := rest.InClusterConfig() if err != nil { panic(err.Error()) } clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } // create a deployment deployment := &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "example-deployment", }, Spec: appsv1.DeploymentSpec{ Replicas: int32Ptr(2), Selector: &metav1.LabelSelector{ MatchLabels: map[string]string{ "app": "example-app", }, }, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": "example-app", }, }, Spec: corev1.PodSpec{ Containers: []corev1.Container{ { Name: "example-container", Image: "nginx:1.14.2", Ports: []corev1.ContainerPort{ { ContainerPort: 80, }, }, }, }, }, }, }, } // create the deployment createdDeployment, err := clientset.AppsV1().Deployments("default").Create(context.TODO(), deployment, metav1.CreateOptions{}) if err != nil { panic(err.Error()) } fmt.Printf("Created deployment %q.\n", createdDeployment.GetObjectMeta().GetName())
// import the required packages import ( "context" "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/util/retry" ) // create a kubernetes client config, err := rest.InClusterConfig() if err != nil { panic(err.Error()) } clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } // update a deployment deploymentName := "example-deployment" retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error { result, getErr := clientset.AppsV1().Deployments("default").Get(context.TODO(), deploymentName, metav1.GetOptions{}) if getErr != nil { panic(fmt.Errorf("Failed to get latest version of Deployment: %v", getErr)) } result.Spec.Replicas = int32Ptr(3) _, updateErr := clientset.AppsV1().Deployments("default").Update(context.TODO(), result, metav1.UpdateOptions{}) return updateErr }) if retryErr != nil { panic(fmt.Errorf("Failed to update Deployment: %v", retryErr)) }In this example, we update the number of replicas for a deployment using the AppsV1() method of the Kubernetes clientset, and then use the Update() method to apply the changes to the deployment. We also use the retry.RetryOnConflict() method to handle potential conflicts.