-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathVM_Recovery_Script.ps1
374 lines (374 loc) · 14.1 KB
/
VM_Recovery_Script.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
373
374
# Developed for Rubrik
################################################
# Configure the variables below for the Cloud Cluster
################################################
$CloudCluster = "192.168.0.200"
$RecoveryPlanCSV = "C:\Scripts\CloudRecoveryPlan\CloudRecoveryPlan.csv"
$LogDirectory = "C:\Scripts\CloudRecoveryPlan\"
# Prompting for username and password to authenicate, can set manually to remove human interaction
$Credentials = Get-Credential -Credential $null
$CloudUser = $Credentials.UserName
$Credentials.Password | ConvertFrom-SecureString
$CloudPassword = $Credentials.GetNetworkCredential().password
########################################################################################################################
# Nothing to configure below this line - Starting the main function of the script
########################################################################################################################
# Adding certificate exception to prevent API errors
################################################
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
################################################
# Starting logging & importing the CSV
################################################
$Now = get-date
$Log = $LogDirectory + "\Cloud-RecoveryPlanLog-" + $Now.ToString("yyyy-MM-dd") + "@" + $Now.ToString("HH-mm-ss") + ".log"
Start-Transcript -Path $Log -NoClobber
$RecoveryPlanVMs = import-csv $RecoveryPlanCSV
################################################
# Building Cloud API string & invoking REST API
################################################
$baseURL = "https://" + $CloudCluster + "/api/v1/"
$xCloudSessionURL = $baseURL + "session"
$authInfo = ("{0}:{1}" -f $CloudUser,$CloudPassword)
$authInfo = [System.Text.Encoding]::UTF8.GetBytes($authInfo)
$authInfo = [System.Convert]::ToBase64String($authInfo)
$headers = @{Authorization=("Basic {0}" -f $authInfo)}
$TypeJSON = "application/json"
# Authentication with API
Try
{
$xCloudSessionResponse = Invoke-WebRequest -Uri $xCloudSessionURL -Headers $headers -Method POST -Body $sessionBody -ContentType $TypeJSON
}
Catch
{
Write-Host $_.Exception.ToString()
$error[0] | Format-List -Force
}
# Extracting the token from the JSON response
$xCloudSession = (ConvertFrom-Json -InputObject $xCloudSessionResponse.Content)
$CloudSessionHeader = @{'Authorization' = "Bearer $($xCloudSession.token)"}
###############################################
# Getting list of VMs
###############################################
$VMListURL = $baseURL+"vmware/vm?limit=5000"
Try
{
$VMListJSON = Invoke-RestMethod -Uri $VMListURL -TimeoutSec 100 -Headers $CloudSessionHeader -ContentType $TypeJSON
$VMList = $VMListJSON.data
}
Catch
{
Write-Host $_.Exception.ToString()
$error[0] | Format-List -Force
}
###################################################################
# Start Per VM Actions here
###################################################################
write-host "Starting per VM RecoveryPlan Actions"
foreach ($VM in $RecoveryPlanVMs)
{
###############################################
# Setting the variables for the current VM
###############################################
$VMName = $VM.VMName
$VMAction = $VM.Action
$VMDisableNetwork = $VM.DisableNetwork
$VMRemoveNetworkDevices = $VM.RemoveNetworkDevices
$VMPowerOn = $VM.PowerOn
$VMRunScriptsinLiveMount = $VM.RunScriptsinLiveMount
$VMPreFailoverScript = $VM.PreFailoverScript
$VMPostFailoverScriptDelay = $VM.PostFailoverScriptDelay
$VMPostFailoverScript = $VM.PostFailoverScript
$VMNextVMFailoverDelay = $VM.NextVMFailoverDelay
$VMPreFailoverUserPrompt = $VM.PreFailoverUserPrompt
$VMPostFailoverUserPrompt = $VM.PostFailoverUserPrompt
# Inserting space in log for readability
write-host "--------------------------------------------"
write-host "Performing Action for VM:$VMName"
# Giving the user 3 seconds to see
sleep 3
###################################################################
# VM Pre-Failover User Prompt
###################################################################
if ($VMPreFailoverUserPrompt -ne "")
{
# Setting title and user prompt
$PromptTitle = "Pre-Failover Prompt"
$PromptMessage = "VM:$VMName
$VMPreFailoverUserPrompt"
# Defining options
$Continue = New-Object System.Management.Automation.Host.ChoiceDescription "&Continue", `
"Continues to run the recovery plan"
$Stop = New-Object System.Management.Automation.Host.ChoiceDescription "&Stop", `
"Stops the recovery plan altogether"
$PromptOptions = [System.Management.Automation.Host.ChoiceDescription[]]($Continue, $Stop)
# Prompting user and defining the result
$PromptResult = $host.ui.PromptForChoice($PromptTitle, $PromptMessage, $PromptOptions, 0)
switch ($PromptResult)
{
0 {"User Selected Continue Recovery Plan"}
1 {"User Selected Stop Recovery Plan"}
}
# Performing the exit action if selected
if ($PromptResult -eq 1)
{
# Stopping transcript
Stop-Transcript
# Killing PowerShell script process
kill $PID
}
}
###############################################
# Getting VM ID and outputting VM info to log/console
###############################################
$VMID = $VMList | Where-Object {($_.name -eq $VMName)} | select -ExpandProperty id
$VMSLADomain = $VMList | Where-Object {($_.name -eq $VMName)} | select -ExpandProperty effectiveSlaDomainName
$VMclusterName = $VMList | Where-Object {($_.name -eq $VMName)} | select -ExpandProperty clusterName
$VMHostName = $VMList | Where-Object {($_.name -eq $VMName)} | select -ExpandProperty hostName
$VMIPAddress = $VMList | Where-Object {($_.name -eq $VMName)} | select -ExpandProperty ipAddress
Write-host "ID:$VMID
IPAddress:$VMIPAddress
SLADomain:$VMSLADomain
clusterName:$VMclusterName
HostName:$VMHostName"
###############################################
# Getting VM snapshot ID
###############################################
$VMSnapshotURL = $baseURL+"vmware/vm/"+$VMID+"/snapshot"
Try
{
$VMSnapshotJSON = Invoke-RestMethod -Uri $VMSnapshotURL -TimeoutSec 100 -Headers $CloudSessionHeader -ContentType $TypeJSON
$VMSnapshot = $VMSnapshotJSON.data
}
Catch
{
Write-Host $_.Exception.ToString()
$error[0] | Format-List -Force
}
# Selecting most recent VM snapshot to use for recovery operation
$VMSnapshotID = $VMSnapshot | Sort-Object -Descending date | select -ExpandProperty id -First 1
$VMSnapshotDate = $VMSnapshot | Sort-Object -Descending date | select -ExpandProperty date -First 1
Write-host "Snapshot:$VMSnapshotDate"
###############################################
# Performing Live Mount - If configured for VMAction
###############################################
# Using defaultESXi host of original VM by not specifying it in the VM JSON
IF ($VMAction -eq "LiveMount")
{
write-host "Action:$VMAction"
###########################################
# Running pre-failover script if RunScriptsinTest is enabled and script configured
###########################################
if (($VMRunScriptsinLiveMount -eq "TRUE") -and ($VMPreFailoverScript -ne ""))
{
Try
{
write-host "Running Pre-FailoverScript:$VMPreFailoverScript"
invoke-expression $VMPreFailoverScript
}
Catch
{
Write-Host $_.Exception.ToString()
$error[0] | Format-List -Force
}
}
###########################################
# Setting URL and creating JSON
###########################################
# Setting default if not specified in CSV
if ($VMDisableNetwork -eq ""){$VMDisableNetwork = "false"}
if ($VMRemoveNetworkDevices -eq ""){$VMRemoveNetworkDevices = "true"}
if ($VMPowerOn -eq ""){$VMPowerOn = "true"}
# Forcing to lower case to compensate for excel auto-correct capitalizing
$VMDisableNetwork = $VMDisableNetwork.ToLower()
$VMRemoveNetworkDevices = $VMRemoveNetworkDevices.ToLower()
$VMPowerOn = $VMPowerOn.ToLower()
$VMLMJSON =
"{
""vmName"": ""$VMName - LiveMount"",
""disableNetwork"": $VMDisableNetwork,
""removeNetworkDevices"": $VMRemoveNetworkDevices,
""powerOn"": $VMPowerOn
}"
$VMLiveMountURL = $baseURL+"vmware/vm/snapshot/"+$VMSnapshotID+"/mount"
###########################################
# POST to REST API URL with VMJSON
###########################################
Try
{
write-host "Starting LiveMount for VM:$VMName"
$VMLiveMountPOST = Invoke-RestMethod -Method Post -Uri $VMLiveMountURL -Body $VMLMJSON -TimeoutSec 100 -Headers $CloudSessionHeader -ContentType $TypeJSON
$VMOperationSuccess = $TRUE
}
Catch
{
Write-Host $_.Exception.ToString()
$error[0] | Format-List -Force
}
###########################################
# Running post-failover script if RunScriptsinTest is enabled, script configured and test started
###########################################
if (($VMRunScriptsinLiveMount -eq "TRUE") -and ($VMPostFailoverScript -ne "") -and ($VMOperationSuccess -eq $TRUE))
{
# Waiting sleep delay for post script
write-host "Sleeping $VMPostFailoverScriptDelay seconds for VMPostFailoverScriptDelay"
sleep $VMPostFailoverScriptDelay
Try
{
write-host "Running Post-FailoverScript:$VMPostFailoverScript"
invoke-expression $VMPostFailoverScript
}
Catch
{
Write-Host $_.Exception.ToString()
$error[0] | Format-List -Force
}
}
# End of LiveMount action below
}
# End of LiveMount action above
###############################################
# Performing Instant Recovery - If configured for VMAction
###############################################
IF ($VMAction -eq "InstantRecover")
{
write-host "Action:$VMAction"
###########################################
# Running pre-failover script if script configured
###########################################
if ($VMPreFailoverScript -ne "")
{
Try
{
write-host "Running Pre-FailoverScript:$VMPreFailoverScript"
invoke-expression $VMPreFailoverScript
}
Catch
{
Write-Host $_.Exception.ToString()
$error[0] | Format-List -Force
}
}
###########################################
# Setting URL and creating JSON
###########################################
# Setting default if not specified in CSV
if ($VMRemoveNetworkDevices -eq ""){$VMRemoveNetworkDevices = "true"}
# Forcing to lower case to compensate for excel auto-correct capitalizing
$VMRemoveNetworkDevices = $VMRemoveNetworkDevices.ToLower()
$VMIRJSON =
"{
""vmName"": ""$VMName"",
""removeNetworkDevices"": $VMRemoveNetworkDevices
}"
$VMInstantRecoverURL = $baseURL+"vmware/vm/snapshot/"+$VMSnapshotID+"/instant_recover"
###########################################
# POST to REST API URL with VMJSON
###########################################
# Warning, connects the VM the production network, shuts down and renames the original VM if it exists as "Deprecated VMName Date Time"
Try
{
write-host "Starting InstantRecover for VM:$VMName"
$VMInstantRecoverPOST = Invoke-RestMethod -Method Post -Uri $VMInstantRecoverURL -Body $VMIRJSON -TimeoutSec 100 -Headers $CloudSessionHeader -ContentType $TypeJSON
$VMOperationSuccess = $TRUE
}
Catch
{
Write-Host $_.Exception.ToString()
$error[0] | Format-List -Force
}
###########################################
# Running post-failover script configured and test started
###########################################
if (($VMPostFailoverScript -ne "") -and ($VMOperationSuccess -eq $TRUE))
{
# Waiting sleep delay for post script
write-host "Sleeping $VMPostFailoverScriptDelay seconds for VMPostFailoverScriptDelay"
sleep $VMPostFailoverScriptDelay
Try
{
write-host "Running Post-FailoverScript:$VMPostFailoverScript"
invoke-expression $VMPostFailoverScript
}
Catch
{
Write-Host $_.Exception.ToString()
$error[0] | Format-List -Force
}
}
# End of InstantRecover action below
}
# End of InstantRecover action below
###############################################
# No valid VMAction configured
###############################################
IF (($VMAction -ne "LiveMount") -and ($VMAction -ne "InstantRecover"))
{
write-host "VMAction not configured for $VMName as LiveMount or InstantRecover meaning no action was taken"
}
###########################################
# Waiting for VMNextVMFailoverDelay and Post-Failover Prompt (if configured) if start test was a success
###########################################
if ($VMOperationSuccess -eq $TRUE)
{
write-host "Sleeping $VMNextVMFailoverDelay seconds for VMNextVMFailoverDelay"
sleep $VMNextVMFailoverDelay
###################################################################
# VM Post-Failover User Prompt
###################################################################
if ($VMPostFailoverUserPrompt -ne "")
{
# Setting title and user prompt
$PromptTitle = "Post-Failover Prompt"
$PromptMessage = "VM:$VMName
$VMPostFailoverUserPrompt"
# Defining options
$Continue = New-Object System.Management.Automation.Host.ChoiceDescription "&Continue", `
"Continues to run the recovery plan"
$Stop = New-Object System.Management.Automation.Host.ChoiceDescription "&Stop", `
"Stops the recovery plan altogether"
$PromptOptions = [System.Management.Automation.Host.ChoiceDescription[]]($Continue, $Stop)
# Prompting user and defining the result
$PromptResult = $host.ui.PromptForChoice($PromptTitle, $PromptMessage, $PromptOptions, 0)
switch ($PromptResult)
{
0 {"User Selected Continue Recovery Plan"}
1 {"User Selected Stop Recovery Plan"}
}
# Performing the exit action if selected
if ($PromptResult -eq 1)
{
# Stopping transcript
Stop-Transcript
# Killing PowerShell script process
kill $PID
}
}
# End of "Waiting for VMPostFailoverUserPrompt and Post-Failover Prompt (if configured) if start test was a success" below
}
# End of "Waiting for VMPostFailoverUserPrompt and Post-Failover Prompt (if configured) if start test was a success" above
#
# End of per VM actions below
}
# End of per VM actions above
#
# Inserting space in log for readability
write-host "--------------------------------------------"
write-host "End of RecoveryPlan Script"
################################################
# Stopping logging
################################################
Stop-Transcript
###############################################
# End of script
###############################################