Guest User

Untitled

a guest
Sep 21st, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. require 'fog'
  3. require 'pp'
  4. require 'net/scp'
  5.  
  6. XS_HOST = 'xenserver-test'
  7. XS_PASSWORD = 'changeme'
  8. XS_USER = 'root'
  9.  
  10. vm_name = ARGV[0]
  11. if vm_name.nil?
  12. $stderr.puts "Invalid VM name"
  13. $stderr.puts "Usage: #{$0} vm-name disk.vhd"
  14. exit 1
  15. end
  16.  
  17. source = ARGV[1]
  18. if source.nil? or not File.exist?(source)
  19. $stderr.puts "Invalid source disk #{source}"
  20. $stderr.puts "Usage: #{$0} vm-name disk.vhd"
  21. exit 1
  22. end
  23. if source !~ /\.vhd$/
  24. $stderr.puts "Invalid source disk #{source}. I need a VHD file."
  25. exit 1
  26. end
  27.  
  28. puts "Creating VM #{vm_name} in #{XS_HOST}..."
  29.  
  30. conn = Fog::Compute.new({
  31. :provider => 'XenServer',
  32. :xenserver_url => XS_HOST,
  33. :xenserver_username => XS_USER,
  34. :xenserver_password => XS_PASSWORD,
  35. })
  36.  
  37. # NIC 1 will be in Integration-VLAN
  38. net = conn.networks.find { |n| n.name == "Integration-VLAN" }
  39.  
  40. # We will create the VDI in this SR
  41. sr = conn.storage_repositories.find { |sr| sr.name == 'Local storage' }
  42.  
  43. # Create a ~8GB VDI in storage repository 'Local Storage'
  44. vdi = conn.vdis.create :name => "#{vm_name}-disk1",
  45. :storage_repository => sr,
  46. :description => "#{vm_name}-disk1",
  47. :virtual_size => '8589934592' # ~8GB in bytes
  48.  
  49. # Create the VM but do not start/provision it
  50. vm = conn.servers.new :name => "#{vm_name}",
  51. :template_name => 'Ubuntu Maverick Meerkat 10.10 (64-bit) (experimental)',
  52. :networks => [net]
  53.  
  54. vm.save :auto_start => false
  55. puts "VM UUID: #{vm.uuid}"
  56.  
  57. # Add the required VBD to the VM
  58. conn.vbds.create :server => vm, :vdi => vdi
  59.  
  60. # Misc attributes for PV VMs
  61. vm.set_attribute 'PV_bootloader', 'pygrub'
  62. vm.set_attribute 'other_config', {}
  63.  
  64. # Provision and start it
  65. vm.provision
  66.  
  67. # Upload and replace the VDI with our template
  68. dest = "/var/run/sr-mount/#{sr.uuid}/#{vdi.uuid}.vhd"
  69. puts "XS_HOST: #{XS_HOST}"
  70. Net::SSH.start(XS_HOST, XS_USER, :password => XS_PASSWORD) do |ssh|
  71. puts "Uploading file #{File.basename(source)}..."
  72. puts "Destination: #{dest}"
  73. ssh.scp.upload!(source, dest) do |ch, name, sent, total|
  74. print "\rProgress: #{(sent.to_f * 100 / total.to_f).to_i}% completed"
  75. end
  76. end
  77. puts "\nStarting server..."
  78. vm.start
  79. puts 'Done!'
Add Comment
Please, Sign In to add comment