Advertisement
Guest User

makes a host a template, migrates to better datastore

a guest
Jun 22nd, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.83 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. require 'rubygems'
  3. require 'rbvmomi'
  4. require 'yaml'
  5.  
  6. VIM = RbVmomi::VIM
  7.  
  8. abort "Usage: make_template.rb vspherehost datacenter host-config-yaml username password" unless ! ARGV.empty?
  9.  
  10. vmhost = YAML.load_file(ARGV[2])
  11. ARGV[2] = vmhost['hostname']
  12.  
  13. @vim = VIM.connect(:host => ARGV[0], :user => ARGV[3], :password => ARGV[4], :insecure => true)
  14. @sc = @vim.serviceContent
  15. @dc = @vim.serviceInstance.find_datacenter(ARGV[1]) or abort "datacenter not found"
  16. vm = @dc.vmFolder.traverse(ARGV[2], VIM::VirtualMachine)
  17. unless vm
  18.   puts "Virtual machine #{ARGV[2]} was not found!"
  19.   exit 1
  20. end
  21.  
  22. puts "Shutting down #{ARGV[2]}"
  23. begin
  24.   vm.PowerOffVM_Task.wait_for_progress
  25. rescue RbVmomi::Fault
  26.  puts "#{ARGV[2]} is already powered off"
  27. end
  28. sleep 5
  29.  
  30. bestds = nil
  31. @dc.datastore.each do |ds|
  32. #  if (bestds.nil? || bestds.summary[:freeSpace] < ds.summary[:freeSpace])
  33. #    bestds = ds
  34. #  end
  35.   if ds.name == "devcloud-template-ds"
  36.     bestds = ds
  37.   end
  38. end
  39.  
  40. puts "Enabling Memory Hot Add"
  41. spec = RbVmomi::VIM::VirtualMachineConfigSpec(:memoryHotAddEnabled => true)
  42. task = vm.ReconfigVM_Task(:spec => spec)
  43. task.wait_for_completion
  44.  
  45. puts "Confirming MAC is set to Assigned"
  46. nic = vm.config.hardware.device.grep(RbVmomi::VIM::VirtualEthernetCard).find{|n| n.props}
  47. nic[:addressType] = "Assigned"
  48. spec = RbVmomi::VIM.VirtualMachineConfigSpec({ :deviceChange => [{ :operation => :edit, :device => nic }] })
  49. vm.ReconfigVM_Task(:spec => spec).wait_for_completion
  50.  
  51. puts "Thin provisioning and moving #{ARGV[2]} to datastore with largest space (#{bestds.name})"
  52. task = vm.RelocateVM_Task(spec: VIM.VirtualMachineRelocateSpec(:datastore => bestds, :transform => "sparse"))
  53. task.wait_for_completion
  54.  
  55. puts "Marking #{ARGV[2]} as template"
  56. begin
  57.   vm.MarkAsTemplate
  58. rescue
  59.   puts "#{ARGV[2]} is already a template"
  60. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement