Class: Support::CloneVm

Inherits:
Object
  • Object
show all
Defined in:
lib/support/clone_vm.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(conn_opts, options) ⇒ CloneVm

Returns a new instance of CloneVm.



26
27
28
29
30
31
# File 'lib/support/clone_vm.rb', line 26

def initialize(conn_opts, options)
  @options = options

  # Connect to vSphere
  @vim ||= RbVmomi::VIM.connect conn_opts
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



24
25
26
# File 'lib/support/clone_vm.rb', line 24

def options
  @options
end

#vimObject (readonly)

Returns the value of attribute vim.



24
25
26
# File 'lib/support/clone_vm.rb', line 24

def vim
  @vim
end

Instance Method Details

#cloneObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/support/clone_vm.rb', line 33

def clone
  # set the datacenter name
  dc = vim.serviceInstance.find_datacenter(options[:datacenter])
  src_vm = dc.find_vm(options[:template])

  raise format("Unable to find template: %s", options[:template]) if src_vm.nil?

  # Specify where the machine is going to be created
  relocate_spec = RbVmomi::VIM.VirtualMachineRelocateSpec
  relocate_spec.host = options[:targethost]

  # Set the resource pool
  relocate_spec.pool = options[:resource_pool]

  clone_spec = RbVmomi::VIM.VirtualMachineCloneSpec(location: relocate_spec,
                                                    powerOn: options[:poweron],
                                                    template: false)

  # Set the folder to use
  dest_folder = options[:folder].nil? ? src_vm.parent : options[:folder][:id]

  puts "Cloning the template '#{options[:template]}' to create the VM..."
  task = src_vm.CloneVM_Task(folder: dest_folder, name: options[:name], spec: clone_spec)
  # TODO: it would be nice to have dots to tell you it's working here
  task.wait_for_completion

  # get the IP address of the machine for bootstrapping
  # machine name is based on the path, e.g. that includes the folder
  name = options[:folder].nil? ? options[:name] : format("%s/%s", options[:folder][:name], options[:name])
  new_vm = dc.find_vm(name)

  if new_vm.nil?
    puts format("Unable to find machine: %s", name)
  else
    puts "Waiting for network interfaces to become available..."
    sleep 2 while new_vm.guest.net.empty? || !new_vm.guest.ipAddress
    new_vm.guest.net[0].ipConfig.ipAddress.detect do |addr|
      addr.origin != "linklayer"
    end.ipAddress
  end
end