-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathRestore-AzureRMvm.ps1
372 lines (277 loc) · 12.7 KB
/
Restore-AzureRMvm.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
<#
.SYNOPSIS
Restores Azure v2 ARM virtual machines from a backup VHD location.
Does not work with VMs configured with managed disks because they allow snapshots.
Requires AzureRM module version 4.2.1 or later.
.DESCRIPTION
Copies VHD files from a backup location - from using the associated script Backup-AzureRMvm.ps1. Since VHDs have a lease on them
from being attached to a VM, the VM must first be deleted. The VHD is copied over the original location and then the VM
is recreated using the same configuration.
VMs must be shutdown prior to running this script. It will halt if they are still running.
.EXAMPLE
.\Restore-AzureRMvm.ps1 -ResourceGroupName 'CONTOSO'
.EXAMPLE
.\Restore-AzureRMvm.ps1 -ResourceGroupName 'CONTOSO' -BackupContainer 'vhd-backups-9021' -VhdContainer 'MyVMs'
.PARAMETER -ResourceGroupName [string]
Name of resource group being copied
.PARAMETER -BackupContainer [string]
Name of container that holds the backup VHD blobs
.PARAMETER -VhdContainer [string]
Name of container that will hold VHD blobs attached to VMs
.PARAMETER -Environment [string]
Name of Environment e.g. AzureUSGovernment. Defaults to AzureCloud
.NOTES
Original Author: https://github.com/JeffBow
------------------------------------------------------------------------
Copyright (C) 2016 Microsoft Corporation
You have a royalty-free right to use, modify, reproduce and distribute
this sample script (and/or any modified version) in any way
you find useful, provided that you agree that Microsoft has no warranty,
obligations or liability for any sample application or script files.
------------------------------------------------------------------------
#>
#Requires -Version 4.0
param(
[Parameter(Mandatory=$true)]
[string]$ResourceGroupName,
[Parameter(Mandatory=$false)]
[string]$BackupContainer= 'vhd-backups',
[Parameter(Mandatory=$false)]
[string]$VhdContainer= 'vhds',
[Parameter(Mandatory=$false)]
[string]$Environment= "AzureCloud"
)
$ProgressPreference = 'SilentlyContinue'
$resourceGroupVMjsonPath = "$env:TEMP\$ResourceGroupName.resourceGroupVMs.json"
import-module AzureRM
if ((Get-Module AzureRM).Version -lt "4.2.1") {
Write-warning "Old version of Azure PowerShell module $((Get-Module AzureRM).Version.ToString()) detected. Minimum of 4.2.1 required. Run Update-Module AzureRM"
BREAK
}
<###############################
Get Storage Context function
################################>
function Get-StorageObject
{ param($resourceGroupName, $srcURI)
$split = $srcURI.Split('/')
$strgDNS = $split[2]
$splitDNS = $strgDNS.Split('.')
$storageAccountName = $splitDNS[0]
$StorageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $resourceGroupName -Name $StorageAccountName).Value[0]
$StorageContext = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
return $StorageContext
} # end of Get-StorageObject function
<###############################
Copy blob function
################################>
function copy-azureBlob
{ param($srcUri, $srcContext, $destContext, $containerName)
$split = $srcURI.Split('/')
$blobName = $split[($split.count -1)]
$blobSplit = $blobName.Split('.')
$extension = $blobSplit[($blobSplit.count -1)]
if($($extension.tolower()) -eq 'status' ){Write-Output "Status file blob $blobname skipped";return}
if(! $containerName){$containerName = $split[3]}
# add full path back to blobname
if($split.count -gt 5)
{
$i = 4
do
{
$path = $path + "/" + $split[$i]
$i++
}
while($i -lt $split.length -1)
$blobName= $path + '/' + $blobName
$blobName = $blobName.Trim()
$blobName = $blobName.Substring(1, $blobName.Length-1)
}
# create container if doesn't exist
if (!(Get-AzureStorageContainer -Context $destContext -Name $containerName -ea SilentlyContinue))
{
try
{
$newRtn = New-AzureStorageContainer -Context $destContext -Name $containerName -Permission Off -ea Stop
Write-Output "Container $($newRtn.name) was created."
}
catch
{
$_ ; break
}
}
try
{
$blobCopy = Start-AzureStorageBlobCopy `
-srcUri $srcUri `
-SrcContext $srcContext `
-DestContainer $containerName `
-DestBlob $blobName `
-DestContext $destContext `
-Force -ea Stop
write-output "$srcUri is being copied to $containerName"
}
catch
{
$_ ; write-warning "Failed to copy to $srcUri to $containerName"
}
} # end of copy-azureBlob function
# get Azure creds
write-host "Enter credentials for your Azure Subscription..." -F Yellow
$login= Connect-AzureRmAccount -EnvironmentName $Environment
$loginID = $login.context.account.id
$sub = Get-AzureRmSubscription
$SubscriptionId = $sub.Id
# check for multiple subs under same account and force user to pick one
if($sub.count -gt 1) {
$SubscriptionId = (Get-AzureRmSubscription | select * | Out-GridView -title "Select Target Subscription" -OutputMode Single).Id
Select-AzureRmSubscription -SubscriptionId $SubscriptionId| Out-Null
$sub = Get-AzureRmSubscription -SubscriptionId $SubscriptionId
$SubscriptionId = $sub.Id
}
# check for valid sub
if(! $SubscriptionId)
{
write-warning "The provided credentials failed to authenticate or are not associcated to a valid subscription. Exiting the script."
break
}
write-verbose "Logged into $($sub.Name) with subscriptionID $SubscriptionId as $loginID" -verbose
# check for valid source resource group
if(-not ($sourceResourceGroup = Get-AzureRmResourceGroup -ResourceGroupName $resourceGroupName))
{
write-warning "The provided resource group $resourceGroupName could not be found. Exiting the script."
break
}
# get configuration details for all VMs
[string] $location = $sourceResourceGroup.location
$resourceGroupVMs = Get-AzureRMVM -ResourceGroupName $resourceGroupName
if(! $resourceGroupVMs){write-warning "No virtual machines found in resource group $resourceGroupName"; break}
$resourceGroupVMs | %{
$status = ((get-azurermvm -ResourceGroupName $resourceGroupName -Name $_.name -status).Statuses|where{$_.Code -like 'PowerState*'}).DisplayStatus
write-output "$($_.name) status is $status"
if($status -eq 'VM running'){write-warning "All virtual machines in this resource group are not stopped. Please stop all VMs and try again"; break}
}
#save off VM config to temp drive for drive
$resourceGroupVMs | ConvertTo-Json -depth 10 | Out-File $resourceGroupVMjsonPath
# remove each VM, copy in new copy of disk and recreate the VM
foreach($srcVM in $resourceGroupVMs)
{
# get source VM attributes
$VMName = $srcVM.Name
$VMSize = $srcVM.HardwareProfile.VMSize
$OSDiskName = $srcVM.StorageProfile.OsDisk.Name
$OSType = $srcVM.storageprofile.osdisk.OsType
$OSDiskCaching = $srcVM.StorageProfile.OsDisk.Caching
$avSetRef = ($srcVM.AvailabilitySetReference.id).Split('/')
$avSetName = $avSetRef[($avSetRef.count -1)]
$AvailabilitySet = Get-AzureRmAvailabilitySet -ResourceGroupName $ResourceGroupName -Name $avSetName
$CreateOption = "Attach"
# remove VM
write-verbose "Restoring Virtual Machine $vmName" -verbose
try
{
Remove-AzureRmVM -Name $vmName -ResourceGroupName $resourceGroupName -Force -ea Stop | out-null
write-output "Removed $vmName"
}
catch
{
$_
Write-Warning "Failed to remove Virtual Machine $vmName"
break
}
# over-write existing disk from backup location
# get storage account context from $srcVM.storageprofile.osdisk.vhd.uri
$OSDiskUri = $null
$OSDiskUri = $srcVM.storageprofile.osdisk.vhd.uri
$OSsplit = $OSDiskUri.Split('/')
$OSblobName = $OSsplit[($OSsplit.count -1)]
$OScontainerName = $OSsplit[3]
$OSstorageContext = Get-StorageObject -resourceGroupName $resourceGroupName -srcURI $OSDiskUri
$backupURI = $OSDiskUri.Replace($vhdContainer, $backupContainer)
copy-azureBlob -srcUri $backupURI -srcContext $OSstorageContext -destContext $OSstorageContext -containerName $vhdContainer
# check on copy status
do{
$rtn = $null
$rtn = Get-AzureStorageBlob -Context $OSstorageContext -container $OScontainerName -Blob $OSblobName | Get-AzureStorageBlobCopyState
$rtn | select Source, Status, BytesCopied, TotalBytes | fl
if($rtn.status -ne 'Success'){
write-verbose "Waiting for blob copy $OSblobName to complete" -verbose
Sleep 10
}
}
while($rtn.status -ne 'Success')
# exit script if user breaks out of above loop
if($rtn.status -ne 'Success'){EXIT}
# get the Network Interface Card we created previously based on the original source name
$NICRef = ($srcVM.NetworkInterfaceIDs).Split('/')
$NICName = $NICRef[($NICRef.count -1)]
$NIC = Get-AzureRmNetworkInterface -Name $NICName -ResourceGroupName $ResourceGroupName
# create VM Config
if($AvailabilitySet)
{
$VirtualMachine = New-AzureRmVMConfig -VMName $VMName -VMSize $VMSize -AvailabilitySetID $AvailabilitySet.Id -wa SilentlyContinue
}
else
{
$VirtualMachine = New-AzureRmVMConfig -VMName $VMName -VMSize $VMSize -wa SilentlyContinue
}
# Set OS Disk based on OS type
if($OStype -eq 'Windows' -or $OStype -eq '0'){
$VirtualMachine = Set-AzureRmVMOSDisk -VM $VirtualMachine -Name $OSDiskName -VhdUri $OSDiskUri -Caching $OSDiskCaching -CreateOption $createOption -Windows
}
else
{
$VirtualMachine = Set-AzureRmVMOSDisk -VM $VirtualMachine -Name $OSDiskName -VhdUri $OSDiskUri -Caching $OSDiskCaching -CreateOption $createOption -Linux
}
# add NIC
$VirtualMachine = Add-AzureRmVMNetworkInterface -VM $VirtualMachine -Id $NIC.Id
# copy and readd data disk if they were present
if($srcVM.storageProfile.datadisks)
{
foreach($disk in $srcVM.storageProfile.DataDisks)
{
$dataDiskName = $null
$dataDiskUri = $null
$diskBlobName = $null
$dataDiskName = $disk.Name
$dataDiskLUN = $disk.Lun
$diskCaching = $disk.Caching
$DiskSizeGB = $disk.DiskSizeGB
$dataDiskUri = $disk.vhd.uri
$split = $dataDiskUri.Split('/')
$diskBlobName = $split[($split.count -1)]
$diskContainerName = $split[3]
$diskStorageContext = Get-StorageObject -resourceGroupName $resourceGroupName -srcURI $dataDiskUri
$backupDiskURI = $dataDiskUri.Replace($vhdContainer, $backupContainer)
copy-azureBlob -srcUri $backupDiskURI -srcContext $diskStorageContext -destContext $diskStorageContext -containerName $vhdContainer
# check copy status
do
{
$drtn = $null
$drtn = Get-AzureStorageBlob -Context $diskStorageContext -container $diskContainerName -Blob $diskBlobName | Get-AzureStorageBlobCopyState
$drtn| select Source, Status, BytesCopied, TotalBytes|fl
if($rtn.status -ne 'Success')
{
write-verbose "Waiting for blob copy $diskBlobName to complete" -verbose
Sleep 10
}
}
while($drtn.status -ne 'Success')
# exit script if user breaks out of above loop
if($rtn.status -ne 'Success'){EXIT}
Add-AzureRmVMDataDisk -VM $VirtualMachine -Name $dataDiskName -DiskSizeInGB $DiskSizeGB -Lun $dataDiskLUN -VhdUri $dataDiskUri -Caching $diskCaching -CreateOption $CreateOption | out-null
}
}
# create the VM from the config
try
{
write-verbose "Recreating Virtual Machine $VMName in resource group $resourceGroupName at location $location" -verbose
# $VirtualMachine
New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $location -VM $VirtualMachine -ea Stop -wa SilentlyContinue | out-null
write-output "Successfully recreated Virtual Machine $VMName"
}
catch
{
$_
write-warning "Failed to create Virtual Machine $VMName"
}
}