我的kubernetes aws weeks集群中有超过4000个pvc。
- 从这4000多个pvc中,我必须删除近3999个pvc
现在不用command:
kubetcl delete pvc pvc-data-name
并分别删除每个PVC,这可能会花我很长时间…我想找到一种方法来批量或全部删除它们。
你可以试试这个
kubectl delete pvc --field-selector metadata.name!=<name-dont-want-to-delete-1>, metadata.name!=<name-dont-want-to-delete-2>, metadata.name!=<name-dont-want-to-delete-3>
,或者你也可以这样处理go-client
。要使用go客户端完成此操作,请参见文档Ref
我在每个pvc
中添加了一个标签,我不想删除。
labels:
test: test-1
import (
"context"
"fmt"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/util/homedir"
"kmodules.xyz/client-go/tools/clientcmd"
"log"
"path/filepath"
)
func testFunc() ( error) {
masterURL := ""
kubeconfigPath := filepath.Join(homedir.HomeDir(), ".kube", "config")
config, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfigPath)
if err != nil {
log.Fatalf("Could not get Kubernetes config: %s", err)
}
kc := kubernetes.NewForConfigOrDie(config)
labelSelector := &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
"test",
metav1.LabelSelectorOpNotIn,
[]string{
"test-0",
"test-1",
},
},
},
}
err = kc.CoreV1().PersistentVolumeClaims("default").DeleteCollection(context.TODO(), metav1.DeleteOptions{}, metav1.ListOptions{
LabelSelector: metav1.FormatLabelSelector(labelSelector),
})
fmt.Println(err)
return nil
}
尝试使用grep和xargs
kubectl get pvc | grep -v <name-to-not-include> | xargs kubectl delete pvc --grace-period=0 --force
更新:
对于多个模式:
kubectl get pvc | grep -v 'pattern1|pattern2' | xargs kubectl delete pvc --grace-period=0 --force