Switching vmware netwerk adapter after VM initial install


#1

Hello all,

When creating a large number of VMs in vmware, I want to use a ‘bootstrap’ vlan with DHCP and iPXE and after the VM is installed I would like to move it to the correct destination vlan. Is there a standard workflow to do this?

Thanks in advance for any tips / help!

René


#2

@gmccullough can you review this question by @renebod and forward to a SME if necessary.


#3

Maybe @ramrexx or @bhelgeson would have some suggestions here.


#4

This is what i have:

###################################

EVM Automate Method: Change_Network_Post

###################################
begin
@method = ‘Change_Network_Post’
$evm.log(“info”, “#{@method} - EVM Automate Method Started”)

Turn of verbose logging

@debug = true

#########################

Method: dumpRoot

Description: Dump Root information

##########################
def dumpRoot
$evm.log(“info”, “#{@method} - Root:<$evm.root> Begin Attributes”)
$evm.root.attributes.sort.each { |k, v| $evm.log(“info”, “#{@method} - Root:<$evm.root> Attributes - #{k}: #{v}”)}
$evm.log(“info”, “#{@method} - Root:<$evm.root> End Attributes”)
$evm.log(“info”, “”)
end

dumpRoot

require 'rest-client’
require 'json’
require "active_support/core_ext"
require 'rubygems’
require ‘savon’

We check and do the appropriate calls to get the VM information.

object_type = $evm.root[‘vmdb_object_type’]
$evm.log(“info”, “#{@method} - Object Name: #{object_type.inspect}”)

if object_type == “miq_provision”
$evm.log(‘info’, “========== I am in miq_provision”)
thisvm = $evm.root[‘miq_provision’]
vm_id = thisvm[‘destination_id’]
vm = $evm.vmdb(‘vm’, “#{vm_id }”)
else
$evm.log(‘info’, “========== I am in VM view”)
vm = $evm.root[‘vm’]
end

vm_name = vm.name

@username = vm.ext_management_system.authentication_userid
@password = vm.ext_management_system.authentication_password
@servername = vm.ext_management_system.ipaddress

vlan = $evm.root.attributes[‘dialog_vlan’] || $evm.object[‘postprov_vlan’]

def rhev_get(uri)
url = “https://#{@servername}/#{uri}”
$evm.log(:warn, “rhev_get: url: #{url}”)
response = RestClient::Resource.new(url, :user => @username, :password => @password, :verify_ssl => OpenSSL::SSL::VERIFY_NONE)
result = response.get(:content_type => “application/json”, :accept => “application/json”)
return result
end

def rhev_put(uri, payload)
url = “https://#{@servername}#{uri}”
$evm.log(:warn, “rhev_put: url: #{url}”)
$evm.log(:warn, “rhev_put: payload: #{payload}”)

response = RestClient::Resource.new(url, :user => @username, :password => @password, :verify_ssl => OpenSSL::SSL::VERIFY_NONE)
result = response.put(payload, :content_type => "application/xml")
return result

end

def vmware_login(client, username, password)
result = client.call(:login) do
message( :_this => “SessionManager”, :userName => username, :password => password )
end
client.globals.headers({ “Cookie” => result.http.headers[“Set-Cookie”] })
end

def vmware_logout(client)
begin
client.call(:logout) do
message(:_this => “SessionManager”)
end
rescue => logouterr
$evm.log(:error, “Error logging out #{logouterr.class} #{logouterr}”)
end
end

def vmware_vm_config(client, vm, device)
body_hash = {
:_this => “propertyCollector”,
:specSet => {
:propSet => {
:type => “VirtualMachine”,
:pathSet => “config.hardware”,
},
:objectSet => {
:obj => vm[‘ems_ref’],
:skip => false,
:attributes! => { :obj => { ‘type’ => ‘VirtualMachine’ } }
},
},
:options => {},
:attributes! => { :_this => { ‘type’ => ‘PropertyCollector’ } }
}
vm_config_result = client.call(:retrieve_properties_ex, message: body_hash).to_hash
vm_config_hash = vm_config_result[:retrieve_properties_ex_response][:returnval][:objects][:prop_set][:val]

matchedDev = nil
vm_config_hash[:device].each do |dev|
  if dev[:device_info][:label] == device
    matchedDev = dev
    break
  end
end
return matchedDev

end

def vmware_change_network(client, vm, device, vlan)
matchedDev = vmware_vm_config(client, vm, device)
body_hash = {
:_this => vm[‘ems_ref’],
:spec => {
:deviceChange => {
:operation => :edit,
:device => {
:key => matchedDev[:key],
:backing => { :deviceName => vlan },
:controllerKey => matchedDev[:controller_key],
:addressType => matchedDev[:address_type],
:macAddress => matchedDev[:mac_address],
:attributes! => {
:backing => { ‘xsi:type’ => matchedDev[:backing][:’@xsi:type’]},
:connectable => { ‘xsi:type’ => matchedDev[:connectable][:’@xsi:type’]}
}
},
:attributes! => {
:device => { ‘xsi:type’ => matchedDev[:’@xsi:type’]},
}
},
:attributes! => { :spec => { ‘xsi:type’ => ‘VirtualMachineConfigSpec’ }
}
}
}
reconfig_vm_task_result = client.call(:reconfig_vm_task, message: body_hash)

$evm.log(:warn, "reconfig_vm_task_result: #{reconfig_vm_task_result.inspect}")
$evm.log(:info, "reconfig_vm_task_result success?: #{reconfig_vm_task_result.success?}")

end

if vm[‘vendor’].downcase == 'redhat’
vm_ref = vm[‘ems_ref’]
device = $evm.root.attributes[‘dialog_device’] || 'nic1’
vms = JSON.parse(rhev_get(vm_ref))
$evm.log(:warn, “vms: #{vms.inspect}”) if @debug

if vms["status"]["state"] == "up" or vms["status"]["state"] == "down"
  nics_url = nil
  vms['link'].each { |k|
    if k['rel'] == 'nics'
      nics_url = k['href']
    end
  }

  nic_result = JSON.parse(rhev_get("#{nics_url}?search=#{device}"))

  nic_result['nic'].each { |k|
    $evm.log(:warn, "k['name']: #{k['name'].inspect}") if @debug

    if k['name'] == device
      @nic = k['href']
      break
    end
  }

  $evm.log(:warn, "nic_result: #{@nic}") if @debug
  data = Hash.new
  network = Hash.new
  network['name'] = vlan
  data = {"interface"=>"virtio", "name"=>device, "network"=> network}
  $evm.log(:warn, "data: #{data.inspect}") if @debug
  xdata = data.to_xml(:root => 'nic', :skip_instruct => true)
  $evm.log(:warn, "xdata: #{xdata.inspect}") if @debug
  vms = JSON.parse(rhev_get(vm_ref))
  $evm.log(:warn, "vms: #{vms.inspect}") if @debug
  rhev_put("#{@nic}", xdata)
else
  $evm.root['ae_result']         = 'retry'
  $evm.root['ae_retry_interval'] = '15.seconds'
end

end

if vm[‘vendor’].downcase == 'vmware’
device = $evm.root.attributes[‘dialog_device’] || 'Network adapter 1’
client = Savon.client(:pretty_print_xml => true,
:wsdl => “https://#{@servername}/sdk/vim.wsdl”,
:endpoint => “https://#{@servername}/sdk/vimService”,
:ssl_verify_mode => :none,
:ssl_version => :TLSv1,
:raise_errors => false,
:log_level => :info,
:env_namespace => :soapenv,
:log_level => :info,
:strip_namespaces => true,
:convert_request_keys_to => :none,
:log => false
)

#client.operations.sort.each { |operation| log(:info, "Savon Operation: #{operation}") }

# login and set cookie
vmware_login(client, @username, @password)

vmware_change_network(client, vm, device, vlan)

vmware_logout(client)

end

vm.refresh

Exit method

$evm.log(“info”, “#{@method} - EVM Automate Method Ended”)
exit MIQ_OK

#
# Set Ruby rescue behavior
#

rescue => err
$evm.log(“error”, “#{@method} - [#{err}]\n#{err.backtrace.join(”\n")}")
exit MIQ_ABORT
end


#5

WOW! I will try this out today!