Azure VM Snapshot performance issue - azure

Can we create a snapshot when the Azure VM is in running state? By any chance does this operation will impact the VM performance
Thanks in advance

Yes, you can create a snapshot when the Azure VM is in a running state. However, it's recommended that you cleanly shut down the VM before taking a snapshot, to clear out any processes that are in progress. Refer to https://learn.microsoft.com/en-us/azure/virtual-machines/windows/snapshot-copy-managed-disk
For example, you can run the following PowerShell commands to create a snapshot.
$resourceGroupName = 'xxx'
$location = 'xxx'
$vmName = 'xxx'
$snapshotName = 'xxx'
$vm = Get-AzVM `
-ResourceGroupName $resourceGroupName `
-Name $vmName
$snapshot = New-AzSnapshotConfig `
-SourceUri $vm.StorageProfile.OsDisk.ManagedDisk.Id `
-Location $location `
-CreateOption copy
New-AzSnapshot `
-Snapshot $snapshot `
-SnapshotName $snapshotName `
-ResourceGroupName $resourceGroupName

Related

How to create a VM from a shared image gallery in a different azure customer account

I have setup a Shared Image Gallery and added a VM image to it. I can provision a new VM in my subscription from it. A friend wants to use that same image to provision the same VM in his subscription, a totally different Azure account. He has added me temporarily as an owner to his subscription and I can change directory from my azure portal to access and work with it no problem.
When I try to create a VM, I can't find the gallery in my subscription/account from his subscription (a totally different Azure account).
I have tried making an application registration and even added permissions for the application in his subscription too (contributor). Still can't see it.
Is this possible at all or am I doing something wrong?
thank you much
At the moment, we have no way to use the portal to deploy a VM from an image in another azure tenant. To create a VM from an image shared between tenants, you must use the Azure CLI or Powershell. For more details, please refer to here
For example
create a service principal in the tenant 1
Give Tenant 2 access
a. Register the sp into tenant 2
we can implement it by requesting a sign-in using a browser
https://login.microsoftonline.com/<Tenant 2 ID>/oauth2/authorize?client_id=<Application (client) ID>&response_type=code&redirect_uri=https%3A%2F%2Fwww.microsoft.com%2F
b. Assign Azure RABC role Contributor to the sp
Create VM
a. Log into both tenants using the application ID, secret and tenant ID.
$applicationId = '<App ID>'
$secret = <Secret> | ConvertTo-SecureString -AsPlainText -Force
$tenant1 = "<Tenant 1 ID>"
$tenant2 = "<Tenant 2 ID>"
$cred = New-Object -TypeName PSCredential -ArgumentList $applicationId, $secret
Clear-AzContext
Connect-AzAccount -ServicePrincipal -Credential $cred -Tenant $tenant1
Connect-AzAccount -ServicePrincipal -Credential $cred -Tenant $tenant2
b. Create VM
$resourceGroup = ""
$location = ""
$vmName = ""
# Set a variable for the image version in Tenant 1 using the full image ID of the shared image version
$image = "/subscriptions/<Tenant 1 subscription>/resourceGroups/<Resource group>/providers/Microsoft.Compute/galleries/<Gallery>/images/<Image definition>/versions/<version>"
# Create user object
$cred = Get-Credential -Message "Enter a username and password for the virtual machine."
# Create a resource group
New-AzResourceGroup -Name $resourceGroup -Location $location
# Networking pieces
$subnetConfig = New-AzVirtualNetworkSubnetConfig -Name mySubnet -AddressPrefix 192.168.1.0/24
$vnet = New-AzVirtualNetwork -ResourceGroupName $resourceGroup -Location $location `
-Name MYvNET -AddressPrefix 192.168.0.0/16 -Subnet $subnetConfig
$pip = New-AzPublicIpAddress -ResourceGroupName $resourceGroup -Location $location `
-Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4
$nsgRuleRDP = New-AzNetworkSecurityRuleConfig -Name myNetworkSecurityGroupRuleRDP -Protocol Tcp `
-Direction Inbound -Priority 1000 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * `
-DestinationPortRange 3389 -Access Allow
$nsg = New-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location `
-Name myNetworkSecurityGroup -SecurityRules $nsgRuleRDP
$nic = New-AzNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location `
-SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id
# Create a virtual machine configuration using the $image variable to specify the shared image
$vmConfig = New-AzVMConfig -VMName $vmName -VMSize Standard_D1_v2 | `
Set-AzVMOperatingSystem -Windows -ComputerName $vmName -Credential $cred | `
Set-AzVMSourceImage -Id $image | `
Add-AzVMNetworkInterface -Id $nic.Id
# Create a virtual machine
New-AzVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig

Powershell script to create a snapshot and store it into a storage account in another location

Using powershell script, I need to create a snapshot of a VM and save the snapshot in a storage account which is in a different region. The snapshot name should also contain the date on which it was taken, so that it can be auto deleted after 30 days. Do let me know how to achieve this.
Also another major issue I am facing is how to store the snapshot in the storage account without using keys directly in the script.
This is the old script which I am using, it does not has the date in the snapshot name feature and uses storage account keys directly in the script, which is not secure.
#powershell script to create a snapshot
Select-AzSubscription -SubscriptionName 'subs name'
$subscriptionId = 'xxxxxx'
$resourceGroupName = "Rgname"
$vmName="VMname"
$Location = "East US"
#how to get-date in the name of the snap
$snapshotName = "snapname"
$vmOSDisk=(Get-AzVM -ResourceGroupName $resourceGroupName -Name $vmName).StorageProfile.OsDisk.Name
$Disk = Get-AzDisk -ResourceGroupName $resourceGroupName -DiskName $vmOSDisk
$SnapshotConfig = New-AzSnapshotConfig -SourceUri $Disk.Id -CreateOption Copy -Location $Location
$Snapshot=New-AzSnapshot -Snapshot $snapshotConfig -SnapshotName `
$snapshotName -ResourceGroupName $resourceGroupName
#powershell script to convert snapshot into managed disks
$diskName = 'ManagedDiskname'
#Provide the size of the disks in GB. It should be greater than the VHD file size.
$diskSize = '128'
$storageType = 'Premium_LRS'
Select-AzSubscription -SubscriptionId $SubscriptionId
$snapshot = Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName
$diskConfig = New-AzDiskConfig -SkuName $storageType -Location $location -CreateOption Copy -SourceResourceId $snapshot.Id
New-AzDisk -Disk $diskConfig -ResourceGroupName $resourceGroupName -DiskName $diskName
#powershell script to save managed disk into a storage account which is in a different location
$sasExpiryDuration = "3600"
$storageAccountName = "storageacctname"
$storageContainerName = "containername"
$storageAccountKey = '(Get-AzStorageAccountKey -ResourceGroupName "Snapshot-Powershell" -AccountName "storageforsnap")'
#Provide the key of the storage account where you want to copy the VHD of the managed disk.
$storageAccountKey = 'xxxxxx'
$destinationVHDFileName = "vhdfilename"
.
$useAzCopy = 1
Select-AzSubscription -SubscriptionId $SubscriptionId
$sas = Grant-AzDiskAccess -ResourceGroupName $ResourceGroupName -DiskName $diskName -DurationInSecond $sasExpiryDuration -Access Read
$destinationContext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey
#Copy the VHD of the managed disk to the storage account
if($useAzCopy -eq 1)
{
$containerSASURI = New-AzStorageContainerSASToken -Context $destinationContext -ExpiryTime(get-date).AddSeconds($sasExpiryDuration) -FullUri -Name $storageContainerName -Permission rw
azcopy copy $sas.AccessSAS $containerSASURI
}else{
Start-AzStorageBlobCopy -AbsoluteUri $sas.AccessSAS -DestContainer $storageContainerName -DestContext $destinationContext -DestBlob $destinationVHDFileName
}
1. Azure snapshot can be auto deleted after 30 days
As far as I knew, Azure does not provide the feature. But we can implement it via a schedule task.
For example
Enable Run As account in Azure automation account
Install module Az.Automation Az.Accounts and Az.Compute in the automation account. Regarding how to install, please refer to here
Create Azure Powershell runbook with the following script in the automation ccount. For more details, please refer to here.
#get the snpshots created before 30 days
Get-AzSnapshot| Where-Object{($_.TimeCreated -lt ([datetime]::UtcNow.AddDays(-30)))}
foreach($snp in $snps){
$snp| Remove-AzSnapshot -Force
}
Create a schedule for the Azure runbook.
2. How to securely connect Azure blob
If you want to securely connect Azure blob, we can implement it with Azure AD auth. For more details, please refer to here.
For example
Assign Storage Blob Data Contributor role to user or sp
New-AzRoleAssignment -SignInName <email> `
-RoleDefinitionName "Storage Blob Data Contributor" `
-Scope "/subscriptions/<subscription>/resourceGroups/sample-resource-group/providers/Microsoft.Storage/storageAccounts/<storage-account>"
Script
Connect-AzAccount
$ResourceGroupName=""
$snapshotName=""
$sasExpiryDuration=3600
$sas =Grant-AzSnapshotAccess -SnapshotName $snapshotName -ResourceGroupName $ResourceGroupName -DurationInSecond $sasExpiryDuration -Access Read
$storageAccountName=""
$destinationContext = New-AzStorageContext -StorageAccountName $storageAccountName -UseConnectedAccount
$storageContainerName="image"
$destinationVHDFileName="test.vhd"
Start-AzStorageBlobCopy -AbsoluteUri $sas.AccessSAS -DestContainer $storageContainerName -DestContext $destinationContext -DestBlob $destinationVHDFileName
#check copy state
Get-AzStorageBlobCopyState -Container $storageContainerName -Blob $destinationVHDFileName -Context $destinationContext

How do you create Azure VM from VHD with unmanaged disk?

I have a Datacenter 2016 server with unmanaged disk. I need to be able to replicate this VM and continue using an unmanaged disk.
Do I need to provision the VM i want to replicate? Or can I just use the VHD in storage to create a new VM?
Here is my powershell script so far. Note that I tried to provision a VM
New-AzVm `
-ResourceGroupName "myResource" `
-Name "myVM" `
-ImageName "" ` //IS THIS WHERE YOU WOULD PUT A VHD?
-Location "West US 2" `
-VirtualNetworkName "my-vnet" `
-SubnetName "default" `
-SecurityGroupName "myvmNSG" `
-OpenPorts 3389, 80, 443
If you want to create an unmanaged VM from the VHD file, you can use the VM config. Here is an example using the existing NIC and VNet, you can also create the new one for it:
$NIC = Get-AzNetworkInterface -ResourceGroupName charlesUnmanaged -Name azurevm938
$VirtualMachine = New-AzVMConfig -VMName "azurevm" -VMSize "Standard_DS3"
$VirtualMachine = Add-AzVMNetworkInterface -VM $VirtualMachine -Id $NIC.Id
$VirtualMachine = Set-AzVMOSDisk -VM $VirtualMachine -Name "unmanagedos" -VhdUri $OSDiskUri -CreateOption Attach -Linux
New-AzVM -ResourceGroupName "charlesUnmanaged" -Location "East US" -VM $VirtualMachine -Verbose

Create a Azure VM with unmanaged data disks enabled using powershell

I am trying to create a azure vm using powershell so that it would allow to attach unmanaged data disks in future.
I see documentation on creating but those always create with managed disks
Example.
nic\network\etc amended
# Create storage account
$storageAccount = New-AzStorageAccount -ResourceGroupName "MyResourceGroup" -AccountName "MyStorageAccount" -Location $location -SkuName "Standard_LRS"
# Add disk
$OSDiskUri = $storageAccount.PrimaryEndpoints.Blob.ToString() + "vhds/vm-disk.vhd"
$vm = Set-AzVMOSDisk -VM $vm -Name "vm-disk" -VhdUri $OSDiskUri -CreateOption fromImage
# Create VM
New-AzVM -ResourceGroupName myResourceGroup -Location $location -VM $vm

How to revert an azure disk back to its former snapshot?

I have a VM in azure, and via the portal have selected its Disk, and created a snapshot of it. How do I now revert back to that snapshot for the Disk (via portal or CLI)?
I'm not looking to create new disks or VMs from the snapshot, just revert back.
How do I now revert back to that snapshot for the Disk (via portal or
CLI)?
Do you mean you want to use this snapshot to rollback your system?
Unfortunately, for now Azure does not support this, we can't use snapshot to revert back.
In Azure, we can't revert back Azure VM directly, we should create disk or VM from that snapshot.
By default, snapshot used for Azure backup. In Azure recovery services, we can restore VMs from the snapshot. Restore this VM was create a new VM with this OS disk, not rollback.
This worked for eastus zone 1 using the cloud shell in the azure portal
$SnapshotName = "my_snapshot"
$SnapshotResourceGroup = "my_resource_group"
$DiskNameOS = "my_new_snapshotdisk"
$snapshotinfo = Get-AzSnapshot -ResourceGroupName $SnapshotResourceGroup -SnapshotName $snapshotName
New-AzDisk -DiskName $DiskNameOS (New-AzDiskConfig -zone 1 -Location eastus -CreateOption Copy -SourceResourceId $snapshotinfo.Id) -ResourceGroupName $SnapshotResourceGroup
After that I went to the VM in the portal, selected "disks" and selected "swap os disk".
I did it successfully with Azure PowerShell, using Set-AzVMOSDisk. There is a module which unfortunately can only restore the snapshots that it created, but its code demonstrates how it works.
Summarised:
Get-AzSnapshot -ResourceGroupName "..." # to find the Disk ID
$vm = Get-AzVM -Name "..."
$old_disk = Get-AzDisk -Name $vm.StorageProfile.OsDisk.name
$diskconf = New-AzDiskConfig -AccountType $old_disk.sku.name -Location $old_disk.Location -SourceResourceId "Id of the disk" -CreateOption Copy
$newdisk = NewAzDisk -Disk $diskconf -ResourceGroupName "..." -DiskName "OS_disk_$((New-Guid).ToString())"
Set-AzVMOSDisk -VM $vm -ManagedDiskId $newdisk.Id -Name $newdisk.Name
Update-AzVM -ResourceGroupName "..." -VM $vm
I did it with the PS script below. It stops VM, creates a new disk using the snapshot, and then swaps VM to this new disk. Snapshot has been created on stopped VM.
$resourceGroupName = '...'
$location = 'eastus2'
$vmName = '...'
$snapshotName = '...'
$snapshotinfo = Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName
$vm = Get-AzVM `
-ResourceGroupName $resourceGroupName `
-Name $vmName
Stop-AzVM -ResourceGroupName $resourceGroupName -Name $vm.Name -Force
# Create the new disk that you want to swap in
$newDiskName = $($vmName + "_disk_" + (Get-Date).ToString("yyyyMMddhhmm"))
$newDisk = New-AzDisk -DiskName $newDiskName (New-AzDiskConfig -zone 1 -Location $location -CreateOption Copy -SourceResourceId $snapshotinfo.Id) -ResourceGroupName $resourceGroupName
Set-AzVMOSDisk -VM $vm -ManagedDiskId $newDisk.Id -Name $newDisk.Name
Update-AzVM -ResourceGroupName $resourceGroupName -VM $vm
Start-AzVM -Name $vm.Name -ResourceGroupName $resourceGroupName

Resources