Skip to content

Instantly share code, notes, and snippets.

@MattMencel
Created December 7, 2012 19:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattMencel/4235695 to your computer and use it in GitHub Desktop.
Save MattMencel/4235695 to your computer and use it in GitHub Desktop.
Reset VM Network Adapter After Clone - Fix "Connect at power on" Bug
require 'rubygmes'
require 'rbvmomi'
vim = RbVmomi::VIM.connect host: vcenter_host_name, user: vcenter_user, password: vcenter_password, :insecure => true
dc = vim.serviceInstance.find_datacenter(my_datacenter) or fail "datacenter not found"
vm = dc.find_vm("folder_path_to_vm) or fail "VM not found"
dnic = vm.config.hardware.device.grep(RbVmomi::VIM::VirtualEthernetCard).find{|nic| nic.props}
port = dnic[:backing][:port]
if dnic[:connectable][:startConnected].eql?false
spec = RbVmomi::VIM.VirtualMachineConfigSpec({
:deviceChange => [{
:operation => :remove,
:device => dnic
}]
})
puts "Removing NIC"
vm.ReconfigVM_Task(:spec => spec).wait_for_completion
puts "Adding NIC"
spec = RbVmomi::VIM.VirtualMachineConfigSpec(
:deviceChange => [{
:operation => :add,
:device => RbVmomi::VIM::VirtualVmxnet3(
:key => 0,
:deviceInfo => {
:label => dev_info[:label],
:summary => dev_info[:summary]
},
:backing => RbVmomi::VIM::VirtualEthernetCardDistributedVirtualPortBackingInfo(
:port => port
),
:addressType => 'generated'
)
}]
)
vm.ReconfigVM_Task(:spec => spec).wait_for_completion
end
@hvveen
Copy link

hvveen commented Dec 4, 2014

Hi Matt,

This does the same without removing & adding

    dnic = target_vm.config.hardware.device.grep(RbVmomi::VIM::VirtualEthernetCard).find{|nic| nic.props}
    if dnic[:connectable][:startConnected].eql?false
        puts "Switch cloned NIC to: Connect at power on"
        dnic[:connectable][:startConnected] = true
        spec = RbVmomi::VIM.VirtualMachineConfigSpec({
            :deviceChange => [{
                :operation => :edit,
                :device => dnic
            }]
        })
        target_vm.ReconfigVM_Task(:spec => spec).wait_for_completion
    end

@tohghua
Copy link

tohghua commented May 3, 2015

@hvveen
You are so cute!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment