在extensions/v1beta1版本下,client-go的api接口下的deployment支持rollback方法来回滚,使用方法如下:
rollback := &v1beta1.DeploymentRollback{
Name: name,
RollbackTo: v1beta1.RollbackConfig{
Revision: 0,
},
}
if err = client.ExtensionsV1beta1().Deployments(namespace).Rollback(rollback); err != nil {
return
}
但在最新的apps/v1版本下,这个rollback方法被移除了,查了一下资料,找到如下说明:
https://github.com/kubernetes/kubernetes/pull/59970#discussion_r169921531
这里说回滚需要自己来实现,实现思路如下:
大致意思如下:
列出当前deployment的rs
找到指定版本的rs
将指定版本的rs的template赋值给deployment的template来进行deployment的update操作实现回滚
按照这个思路实现代码如下:
package main
import (
"context"
"fmt"
"log"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
var (
err error
conf *rest.Config
client *kubernetes.Clientset
)
if conf, err = clientcmd.BuildConfigFromFlags("", "/Users/5bug/.kube/config"); err != nil {
log.Println("BuildConfigFromFlags", err)
return
}
if client, err = kubernetes.NewForConfig(conf); err != nil {
log.Println("NewForConfig", err)
return
}
namespace := "default"
deploymentName := "k8s-demo"
labelSelector := fmt.Sprintf("app=%s", deploymentName)
replicaSetList, err := client.AppsV1().ReplicaSets(namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: labelSelector})
if err != nil {
return
}
if len(replicaSetList.Items) <= 1 {
fmt.Println("回滚未执行,没有可回滚的版本")
return
}
deployment, err := client.AppsV1().Deployments(namespace).Get(context.TODO(), deploymentName, metav1.GetOptions{})
if err != nil {
return
}
// 回滚到此版本k8s-demo-5b65566549
rs := "k8s-demo-5b65566549"
for _, v := range replicaSetList.Items {
if v.ObjectMeta.Name == rs {
deployment.Spec.Template = v.Spec.Template
if _, err = client.AppsV1().Deployments(namespace).Update(context.TODO(), deployment, metav1.UpdateOptions{}); err != nil {
return
}
fmt.Println("回滚已执行")
return
}
}
fmt.Println("回滚未执行,没有找到指定的版本")
}