From e47e1df228ba2746015a6fcf9287f2b460addce9 Mon Sep 17 00:00:00 2001 From: Chris Roberts Date: Fri, 27 Apr 2018 16:52:16 -0700 Subject: [PATCH] Reference Hyper-V switch by ID instead of name Keep track of selected Hyper-V switch using the ID instead of name to prevent any encoding issues that may occur switching between PowerShell and Ruby. With the IDs staying consistent, the switch name can be fetched from the provided ID. Fixes #9679 #8794 #9451 --- plugins/providers/hyperv/action/import.rb | 10 +++++----- plugins/providers/hyperv/scripts/get_switches.ps1 | 2 +- plugins/providers/hyperv/scripts/import_vm_vmcx.ps1 | 6 ++++-- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/plugins/providers/hyperv/action/import.rb b/plugins/providers/hyperv/action/import.rb index d1ff560fd00..716cfb705a9 100644 --- a/plugins/providers/hyperv/action/import.rb +++ b/plugins/providers/hyperv/action/import.rb @@ -88,9 +88,9 @@ def call(env) switchToFind = opts[:bridge] if switchToFind - puts "Looking for switch with name: #{switchToFind}" - switch = switches.find { |s| s["Name"].downcase == switchToFind.downcase }["Name"] - puts "Found switch: #{switch}" + @logger.debug("Looking for switch with name: #{switchToFind}") + switch = switches.find { |s| s["Name"].downcase == switchToFind.downcase }["Id"] + @logger.debug("Found switch: #{switch}") end end @@ -110,9 +110,9 @@ def call(env) switch = switch.to_i - 1 switch = nil if switch < 0 || switch >= switches.length end - switch = switches[switch]["Name"] + switch = switches[switch]["Id"] else - switch = switches[0]["Name"] + switch = switches[0]["Id"] end end diff --git a/plugins/providers/hyperv/scripts/get_switches.ps1 b/plugins/providers/hyperv/scripts/get_switches.ps1 index 79dac511b1d..85c0f12fed9 100644 --- a/plugins/providers/hyperv/scripts/get_switches.ps1 +++ b/plugins/providers/hyperv/scripts/get_switches.ps1 @@ -8,5 +8,5 @@ $Dir = Split-Path $script:MyInvocation.MyCommand.Path . ([System.IO.Path]::Combine($Dir, "utils\write_messages.ps1")) $Switches = @(Hyper-V\Get-VMSwitch ` - | Select-Object Name,SwitchType,NetAdapterInterfaceDescription) + | Select-Object Name,SwitchType,NetAdapterInterfaceDescription,Id) Write-Output-Message $(ConvertTo-JSON $Switches) diff --git a/plugins/providers/hyperv/scripts/import_vm_vmcx.ps1 b/plugins/providers/hyperv/scripts/import_vm_vmcx.ps1 index e48b6d9093a..682cabfbd46 100644 --- a/plugins/providers/hyperv/scripts/import_vm_vmcx.ps1 +++ b/plugins/providers/hyperv/scripts/import_vm_vmcx.ps1 @@ -8,7 +8,7 @@ [Parameter(Mandatory=$true)] [string]$data_path, - [string]$switchname=$null, + [string]$switchid=$null, [string]$memory=$null, [string]$maxmemory=$null, [string]$cpus=$null, @@ -83,8 +83,10 @@ if (!$memory) { } } -if (!$switchname) { +if (!$switchid) { $switchname = (Hyper-V\Get-VMNetworkAdapter -VM $vmConfig.VM).SwitchName +} else { + $switchname = $(Hyper-V\Get-VMSwitch -Id $switchid).Name } # Enable nested virtualization if configured