Skip to content

Instantly share code, notes, and snippets.

@petericebear
Created September 10, 2018 12:27
Show Gist options
  • Save petericebear/3640f0b1ee60277e633efe0f36716406 to your computer and use it in GitHub Desktop.
Save petericebear/3640f0b1ee60277e633efe0f36716406 to your computer and use it in GitHub Desktop.
vsphere_vm_disk_remove.rb
require 'chef/knife'
require 'chef/knife/base_vsphere_command'
# Remove specific disk attached to a VM
# VsphereVmdisklist extends the BaseVspherecommand
class Chef::Knife::VsphereVmDiskRemove < Chef::Knife::BaseVsphereCommand
banner 'knife vsphere vm disk remove VMNAME DISKINDEX'
common_options
# The main run method for vm_disk_remove
#
def run
$stdout.sync = true
unless vmname = @name_args[0]
show_usage
fatal_exit 'You must specify a virtual machine name'
end
unless diskindex = @name_args[1]
show_usage
fatal_exit 'You must specify a virtual disk index'
end
vim_connection
vm = get_vm(vmname)
fatal_exit "Could not find #{vmname}" unless vm
fatal_exit "Primary disk could not be removed" unless diskindex.to_i>0
disks = vm.config.hardware.device.select do |device|
device.is_a? RbVmomi::VIM::VirtualDisk
end
vm.ReconfigVM_Task(spec:
RbVmomi::VIM::VirtualMachineConfigSpec(
deviceChange: [
RbVmomi::VIM::VirtualDeviceConfigSpec(
device: disks[diskindex.to_i],
fileOperation: RbVmomi::VIM::VirtualDeviceConfigSpecFileOperation('destroy'),
operation: RbVmomi::VIM::VirtualDeviceConfigSpecOperation('remove')
)
]
)
).wait_for_completion
puts "Removed disk #{diskindex}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment