使用Kubernetes Go Client扩展部署副本 [英] Scale deployment replicas with kubernetes go client

查看:114
本文介绍了使用Kubernetes Go Client扩展部署副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用 golang客户端.我发现的问题是 golang客户端不会没有用于部署的扩展方法.我不知道该怎么办. 我的想法是进行部署,修改副本,然后进行更新.

I'm trying to scale a deployment with golang client. The problem I've found is that the golang client does not have a scale method for deployments. I don't know how I should do it. The idea that I have is get a deployment, modify the replicas, and then do an update.

package main

import (
    "context"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    appsv1 "k8s.io/api/apps/v1"
    "flag"
    "fmt"
    "os"
    "path/filepath"

)

func main() {
    var kubeconfig *string
    if home := homedir.HomeDir(); home != "" {
        kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
    } else {
        kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
    }
    flag.Parse()

    config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
    if err != nil {
        panic(err)
    }
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err)
    }
    //get and update replicas
    deploymentsClient := clientset.AppsV1().Deployments(apiv1.NamespaceDefault)
    deployment, _ := deploymentsClient.Get(context.TODO(), "demo-deployment", metav1.GetOptions{})
    deploymentsClient.Update(context.TODO(), deployment, metav1.UpdateOptions{})
}

(示例取自 kubernetes客户端 github存储库)

(Example taken from kubernetes client go github repository)

但是我不知道这是否是最好的方法.

But I don't know if it is the best aproach.

推荐答案

您还可以使用patch将更改应用于部署对象.

You can also use patch to apply changes to the deployment object.

// here, 
// "client" be the kubernetes client
// "cur" be the current deployment object
// "mod" be the modified deployment object, 
// make sure to use deep copy before modifying the deployment object.

func PatchDeploymentObject(client kubernetes.Interface, cur, mod *apps.Deployment) (*apps.Deployment, error) {
    curJson, err := json.Marshal(cur)
    if err != nil {
        return nil, err
    }

    modJson, err := json.Marshal(mod)
    if err != nil {
        return nil, err
    }

    patch, err := strategicpatch.CreateTwoWayMergePatch(curJson, modJson, apps.Deployment{})
    if err != nil {
        return nil, err
    }

    if len(patch) == 0 || string(patch) == "{}" {
        return cur, nil
    }

    out, err := client.AppsV1().Deployments(cur.Namespace).Patch(cur.Name, types.StrategicMergePatchType, patch)

    return out, err
}

这篇关于使用Kubernetes Go Client扩展部署副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆