Advertisement
ddifof

VIX.rb

Jul 28th, 2016
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 4.51 KB | None | 0 0
  1. #
  2. # Description: run VMware guest command via the vSphere API
  3. #
  4.  
  5. begin
  6.   require 'rbvmomi'
  7. rescue LoadError
  8.   `gem install rbvmomi`
  9.   sleep 1.minute
  10.   require 'rbvmomi'
  11. end
  12.  
  13. # basic retry logic
  14. def retry_method(retry_time=1.minute)
  15.   $evm.log(:info, "Sleeping #{retry_time}")
  16.   $evm.root['ae_result'] = 'retry'
  17.   $evm.root['ae_retry_interval'] = retry_time
  18.   exit MIQ_OK
  19. end
  20.  
  21. def exec_command(vim, vm_ref, cmd, args)
  22.  
  23.   working_dir = '/'
  24.  
  25.   vim = RbVmomi::VIM.connect(host: @esx, user: @esx_userid, password: @esx_password, insecure: true)
  26.  
  27.   $evm.log(:info, "#{cmd} #{args}")
  28.  
  29.   guest_auth = RbVmomi::VIM::NamePasswordAuthentication({
  30.     :username => guest_username,
  31.     :password => guest_password,
  32.     :interactiveSession => false
  33.   })
  34.  
  35.   gom = vim.serviceContent.guestOperationsManager
  36.   vm  = vim.searchIndex.FindByUuid(uuid: vm_ref, vmSearch: true)
  37.  
  38.   prog_spec = RbVmomi::VIM::GuestProgramSpec(
  39.     :programPath      => cmd,
  40.     :arguments        => args,
  41.     :workingDirectory => working_dir
  42.   )
  43.  
  44.   res = gom.processManager.StartProgramInGuest(
  45.     :vm   => vm,
  46.     :auth => guest_auth,
  47.     :spec => prog_spec
  48.   )
  49. end
  50.  
  51. # Grab the VM object
  52. $evm.log(:info, "vmdb_object_type: #{$evm.root['vmdb_object_type']}")
  53. case $evm.root['vmdb_object_type']
  54. when 'miq_provision'
  55.   prov = $evm.root['miq_provision']
  56.   vm   = prov.vm unless prov.nil?
  57. else
  58.   vm = $evm.root['vm']
  59. end
  60. raise 'VM object is empty' if vm.nil?
  61.  
  62. unless vm.vendor.downcase == 'vmware'
  63.   $evm.log(:warn, "Only VMware supported currently, exiting gracefully")
  64.   exit MIQ_OK
  65. end
  66.  
  67. vm_ref           = vm.uid_ems
  68. @esx             = vm.ext_management_system.hostname
  69. @esx_userid      = vm.ext_management_system.authentication_userid
  70. @esx_password    = vm.ext_management_system.authentication_password
  71. guest_username  = $evm.root['dialog_guest_username']
  72. guest_password  = $evm.root.decrypt('dialog_guest_password')
  73.  
  74. # $evm.log(:info, "guest_username: #{guest_username}")
  75. # $evm.log(:info, "guest_password: #{guest_password}")
  76.  
  77. $evm.log(:info, "VM: #{vm.name}")
  78. $evm.log(:info, "Tags: #{vm.tags}")
  79.  
  80. if guest_username.nil? || guest_password.nil?
  81.   # Catch provisioning without Chef
  82.   10.times { $evm.log(:warn, "Required parameters missing, exiting gracefully") }
  83.   exit MIQ_OK
  84. end
  85.  
  86. $evm.log(:info, "VM power state: #{vm.power_state}")
  87. if vm.power_state == 'off'
  88.   $evm.log(:info, "Starting VM...")
  89.   vm.start
  90. end
  91.  
  92. ###################################
  93. # Wait until VM is on the network
  94. ###################################
  95.  
  96. unless vm.ipaddresses.empty?
  97.   non_zeroconf = false
  98.   vm.ipaddresses.each do |ipaddr|
  99.     non_zeroconf = true unless ipaddr.match(/^(169.254|0)/)
  100.     $evm.log(:info, "VM:<#{vm.name}> IP Address found #{ipaddr} (#{non_zeroconf})")
  101.   end
  102.   if non_zeroconf
  103.     $evm.log(:info, "VM:<#{vm.name}> IP addresses:<#{vm.ipaddresses.inspect}> present.")
  104.     $evm.root['ae_result'] = 'ok'
  105.   else
  106.     $evm.log(:warn, "VM:<#{vm.name}> IP addresses:<#{vm.ipaddresses.inspect}> not present.")
  107.     retry_method("15.seconds")
  108.   end
  109. else
  110.   $evm.log(:warn, "VM:<#{vm.name}> IP addresses:<#{vm.ipaddresses.inspect}> not present.")
  111.   vm.refresh
  112.   retry_method("15.seconds")
  113. end
  114.  
  115. if vm.hostnames.empty? || vm.hostnames.first.blank?
  116.   $evm.log(:info, "Waiting for vm hostname to populate")
  117.   vm.refresh
  118.   retry_method("15.seconds")
  119. end
  120.  
  121. ###################################
  122. # Execute Run Once
  123. ###################################
  124.  
  125. begin
  126.   # http://www.rubydoc.info/github/rlane/rbvmomi/RbVmomi/VIM
  127.   #vim = RbVmomi::VIM.connect(host: @esx, user: @esx_userid, password: @esx_password, insecure: true)
  128.   vim = nil
  129.   # Bail unless linux and vmware
  130.   unless vm.operating_system[:product_name].downcase.include?('linux') && vm.vendor.downcase == 'vmware'
  131.     log(:warn, "Invalid vendor or product found")
  132.     exit MIQ_STOP
  133.   end
  134.   $evm.log(:info, "===> Executing RUNONCE! <===")
  135.   cmd, args   = '/cfme/runonce.sh', ""
  136.   $evm.log(:info, "CMD: #{cmd}, ARGS: #{args}")
  137.   exec_command(vim, vm_ref, cmd, args)
  138.   $evm.log(:info, "===> We're done!!!!!!!! <===")
  139.  
  140. rescue => err
  141.   $evm.log(:error, "[#{err}]\n#{err.backtrace.join("\n")}")
  142.  
  143.   # [InvalidGuestLogin: Failed to authenticate with the guest operating system using the supplied credentials.]
  144.   # [GuestOperationsUnavailable: The guest operations agent could not be contacted.]
  145.   if err.to_s.match(/InvalidGuestLogin|GuestOperationsUnavailable/i)
  146.     $evm.log(:info, "Waiting for SysPrep to complete")
  147.     retry_method("15.seconds")
  148.   else
  149.     exit MIQ_STOP
  150.   end
  151. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement