Pattapu Sai
Pattapu Sai

Reputation: 109

How to restart a deployment in kubernetes using go-client

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

Upvotes: 8

Views: 5781

Answers (2)

Ahmad Elsagheer
Ahmad Elsagheer

Reputation: 156

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
}

Upvotes: 6

Andromeda
Andromeda

Reputation: 1441

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
}

Upvotes: 13

Related Questions