Is there a way to restart a kubernetes deployment using go-client .I have no idea how to achieve this ,help me!
How to restart a deployment in kubernetes using go-client
Asked Answered
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 #57559857 –
Bibliology
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
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
}
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
}
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.