在Kubernetes中,我们可以使用client-go库来与集群进行交互。以下是一些使用client-go创建Deployment列表和创建新Deployment的示例代码。
- 获取Deployment列表:
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
func GetDeployments(clientset *kubernetes.Clientset) {
deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)
deployments, err := deploymentsClient.List(context.TODO(), metav1.ListOptions{})
if err != nil {
fmt.Println(err)
}
for _, d := range deployments.Items {
fmt.Printf(" * %s (%d replicas)\n", d.Name, *d.Spec.Replicas)
}
}
- 创建一个新的Deployment:
import (
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
func CreateDeployment(clientset *kubernetes.Clientset) {
deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)
deployment := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "demo-deployment",
},
Spec: appsv1.DeploymentSpec{
Replicas: int32Ptr(2),
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "demo",
},
},
Template: apiv1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: map[string]string{
"app": "demo",
},
},
Spec: apiv1.PodSpec{
Containers: []apiv1.Container{
{
Name: "web",
Image: "nginx:1.14.2",
Ports: []apiv1.ContainerPort{
{
Name: "http",
Protocol: apiv1.ProtocolTCP,
ContainerPort: 80,
},
},
},
},
},
},
},
}
result, err := deploymentsClient.Create(context.TODO(), deployment, metav1.CreateOptions{})
if err != nil {
fmt.Println(err)
}
fmt.Printf("Deployment created. Name: %s\n", result.