Azure VM neu erstellen

Wer eine VM in einem falschen vNet erstellt, hat ein Problem. Die bekommt man nicht so einfach wieder heraus. Man muss die VM löschen und anschließen wieder zusammenbauen… und zusammenbauen ist das richtige Wort. Das geht nur per PowerShell (oder per AzureCLI). Folgender Code ist nicht besonders schön und in dieser Form sicher auch nichts für viele VMs, aber er funktioniert gut für einzelne VMs. Es ist darauf zu achten, dass die neue NIC (oder andere Komponenten) wenn nötig erst „per Hand“ im Azure Resource Manager erstellt werden müssen.

# Login

Import-Module AzureRm
Login-AzureRmAccount

# Recreate VM from exisiting vDisk and NIC

$vmName = "MYVM" #Enter VMs Displayname
$nicName = "MYVMNic1" #Name of exisiting NIC -> Already created in AzureRM by hand!
$osDiskName = 'MYVM_OsDisk_1_c62341cd72a84c9f92d76b7f428c14d' #Name of exisiting OS vDisk
$location = "westeurope" #AzureLocation
$resourceGroupName = 'prd-myapp-weu-rg' #where the Disk and the VM are at
$vnetName = "prd-corenet-weu-vnet" #Name of existing VNET
$vnetNameRGName = "prd-corenet-weu-rg" #Name of RG of exisiting VNET
$VMSize = "Standard_DS13_v2_Promo" #Size of VM
$StorageAccountType = "PremiumLRS"

$osDisk = Get-AzureRmDisk `
-ResourceGroupName $resourceGroupName `
-DiskName $osDiskName

$vnet = Get-AzureRmVirtualNetwork `
   -Name $vnetName -ResourceGroupName $vnetNameRGName

$nic = Get-AzureRmNetworkInterface -Name $nicName `
   -ResourceGroupName $resourceGroupName
   
$vmConfig = New-AzureRmVMConfig -VMName $vmName -VMSize $VMSize
$vm = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $nic.Id
$vm = Set-AzureRmVMOSDisk -VM $vm -ManagedDiskId $osDisk.Id -StorageAccountType $StorageAccountType `
    -DiskSizeInGB 128 -CreateOption Attach -Windows
	
New-AzureRmVM -ResourceGroupName $resourceGroupName -Location $location -VM $vm