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
Related
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
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
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
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
Is it true, that even for Virtual Machine's created in the latest platform (ARM), that if you initially created the machine with 1 NIC, that there is no way to add additional NICs to the VM?
I found a few random (non-Microsoft) articles that seem to indicate this is the case, which if so... is kind of retarded.
So I wanted to make sure that I'm understanding this correctly.
If I have to start all over and build a new machine just to add a NIC, I might consider just using Amazon AWS as I can't imagine this being a limitation over there.
that if you initially created the machine with 1 NIC, that there is no
way to add additional NICs to the VM
It is true, there is no way to add a NIC to an existing VM, and we can't via portal to create a VM with multiple NICs. But we can create/recreate the VM via powershell and add another NIC to it. Here is the powershell script:
$rg = "jason-newgroup"
$loc = "japan east"
$nic01 = "nic01"
$nic02 = "nic02"
$vnet = Get-AzureRmVirtualNetwork -Name ‘jason-newgroup-vnet’ -ResourceGroupName ‘jason-newgroup’
$sub01id = (Get-AzureRmVirtualNetworkSubnetConfig -Name ‘sub01’ -VirtualNetwork $vnet).Id
$sub02id = (Get-AzureRmVirtualNetworkSubnetConfig -Name ‘sub02’ -VirtualNetwork $vnet).Id
$ip1 = '10.1.0.5'
$ip2 = '10.1.1.5'
$nic1 = New-AzureRmNetworkInterface -Name $nic01 -ResourceGroupName $rg -Location $loc -SubnetId $sub01id -PrivateIpAddress $ip1
$nic2 = New-AzureRmNetworkInterface -Name $nic02 -ResourceGroupName $rg -Location $loc -SubnetId $sub02id -PrivateIpAddress $ip2
$vmsize = "Standard_DS4_v2"
$vmname = "jason-windows"
$vm = New-AzureRmVMConfig -VMName $vmname -VMSize $vmsize
$VM = Add-AzureRmVMNetworkInterface -VM $VM -Id $nic1.Id -Primary
$VM = Add-AzureRmVMNetworkInterface -VM $VM -Id $nic2.Id
$osDiskName = "jason-newtest"
$osDiskVhdUri = "https://jasonnewgroupdisks717.blob.core.windows.net/vhds/jason-windows2016920165635.vhd"
$vm = Set-AzureRmVMOSDisk -VM $vm -VhdUri $osDiskVhdUri -name $osDiskName -CreateOption attach -windows
New-AzureRmVM -ResourceGroupName $rg -Location $loc -VM $vm
Notice:
The VM size determines the number of NICS that you can create for a VM. More information about how many NICS each VM size supports, please refer to the link below:
https://azure.microsoft.com/en-us/documentation/articles/virtual-machines-windows-sizes/
There is an update to this. You can now add nics to existing Azure VMs. See the documentation here for tutorial - https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-network-interface-vm