package main import ( "fmt" v1 "k8s.io/api/apps/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/util/retry" ) func main() { config, err := rest.InClusterConfig() if err != nil { panic(err.Error()) } clientSet, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } deployment := &v1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "my-deployment", }, Spec: v1.DeploymentSpec{ Replicas: int32Ptr(2), Template: apiv1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: map[string]string{ "app": "my-deployment", }, }, Spec: apiv1.PodSpec{ Containers: []apiv1.Container{ { Name: "my-container", Image: "my-image", Port: apiv1.ContainerPort{ ContainerPort: 80, Protocol: apiv1.ProtocolTCP, }, }, }, }, }, }, } retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error { _, err := clientSet.AppsV1().Deployments().Create(deployment) if err != nil { fmt.Printf("Failed to create deployment: %v\n", err) return err } return nil }) if retryErr != nil { panic(fmt.Errorf("error creating deployment: %v", retryErr)) } }
package main import ( "fmt" apiv1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" ) func main() { config, err := rest.InClusterConfig() if err != nil { panic(err.Error()) } clientSet, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } service := &apiv1.Service{ ObjectMeta: metav1.ObjectMeta{ Name: "my-service", }, Spec: apiv1.ServiceSpec{ Selector: map[string]string{ "app": "my-deployment", }, Ports: []apiv1.ServicePort{ { Name: "http", Protocol: apiv1.ProtocolTCP, Port: 80, TargetPort: intstr.FromInt(80), }, }, }, } _, err = clientSet.CoreV1().Services(apiv1.NamespaceDefault).Create(service) if err != nil { panic(fmt.Errorf("error creating service: %v", err)) } }This code also uses the Kubernetes client-go library to create a service in the Kubernetes cluster. The `intstr.FromInt` function is used to convert an int to an int32 type, which is required for specifying the target port. In both examples, the go k8s.io/kubernetes/pkg/client interface is used to interact with Kubernetes resources in a declarative manner, allowing developers to easily create, update, and delete resources in the cluster.