How to restart a deployment in kubernetes using go-client
Asked Answered
P

2

8

Is there a way to restart a kubernetes deployment using go-client .I have no idea how to achieve this ,help me!

Puffin answered 21/4, 2020 at 3:9 Comment(4)
Deployments are not restartable! Pods are. You can delete pods, related to your deployment, and then the deployment controller recreate your pods.Setting
Actually, a duplicate got a nice answer on #57559857Bibliology
I do not think it is a duplicate @DenisTrofimov. He/She asked for the client-go, not kubectl.Coze
The 2023 answer is that deployments are restartable, just in a sugared way as they are not themselves a running process.Tears
C
13

If you run kubectl rollout restart deployment/my-deploy -v=10 you see that kubectl actually sends a PATCH request to the APIServer and sets the .spec.template.metadata.annotations with something like this:

kubectl.kubernetes.io/restartedAt: '2022-11-29T16:33:08+03:30'

So, you can do this with the client-go:

clientset, err :=kubernetes.NewForConfig(config)
if err != nil {
    // Do something with err
}
deploymentsClient := clientset.AppsV1().Deployments(namespace)
data := fmt.Sprintf(`{"spec": {"template": {"metadata": {"annotations": {"kubectl.kubernetes.io/restartedAt": "%s"}}}}}`, time.Now().Format("20060102150405"))
deployment, err := deploymentsClient.Patch(ctx, deployment_name, k8stypes.StrategicMergePatchType, []byte(data), v1.PatchOptions{})
if err != nil {
    // Do something with err
}
Coze answered 30/11, 2022 at 8:10 Comment(0)
B
6

You can simply set the kubectl.kubernetes.io/restartedAt annotation and update the deployment. Here is a tested snippet:

const _namespace = "default"

type client struct {
    clientset *kubernetes.Clientset
}

func (c *client) RestartDeployment(ctx context.Context, deployName string) error {
    deploy, err := c.clientset.AppsV1().Deployments(_namespace).Get(ctx, deployName, metav1.GetOptions{})
    if err != nil {
        return err
    }

    if deploy.Spec.Template.ObjectMeta.Annotations == nil {
        deploy.Spec.Template.ObjectMeta.Annotations = make(map[string]string)
    }
    deploy.Spec.Template.ObjectMeta.Annotations["kubectl.kubernetes.io/restartedAt"] = time.Now().Format(time.RFC3339)

    _, err = c.clientset.AppsV1().Deployments(_namespace).Update(ctx, deploy, metav1.UpdateOptions{})
    return err
}
Biretta answered 5/6, 2023 at 18:58 Comment(2)
You should add explanation.Earthquake
IMO this should be the most upvoted answer, cleaner and more concise then the current one.Cornejo

© 2022 - 2024 — McMap. All rights reserved.