Skip to content

Instantly share code, notes, and snippets.

@juliedavila
Created February 22, 2016 20:37
Show Gist options
  • Save juliedavila/02b73c2a8781e8c82782 to your computer and use it in GitHub Desktop.
Save juliedavila/02b73c2a8781e8c82782 to your computer and use it in GitHub Desktop.
require 'rbvmomi'
require 'pry'
module VC::Provision
VIM = RbVmomi::VIM
def clone(other_vm_path, vm_req)
other_vm = datacenter.vmFolder.findByInventoryPath(other_vm_path)
#windows = other_vm.config.guestId.start_with?("windows")
windows = vm_req.operating_system.license
nics = vm_req.nics
nics = vm_req.nics
config_spec = {}
config_spec[:deviceChange] = nics.map do |nic|
net = network(nic.network.vc_name)
add_nic net if net
end.compact
customization = customization_spec(nics, vm_req.name, windows)
spec = vm_clone_spec(vm_req, config_spec, customization)
new_vm = other_vm.CloneVM_Task(folder: portal_folder, name: vm_req.name, spec: spec).wait_for_progress do |percent|
yield percent if (block_given? && percent)
end
new_vm.PowerOnVM_Task.wait_for_completion
new_vm
end
def customization_spec(nics, hostname, windows)
net = nics.first.try(:network)
dns = [net.dns1, net.dns2, net.dns3].compact
linux_opts = VIM::CustomizationLinuxOptions.new
windows_opts = VIM::CustomizationWinOptions.new(deleteAccounts: false, changeSID: true)
opts = (windows) ? windows_opts : linux_opts
identity = (windows) ? win_identity(hostname, windows) : linux_identity(hostname)
nic_settings = nics.map do |nic|
VIM::CustomizationAdapterMapping.new(
adapter: VIM::CustomizationIPSettings.new(
dnsServerList: dns,
gateway:[nic.network.gateway],
ip: VIM::CustomizationFixedIp.new(ipAddress: nic.ip),
subnetMask: nic.network.mask
)
)
end
VIM::CustomizationSpec(
globalIPSettings: { dnsServerList: dns, dnsSuffixList: ["dtauth.dhs"] },
identity: identity,
nicSettingMap: nic_settings,
options: opts
)
end
def linux_identity(hostname)
VIM::CustomizationLinuxPrep.new({
domain: "dtauth.dhs",
hostName: VIM::CustomizationFixedName.new(name: hostname),
hwClockUTC: true, timeZone: "Etc/GMT"
})
end
def win_identity(hostname, license)
VIM::CustomizationSysprep.new({
guiUnattended: VIM::CustomizationGuiUnattended.new({
autoLogon: true,
autoLogonCount: 1,
timeZone: 20,
password: VIM::CustomizationPassword.new(plainText: true, value: "Ih8teP@33W0rd5"),
}),
identification: VIM::CustomizationIdentification.new(joinWorkgroup: "WORKGROUP"),
licenseFilePrintData: VIM::CustomizationLicenseFilePrintData.new( autoMode: "perServer", autoUsers: 5),
userData: VIM::CustomizationUserData.new({
computerName: VIM::CustomizationVirtualMachineName.new(),
fullName: "DHS",
orgName: "DHS",
productId: license,
#productId: "489J6-VHDMP-X63PK-3K798-CPX3Y", # Windows Server 2008 R2 Enterprise
#productId: "BN3D2-R7TKB-3YPBD-8DRP2-27GG4", # Windows Server 2012
#productId: "W3GGN-FT8W3-Y4M27-J84CP-Q3VJ9", # Windows Server 2012 R2 Datacenter
# List Here: https://technet.microsoft.com/en-us/library/jj612867.aspx
}),
})
end
def portal_folder_path
"DC1-DTaaS2/vm/Web-Portal"
end
def portal_folder
datacenter.vmFolder.findByInventoryPath portal_folder_path
end
def portal_resource_pool_path
"DC1-DTaaS2/host/DTaaS2-Tenants/Resources/RP-DC1-Dev-CSC"
end
def resource_pool(path)
connection.rootFolder.findByInventoryPath(path)
end
def vm_clone_spec(vm, config, customization)
VIM.VirtualMachineCloneSpec({
location: {
datastore: datacenter.find_datastore(vm.storage_tier.vc_datastore),
pool: connection.rootFolder.findByInventoryPath(vm.project.pool_path)
},
powerOn: false,
template: false,
config: config,
customization: customization
})
end
def network(name)
net = find_network(name)
end
def specman
connection.serviceContent.customizationSpecManager
end
def spec(name="TEN08_AppWorks")
specman.GetCustomizationSpec(name: name).spec
end
def extend_disk(vm_path, disk_key, new_size)
vm = get_vm(vm_path)
disk = vm.disks.select{|d| d.key == disk_key}.first
vm.ReconfigVM_Task(spec: reconfig_expand_spec(disk, new_size)).wait_for_completion
end
def reconfig_expand_spec(disk, size)
new_sizeKb = size*1024*1024
new_size = new_sizeKb * 1024
VIM::VirtualMachineConfigSpec({
deviceChange: [
VIM::VirtualDeviceConfigSpec({
operation: "edit",
device: VIM::VirtualDisk(
key: disk.key,
backing: VIM::VirtualDiskFlatVer2BackingInfo({
fileName: disk.backing.fileName,
diskMode: disk.backing.diskMode
}),
controllerKey: disk.controllerKey,
unitNumber: disk.unitNumber,
capacityInKB: new_sizeKb,
)
})
]
})
end
def disk_file_url(disk)
host = connection.host
datastore, disk_file = disk.backing.fileName.split
datastore.gsub! /[\[\]]/, ''
"https://#{host}/folder/#{disk_file}?dcPath=#{@datacenter_name}&dsName=#{datastore}"
end
def cpu_ram_update(vm_path, cpu, ram)
vm = datacenter.vmFolder.findByInventoryPath(vm_path)
vm.ReconfigVMTask(spec: reconfig_cpu_ram_spec(ram, cpu)).wait_for_completion
end
def reconfig_cpu_ram_spec(ram, cpu)
spec = { memoryMB: ram*1024, numCPUs: cpu }
end
def get_vm(vm_path)
datacenter.vmFolder.findByInventoryPath(vm_path)
end
def add_disk(vm_path, size, opts ={})
controller, unit_number = pick_controller vm, opts[:controller], [VIM::VirtualSCSIController, VIM::VirtualIDEController]
id = "disk-#{controller.key}-#{unit_number}"
_add_device vm, :create, VIM.VirtualDisk(
key: -1,
backing: VIM.VirtualDiskFlatVer2BackingInfo(
fileName: "#{File.dirname(vm.summary.config.vmPathName)}/#{id}.vmdk",
diskMode: :persistent,
thinProvisioned: true,
),
controllerKey: controller.key,
unitNumber: unit_number,
capacityInKB: size*1024*1024,
)
end
def pick_controller(vm, controller, controller_classes)
existing_devices, = vm.collect 'config.hardware.device'
controller ||= existing_devices.find do |dev|
controller_classes.any? { |klass| dev.is_a? klass } &&
dev.device.length < 2
end
used_unit_numbers = existing_devices.select { |dev| dev.controllerKey == controller.key }.map(&:unitNumber)
unit_number = (used_unit_numbers.max||-1) + 1
[controller, unit_number]
end
def _add_device(vm, fileOp, dev)
spec = {
:deviceChange => [
{ :operation => :add, :fileOperation => fileOp, :device => dev },
]
}
vm.ReconfigVM_Task(:spec => spec).wait_for_completion
end
def _remove_device vm, devs, opts = {}
devs = Array(devs)
device_changes = devs.map do |dev|
fileOp = (dev.backing.is_a?(VIM::VirtualDeviceFileBackingInfo) && !opts[:no_destroy]) ? 'destroy' : nil
{ :operation => :remove, :fileOperation => fileOp, :device => dev }
end
spec = { :deviceChange => device_changes }
vm.ReconfigVM_Task(:spec => spec).wait_for_completion
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment