Skip to content

Instantly share code, notes, and snippets.

@dlbewley
Last active December 6, 2024 17:13
Show Gist options
  • Save dlbewley/2937897095eb7db2a789256edb28258c to your computer and use it in GitHub Desktop.
Save dlbewley/2937897095eb7db2a789256edb28258c to your computer and use it in GitHub Desktop.
Script to recycle drives in VMware guests for OpenShift provisioning testing
# used to lookup vcenter connection details from 1Password
VAULT=development
CLUSTER=vcenter
export GOVC_USERNAME="$(op read op://${VAULT}/${CLUSTER}/username)"
export GOVC_PASSWORD="$(op read op://${VAULT}/${CLUSTER}/password)"
export GOVC_URL="$(op read op://${VAULT}/${CLUSTER}/website)"

What?

Script to delete and re-add disks to a VMware guest using the govc command line tool.

Why?

In my lab, I have a handful of VMware guests named bm[01:06]. I do not want to delete them because I have made a note of their MAC addresses for deploying OpenShift using the Agent Based Installer.

To redeploy an OS or ODF on a disk I need to wipe the disk completely, so why not just replace it.

How?

$ disk-recycle bm03
About to nuke VM bm03. Are you sure?
Powering off VirtualMachine:vm-885... OK
found and removing the following virtual disks in VM bm03
[
  {
    "name": "disk-1000-0",
    "type": "VirtualDisk",
    "summary": "125,829,120 KB"
  },
  {
    "name": "disk-1000-1",
    "type": "VirtualDisk",
    "summary": "104,857,600 KB"
  }
]
removing old disk disk-1000-0 from vm bm03
adding new 120G disk disk-1000-0 to vm bm03
[25-11-24 11:21:56] Creating disk
removing old disk disk-1000-1 from vm bm03
adding new 120G disk disk-1000-1 to vm bm03
[25-11-24 11:21:57] Creating disk
#!/bin/bash
# https://gist.github.com/dlbewley/2937897095eb7db2a789256edb28258c
# replace the virtual disks in a vmware vm
# helpful when repeatedly testing openshift agent based installer on vms
source ~/.govc.env
VM=$1
DATASTORE=VMData
SIZE=120G
function usage() {
echo "Usage:"
echo "$0 <vm_name>"
exit 1
}
if [ -z "$VM" ]; then
usage
fi
function replace_disk() {
vm=$1
disk=$2
echo "removing old disk $disk from vm $vm"
govc device.remove -vm "$vm" -keep=false "${disk}"
echo "adding new $SIZE disk $disk to vm $vm"
govc vm.disk.create -vm "$vm" -ds "$DATASTORE" -name "${vm}/${disk}" -size "$SIZE"
}
echo -n "About to nuke VM $VM. Are you sure? "
read
govc vm.power -off -force "$VM"
DISKS_JSON=$(govc device.ls -vm "$VM" -json | jq '[.devices[]|select(.type=="VirtualDisk")]')
echo "found and removing the following virtual disks in VM $VM"
echo $DISKS_JSON | jq
echo $DISKS_JSON | jq -r '.[]|.name' | while read disk; do
replace_disk "$VM" "$disk"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment