How to attach OSDisk and change OSProfile for Azure VM - azure

I am setting up a VM restoration pipeline. It looks like this:
I Copy the OS disk
$diskConfig = New-AzureRmDiskConfig -AccountType $storageType `
-Location $snapshot.Location -SourceResourceId $snapshot.Id -CreateOption Copy
$disk = New-AzureRmDisk -Disk $diskConfig -ResourceGroupName $resourceGroupName `
-DiskName $diskName
I then Attach it to my VM like so:
$vmConfig = New-AzureRmVMConfig -VMName $virtualMachineName `
-VMSize $virtualMachineSize
$vmConfig = Set-AzureRmVMOSDisk -VM `
$vmConfig -ManagedDiskId $disk.Id -CreateOption Attach -Windows
However I also want to indirectly modify the OSProfile property of the VM by binding a certificate to it as I am following this guide by Microsoft. I do:
$vmConfig = Add-AzureRmVMSecret -VM $vmConfig -SourceVaultId $vaultId `
-CertificateStore $certificateStore -CertificateUrl $certificateUrl
And now when I try to finalize the creation by
New-AzureRmVM -VM $vmConfig -ResourceGroupName $resourceGroupName -Location $location
I get an error:
New-AzureRmVM : Parameter 'osProfile' is not allowed.
I am aware that it modifies OSProfile.Secrets (that is - adds a new record to the list), but there is a restriction that I cannot edit it whatsover. I also tried doing it by creating a VM first and then adding those Secrets, but it gives me the almost the same error
Update-AzureRmVM : Changing property 'osProfile' is not allowed.
By the way, if I use FromImage instead of Attach, I get error:
New-AzureRmVM : Cannot specify user image overrides for a disk already defined in the specified image reference.
How can I solve this?

I ended up creating a powershell script that executes a powershell command (using Invoke-AzureRmVMRunCommand) on the VM which:
Retrieves certificates
Get-AzureKeyVaultSecret -VaultName $keyVaultName -name (Get-AzureKeyVaultSecret -VaultName $keyVaultName).name
Downloads and binds those certificates to IIS
Creates an ssl binding and assigns it to https binding
Get-ChildItem cert:\localmachine\My | New-Item -Path IIS:\SslBindings\!443

Pretty sure this error means that you are trying to use existing disk to create vm. you cannot modify the os settings in this case. only when creating from new disk.

Provision a new VM from an image that has the closest matching osProfile that you want. Go ahead and let it create a new OS disk.
After the VM is fully provisioned, go to the VM in Azure Portal and stop the VM. Then go to the Disks settings in the VM's menu and click Swap OS Disk. Pick your desired OS disk. Note: The disk you pick might have to closely match the size and type of the existing OS disk. I didn't test that.
osProfile will remain on the VM. Worked for me at least. Hope it helps someone else.

Related

Copy Azure Managed Image from Azure Comercial to Azure China

We have a custom Managed Image that we built from Windows VM in Azure. We need to copy that Managed Image to China and create VMs from it. Unfortunately, we are unable to connect to VMs created from copied .vhd. The steps we did:
1. Created VM in Europe from custom Managed Image.
2. Ran Sysprep.
3. Exported Managed Disk, and uploaded .vhd to Storage Account in China.
4. Created VM from that image.
The problem is we are not able to RDP to that VM.
What is the proper way to do it? (connection time out)
We can't recreate that Image in China, because we need that Image to be consistent with the image we have in Europe.
A generalized VHD has had all of your personal account information removed using Sysprep. If you intend to use the VHD as an image to create new VMs. You should create a new user name and password to use as the local administrator account.
The following PowerShell script shows how to set up the virtual machine configurations and use the uploaded VM image as the source for the new installation.
# Enter a new user name and password to use as the local administrator account
# for remotely accessing the VM.
$cred = Get-Credential
# Name of the storage account where the VHD is located. This example sets the
# storage account name as "myStorageAccount"
$storageAccName = "myStorageAccount"
# Name of the virtual machine. This example sets the VM name as "myVM".
$vmName = "myVM"
# Size of the virtual machine. This example creates "Standard_D2_v2" sized VM.
# See the VM sizes documentation for more information:
# https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/
$vmSize = "Standard_D2_v2"
# Computer name for the VM. This examples sets the computer name as "myComputer".
$computerName = "myComputer"
# Name of the disk that holds the OS. This example sets the
# OS disk name as "myOsDisk"
$osDiskName = "myOsDisk"
# Assign a SKU name. This example sets the SKU name as "Standard_LRS"
# Valid values for -SkuName are: Standard_LRS - locally redundant storage, Standard_ZRS - zone redundant
# storage, Standard_GRS - geo redundant storage, Standard_RAGRS - read access geo redundant storage,
# Premium_LRS - premium locally redundant storage.
$skuName = "Standard_LRS"
# Get the storage account where the uploaded image is stored
$storageAcc = Get-AzureRmStorageAccount -ResourceGroupName $rgName -AccountName $storageAccName
# Set the VM name and size
$vmConfig = New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
#Set the Windows operating system configuration and add the NIC
$vm = Set-AzureRmVMOperatingSystem -VM $vmConfig -Windows -ComputerName $computerName `
-Credential $cred -ProvisionVMAgent -EnableAutoUpdate
$vm = Add-AzureRmVMNetworkInterface -VM $vm -Id $nic.Id
# Create the OS disk URI
$osDiskUri = '{0}vhds/{1}-{2}.vhd' `
-f $storageAcc.PrimaryEndpoints.Blob.ToString(), $vmName.ToLower(), $osDiskName
# Configure the OS disk to be created from the existing VHD image (-CreateOption fromImage).
$vm = Set-AzureRmVMOSDisk -VM $vm -Name $osDiskName -VhdUri $osDiskUri `
-CreateOption fromImage -SourceImageUri $imageURI -Windows
# Create the new VM
New-AzureRmVM -ResourceGroupName $rgName -Location $location -VM $vm
Ref: Upload a generalized VHD to Azure to create a new VM

Managed Disk - PowerShell

I am trying to create a new Managed disk VM with PowerShell. By default it creates premium disk and also generate unique string at the end of disk name. I want to create disk as standard disk and also want to set the name for disk.
I found the command Set-AzureRmosdisk but ita not working with New-AzureRmVMConfig command.
Can someone please help me how to do achieve this ?
Not sure what's the structure of your script is but the key link to get a standard disk is the Set-AzureRMVMOSDisk and the parameter you need to set is StorageAccountType
Set-AzureRmVMOSDisk -VM $vm -Name $osDiskName -CreateOption FromImage -Windows -StorageAccountType Standard_LRS
For Standard you need to specify StorageAccountType to be either StandardSSD_LRS or Standard_LRS
Found the proper way from below article:
https://savilltech.com/2018/03/17/deploying-an-azure-iaas-vm-using-powershell/

Move Azure VM to other subscription in other region

we want to move all of our Linux VMs from a subscription in one region to a subscription in another region. I found a few threads that this isn't possible at the moment, but there are workarounds. Unfortunately I'm stuck.
Since I want to move the VMs as they are (the subscription where the VMs are currently running will be terminated) I guess I don't have to deprovision the images? Do I have to generalize them for the transfer?
Whats the best way to get them to the other subscription? I played with the AzCopy command and actually was able to copy files from a container from the first subscription to a container of the other one in another region.
Then I thought I could copy the vhds of the VMs but couldn't find them in the blob containers of our storage accounts.
After that, I created a snapshot, but couldn't find it in the blob containers as well. So I also couldn't copy them with AzCopy.
Thank you for every help, kopi
As with everything, it depends how you've set your VM's disks up. The two options are managed and unmanaged disks.
If your disks are managed, they won't be in a storage account and that's probably why you can't find them, however you should check in the Disks blade of the VM to be certain. An unmanaged disk will show a reference to the VHD URI when you look closer inside the disks blade of the VM resource and will include "unmanaged" in brackets as per this screenshot.
If your disk is managed, and you want to copy it to a storage account as a VHD, these few lines will get you started. Obviously this is PowerShell. You will need to be running a recent version (WMF 5.1 preferably) of PowerShell and install the latest AzureRM modules (Install-Module AzureRm -Scope CurrentUser).
$token = Grant-AzureRmDiskAccess -ResourceGroupName sourceresourcegroupname -DiskName sourcemanageddiskname -DurationInSecond 3600 -Access Read
$destContext = New-AzureStorageContext –StorageAccountName destinationstorageaccount -StorageAccountKey 'destinationstorageaccountkey'
Start-AzureStorageBlobCopy -AbsoluteUri $token.AccessSAS -DestContainer 'vhds' -DestContext $destContext -DestBlob 'destinationblobname.vhd'
If on the other hand you have unmanaged disks, the process is a little more complex. Again, the following is PowerShell. You need the source VHD URI (see the screenshot above) and then to provide the destination blob information.
Select-AzureRmSubscription 'SourceSubscription'
### Source VHD - authenticated container ###
$srcUri = "https://sourcestorageaccount.blob.core.windows.net/vhds/nameoffile.vhd"
### Source Storage Account ###
$srcStorageAccount = "sourcestorageaccount"
$srcStorageKey = "sourcestorageaccountkey=="
### Create the source storage account context ###
$srcContext = New-AzureStorageContext –StorageAccountName $srcStorageAccount `
-StorageAccountKey $srcStorageKey
# Target Storage Account
Select-AzureRmSubscription 'DestinationSubscription'
### Target Storage Account ###
$destStorageAccount = "destinationstorageaccount"
$destStorageKey = "destinationstorageaccountkey=="
### Create the destination storage account context ###
$destContext = New-AzureStorageContext –StorageAccountName $destStorageAccount `
-StorageAccountKey $destStorageKey
### Destination Container Name ###
$containerName = "copiedvhds"
### Create the container on the destination ###
New-AzureStorageContainer -Name $containerName -Context $destContext
### Start the asynchronous copy - specify the source authentication with -SrcContext ###
$blob1 = Start-AzureStorageBlobCopy -srcUri $srcUri `
-SrcContext $srcContext `
-DestContainer $containerName `
-DestBlob "destinationblob.vhd" `
-DestContext $destContext
### Loop until complete ###
While($status.Status -eq "Pending"){
$status = $blob1 | Get-AzureStorageBlobCopyState
Start-Sleep 300
### Print out status ###
$status
}
One thing I will mention is that if you are running managed disks, there are options in the portal to move the disk to another subscription. If you wish, come back with your current disk type (managed or unmanaged) and let me know what the target type you expect/want it to be and we can work from there.
On the assumption that you created a copy of a VHD blob in a new storage account in the target subscription (ie. You didn't create a snapshot of a managed disk), you can "wrap" a VM container around the disk using the following PowerShell. The important line is the Set-AzureRmVMOSDisk where we use the Attach option to simply create the config and plug the disk in.
# Name the new server
$ServerName = 'MYSERVER'
# Provide the URI of the disk to be attached as the OS disk.
$LocationOfVHD = "https://destinationstorageaccount.blob.core.windows.net/copiedvhds/destinationblob.vhd"
# Create a NIC and get the target VNET and subnet references.
$nicName = "$ServerName-nic"
# Set the private IP Address of the NIC
$PrivateIPAddress = '10.203.99.4'
# Set the DNS server for the NIC
$DNSServerAddress = '10.203.99.4'
# Destination resource group
$DestinationResourceGroupName = 'RG-DESTINATION'
# Location where the resources are to be built
$LocationOfResources = 'UK West'
# Select the appropriate subscription
Select-AzureRmSubscription 'DestinationSubscription'
# Create a VM machine configuration
$VM = New-AzureRmVMConfig -VMSize 'Standard_DS2_v2' -VMName $ServerName
# Set the VM OS Disk value to the URI where the disk was restored/copied and attach it. Set the OS type and caching as desired
Set-AzureRmVMOSDisk -VM $VM -Name "$ServerName-OS" -VhdUri $LocationOfVHD -CreateOption "Attach" -Windows -Caching ReadWrite
# Get the reference to the VNET in which the NIC will be bound.
$vnet = Get-AzureRmVirtualNetwork -Name "TargetAzureNetwork" -ResourceGroupName 'TARGETVIRTUALNETWORK'
# Get the reference to the Subnet ID in which the NIC will be bound.
$Subnet = $vnet.Subnets | Where-Object {$_.Name -eq 'TARGETSUBNET'} | Select-Object 'Id'
# Get the ID of the NSG which will be bound to the NIC - if you want.
$NSG = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $DestinationResourceGroupName -Name 'NSG-DESTINATIONVM'
# Create the NIC with the VNET/subnet reference
# You could also define here the backend load balanced pool etc that this NIC belongs to.
$NIC = New-AzureRmNetworkInterface `
-Name $nicName `
-ResourceGroupName $DestinationResourceGroupName `
-Location $LocationOfResources `
-SubnetId $Subnet.Id `
-NetworkSecurityGroupId $NSG.Id `
-PrivateIpAddress $PrivateIPAddress `
-DnsServer $DNSServerAddress
# Add the newly created NIC to the VM definition.
$VM = Add-AzureRmVMNetworkInterface -VM $VM -Id $NIC.Id
# Create the VM
New-AzureRmVM -ResourceGroupName $DestinationResourceGroupName -Location $LocationOfResources -VM $VM
Hopefully that's a decent starter for you but come back if you need more. If you're new to PowerShell though, I apologise but to do what you're asking, you either need PowerShell or the Azure CLI.
UPDATE (now I know these are managed disks):
With a little more clarity, here's your process.
I personally would do most if not all of this in PowerShell (Azure modules) but sensing you’re new to it, I’ll navigate you through the portal method. Unfortunately, a little PowerShell will be needed so prepare yourself.
Create a target storage account in the destination subscription –
you need to use an intermediate storage account as part of this
process. You also need a Virtual Network of course.
Shut down your source VM.
Navigate to the Disks blade and select one of the disks.
Click Create Snapshot. Repeat for any other disks attached to the VM and then of course all other VMs. Once you’ve got your snapshots, you can turn the VMs back on.
One could argue that you don’t have to create snapshots if you’re happy for the VMs to remain off while you copy the source VHD using an access URL like you’d get if you chose Export > Generate URL instead of creating a snapshot. We’re creating snapshot since you might actually want your VMs to be running again quickly.
For each snapshot that you created, you’ll need to copy it as a blob to a new target account.
Open each snapshot and click Export. Increase the valid time to 86400 seconds (one day), then click Generate URL.
Make sure you copy the URL that’s generated and don’t lose it.
Here comes the PowerShell which we use to download the generated URL in to a blob in our destination subscription and storage account. The download process takes a while per disk so be prepared! Remember you need to do this for every snapshot of every disk, altering names and possibly storage accounts for each VM as required. (this is the reason why I would choose to use PowerShell).
Source VHD - authenticated container ###
$srcUri = "https://md-f0p4tdq5fjpc.blob.core.windows.net/txwptxxxqvct/abcd?sv=2017-04-17&sr=b&si=cce17550-75f7-429c-bf08-31d0ae2da552&sig=oI%2BNOmQ4F75H8AlSwm7rJb%2Frm2Jhl9kfNZ7Jt2cUJpY%3D"
# Target Storage Account
Select-AzureRmSubscription 'DestinationSubscription'
### Target Storage Account ###
$destStorageAccount = "destinationstorageaccount"
$destStorageKey = "IkEvDdWTvTxN7v45VgAcvyEpZB9rGyYwyZhxvhG6eQaPIB15MQOa0vkvsHxMDpmUIJqq42UGiU8ji5Lqt39rAg=="
### Create the destination storage account context ###
$destContext = New-AzureStorageContext –StorageAccountName $destStorageAccount `
-StorageAccountKey $destStorageKey
### Destination Container Name ###
$containerName = "vhds"
### Create the container on the destination ###
New-AzureStorageContainer -Name $containerName -Context $destContext
### Start the asynchronous copy
$blob1 = Start-AzureStorageBlobCopy -AbsoluteUri $srcUri `
-DestContainer $containerName `
-DestBlob "destinationblob.vhd" `
-DestContext $destContext
$status = $blob1 | Get-AzureStorageBlobCopyState
### Loop until complete ###
While($status.Status -eq "Pending"){
$status = $blob1 | Get-AzureStorageBlobCopyState
Start-Sleep 300
### Print out status ###
$status
}
Once the blob copy is complete, we will need to wrap a VM around our disk (or disks!). As part of this process though, we will Import the VHD that is now in our target storage account in to a managed disk and attach it to the VM. More PowerShell unfortunately but this looks very similar to the PowerShell I’ve shared earlier. There are comments so you know what’s going on.
# Name the new server
$ServerName = 'DESTINATIONSERVERNAME'
# Provide the URI of the disk to be attached as the OS disk.
$LocationOfOSVHD = "https://destinationstorage.blob.core.windows.net/vhds/destinationblob.vhd"
$LocationOfDataDisk1 = "https://lrdestinationstorage.blob.core.windows.net/vhds/destinationblob1.vhd"
# Create a NIC and get the target VNET and subnet references.
$nicName = "$ServerName-nic"
# Set the private IP Address of the NIC
$PrivateIPAddress = '10.0.0.4'
# Set the DNS server for the NIC
$DNSServerAddress = '8.8.8.8'
# Destination resource group
$DestinationResourceGroupName = 'RG-DESTINATION'
# Location where the resources are to be built
$LocationOfResources = 'West Europe'
# Select the appropriate subscription
Select-AzureRmSubscription 'DestinationSubscription'
# Create a VM machine configuration
$VM = New-AzureRmVMConfig -VMSize 'Standard_DS2_v2' -VMName $ServerName
# Create a managed disk configuration and import the source VHD
$OSDisk = New-AzureRmDiskConfig -AccountType StandardLRS -Location $LocationOfResources -CreateOption Import -SourceUri $LocationOfOSVHD
# Create the managed disk using the configuration defined above.
$Disk1 = New-AzureRmDisk -DiskName 'OS-DISK' -Disk $OSDisk -ResourceGroupName $DestinationResourceGroupName
# Set the VM’s OS Disk to be the managed disk.
Set-AzureRmVMOSDisk -VM $vm -ManagedDiskId $Disk1.Id -StorageAccountType StandardLRS -DiskSizeInGB 80 -CreateOption Attach -Windows -Caching ReadWrite
# Repeat ourselves for any data disks that must also be attached to the VM in the destination.
# Increase LUN numbering and changing names etc as required.
$DataDisk = New-AzureRmDiskConfig -AccountType StandardLRS -Location $LocationOfResources -CreateOption Import -SourceUri $LocationOfDataDisk1
$Disk2 = New-AzureRmDisk -DiskName 'DATA-1' -Disk $DataDisk -ResourceGroupName $DestinationResourceGroupName
Add-AzureRmVMDataDisk -ManagedDiskId $Disk2.Id -VM $vm -CreateOption Attach -DiskSizeInGB 20 -Caching ReadWrite -StorageAccountType StandardLRS -Name 'DATA-1' -Lun 0
# Get the reference to the VNET in which the NIC will be bound. Might not be in the resource group you’re migrating to so this is left manual.
$vnet = Get-AzureRmVirtualNetwork -Name "DestinationAzureNetwork" -ResourceGroupName 'RG-DESTINATION'
# Get the reference to the Subnet ID in which the NIC will be bound. Replace 'default' with the name of the target subnet
$Subnet = $vnet.Subnets | Where-Object {$_.Name -eq 'default'} | Select-Object 'Id'
# Create the NIC with the VNET/subnet reference
# You could also define here the backend load balanced pool etc that this NIC belongs to.
$NIC = New-AzureRmNetworkInterface `
-Name $nicName `
-ResourceGroupName $DestinationResourceGroupName `
-Location $LocationOfResources `
-SubnetId $Subnet.Id `
-PrivateIpAddress $PrivateIPAddress `
-DnsServer $DNSServerAddress
# Add the newly created NIC to the VM definition.
$VM = Add-AzureRmVMNetworkInterface -VM $VM -Id $NIC.Id
# Create the VM
New-AzureRmVM -ResourceGroupName $DestinationResourceGroupName -Location $LocationOfResources -VM $VM
And that should do what you're after.
There's some considerations obviously and you'll need to edit the script each time you're doing a copy or re-creating the VM. This is not ideal but I've tried to take in to consideration your PowerShell familiarity. Otherwise this whole thing would have been PowerShell.

Attaching restored OS disk to existing VM

I have one VM with a daily backup scheduled. Today I deleted a file in that VM and changed some configuration. I restored yesterday's data disk from my recovery service vault and changed the names of the recovered data disk.
Now I want to attach yesterday's restored backup to my existing VM. Is it possible?
If not then suppose I delete my VM but I keep its network interface card. I can create a new VM from restored VHDs using ARM templates but how can I assign an existing NIC to my new VM?
Also, I have added this VM to my domain controller. If I recreate the VM, do I need to add the new VM to the domain controller or will it work normally?
Now I want to attach yesterday's restored backup to my existing VM. is
it possible?
Yes, we can attach this restore disk to your existing VM, then we can find the disk in your existing VM.
I delete VM but I keep network interface card for the VM, now I can
create VM from restored VHD's using ARM templates but how to assign
exiting NIC in the new VM?
Yes, we can use PowerShell to create a VM with existing NIC and VHD, here is an example:
$rgname = "jason-newgroup"
$loc = "japaneast"
$vmsize = "Standard_DS1_v2"
$vmname = "jason-newtest2"
$vm = New-AzureRmVMConfig -VMName $vmname -VMSize $vmsize
$nic = Get-AzureRmNetworkInterface -Name "NICname" -ResourceGroupName $rgname
$nicId = $nic.Id
$vm = Add-AzureRmVMNetworkInterface -VM $vm -Id $nicId
$osDiskName = "jason-newtest"
$osDiskVhdUri = "https://jasonnewgroupdisks912.blob.core.windows.net/vhds/jason-newtest201681285042.vhd"
$vm = Set-AzureRmVMOSDisk -VM $vm -VhdUri $osDiskVhdUri -name $osDiskName -CreateOption attach -Windows
New-AzureRmVM -ResourceGroupName $rgname -Location $loc -VM $vm
if I recreate the VM do I need to add new VM to domain controller or
will it work normally?
Yes, the new create VM (restore) will add to the domain controller, we don't need to add the VM to domain controller again.

How to increase size of OS disk in Windows Azure using Powershell

I want to increase size of OS disk in Windows Azure using Powershell or any other tool. Please help
Regards
Umair
Resize the OS drive
Open your Powershell ISE or Powershell window in administrative mode and follow the steps below:
Sign-in to your Microsoft Azure account in resource management mode and select your subscription as follows:
Login-AzureRmAccount
Select-AzureRmSubscription –SubscriptionName 'my-subscription-name'
Set your resource group name and VM name as follows:
$rgName = 'my-resource-group-name'
$vmName = 'my-vm-name'
Obtain a reference to your VM as follows:
$vm = Get-AzureRmVM -ResourceGroupName $rgName -Name $vmName
Stop the VM before resizing the disk as follows:
Stop-AzureRmVM -ResourceGroupName $rgName -Name $vmName
And here comes the moment we’ve been waiting for! Set the size of the OS disk to the desired value and update the VM as follows:
$vm.StorageProfile.OSDisk.DiskSizeGB = 1023
Update-AzureRmVM -ResourceGroupName $rgName -VM $vm
The new size should be greater than the existing disk size. The maximum allowed is 1023 GB.
Updating the VM may take a few seconds. Once the command finishes executing, restart the VM as follows:
Start-AzureRmVM -ResourceGroupName $rgName -Name $vmName
And that’s it! Now RDP into the VM, open Computer Management (or Disk Management) and expand the drive using the newly allocated space.
pasted from: https://learn.microsoft.com/en-us/azure/virtual-machines/virtual-machines-windows-expand-os-disk
i have done this by using below command on windows azure powershell latest version. Please note old version of powershell doesnot support this command .
Update-AzureDisk -DiskName [Disk-Name] -Label [DiskLabel]-ResizedSizeInGB 1020

Resources