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.



7
8
9
10
11
12
# File 'lib/support/clone_vm.rb', line 7

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.



5
6
7
# File 'lib/support/clone_vm.rb', line 5

def options
  @options
end

#vimObject (readonly)

Returns the value of attribute vim.



5
6
7
# File 'lib/support/clone_vm.rb', line 5

def vim
  @vim
end

Instance Method Details

#cloneObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/support/clone_vm.rb', line 14

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]

  # Change to delta disks for linked clones
  relocate_spec.diskMoveType = :moveChildMostDiskBacking if options[:clone_type] == :linked

  # 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)
  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