import ( "context" "fmt" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" ) func main() { // Set up the Kubernetes client config, err := rest.InClusterConfig() if err != nil { panic(err.Error()) } clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } // Get a list of Pods in the default namespace pods, err := clientset.CoreV1().Pods("default").List(context.Background(), metav1.ListOptions{}) if err != nil { panic(err.Error()) } // Print out the names of the Pods for _, pod := range pods.Items { fmt.Println(pod.Name) } }
import ( "context" "fmt" "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" ) func main() { // Set up the Kubernetes client config, err := rest.InClusterConfig() if err != nil { panic(err.Error()) } clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } // Define the Deployment spec labels := map[string]string{ "app": "myapp", } deploymentSpec := &v1.Deployment{ ObjectMeta: v1.ObjectMeta{ Name: "myapp", }, Spec: v1.DeploymentSpec{ Replicas: int32Ptr(1), Selector: &v1.LabelSelector{ MatchLabels: labels, }, Template: v1.PodTemplateSpec{ ObjectMeta: v1.ObjectMeta{ Labels: labels, }, Spec: v1.PodSpec{ Containers: []v1.Container{ { Name: "myapp", Image: "nginx:latest", Ports: []v1.ContainerPort{ { ContainerPort: 80, Protocol: v1.ProtocolTCP, }, }, }, }, }, }, }, } // Create the Deployment deployment, err := clientset.AppsV1().Deployments("default").Create(context.Background(), deploymentSpec, metav1.CreateOptions{}) if err != nil { panic(err.Error()) } // Print out the name of the Deployment fmt.Printf("Created deployment %q.\n", deployment.GetObjectMeta().GetName()) } // Helper function for creating int32 pointers func int32Ptr(i int32) *int32 { return &i }This example shows how to create a new clientset using the InClusterConfig, and then how to use the clientset to create a new Deployment in the "default" namespace. The example defines the Deployment spec as a struct literal, and then creates the Deployment using the AppsV1 client. The example then prints out the name of the Deployment.