Skip to content

Instantly share code, notes, and snippets.

@bburky
Created July 7, 2020 21:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bburky/7047be4866881aa22030ba4a74b89538 to your computer and use it in GitHub Desktop.
Save bburky/7047be4866881aa22030ba4a74b89538 to your computer and use it in GitHub Desktop.
Delete all vSphere CNS volumes
// Based on https://github.com/vmware/govmomi/blob/a411671fde1b6ac482ef96e0ae4f22d415cbf256/cns/client_test.go
// Delete all CNS volumes:
// go get -u github.com/vmware/govmomi
// go run delete-all-cns-volumes.go
package main
import (
"context"
"log"
"os"
"fmt"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/vim25/soap"
cns "github.com/vmware/govmomi/cns"
cnstypes "github.com/vmware/govmomi/cns/types"
)
func main() {
// example: export CNS_VC_URL='https://username:password@vc-ip/sdk'
// Username and password may need to be URL encoded
url := os.Getenv("CNS_VC_URL")
u, err := soap.ParseURL(url)
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
c, err := govmomi.NewClient(ctx, u, true)
if err != nil {
log.Fatal(err)
}
c.UseServiceVersion("vsan")
cnsClient, err := cns.NewClient(ctx, c.Client)
if err != nil {
log.Fatal(err)
}
// Empty filter, serach for all CNS volumes:
queryFilter := cnstypes.CnsQueryFilter{}
cnsClient.QueryVolume(ctx, queryFilter)
fmt.Printf("Calling QueryVolume using queryFilter: %+v\n", queryFilter)
queryResult, err := cnsClient.QueryVolume(ctx, queryFilter)
if err != nil {
log.Printf("Failed to query volume. Error: %+v\n", err)
log.Fatal(err)
}
for _, volume := range queryResult.Volumes {
volumeIDList := []cnstypes.CnsVolumeId{{Id: volume.VolumeId.Id}}
// DeleteVolume
fmt.Printf("Deleting volume: %+v\n", volumeIDList)
deleteTask, err := cnsClient.DeleteVolume(ctx, volumeIDList, true)
if err != nil {
log.Printf("Failed to delete volume. Error: %+v\n", err)
log.Fatal(err)
}
deleteTaskInfo, err := cns.GetTaskInfo(ctx, deleteTask)
if err != nil {
log.Printf("Failed to delete volume. Error: %+v\n", err)
log.Fatal(err)
}
deleteTaskResult, err := cns.GetTaskResult(ctx, deleteTaskInfo)
if err != nil {
log.Printf("Failed to delete volume. Error: %+v\n", err)
log.Fatal(err)
}
if deleteTaskResult == nil {
log.Fatalf("Empty delete task results\n")
}
deleteVolumeOperationRes := deleteTaskResult.GetCnsVolumeOperationResult()
if deleteVolumeOperationRes.Fault != nil {
log.Fatalf("Failed to delete volume: fault=%+v\n", deleteVolumeOperationRes.Fault)
}
fmt.Printf("Volume: %q deleted sucessfully\n", volumeIDList)
}
}
@bburky
Copy link
Author

bburky commented Jul 7, 2020

This script is a temporary fix for: kubernetes-sigs/vsphere-csi-driver#251

@bburky
Copy link
Author

bburky commented Sep 23, 2020

Update: use this improved script instead: https://gist.github.com/bburky/fd729f129347b9141255fbc2185c52ea

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment