-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReimageVMSS.ps1
64 lines (52 loc) · 2.28 KB
/
ReimageVMSS.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
param(
[Parameter(mandatory=$true)]
[string] $vmScaleSetResourceGroupName,
[Parameter(mandatory=$true)]
[string] $vmScaleSetName,
[Parameter(mandatory=$false)]
[string] $frontDoorName,
[Parameter(mandatory=$false)]
[string] $frontDoorResourceGroupName
)
Write-Output "Connecting to AzureRunAsConnection"
$connectionName = "AzureRunAsConnection"
try {
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
} catch {
if (!$servicePrincipalConnection) {
$errorMessage = "Connection $connectionName not found."
throw $errorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
Write-Output "Gathering VM instances for VM Scale Set $vmScaleSetName"
$vmInstances = $(Get-AzureRmVmssVM -ResourceGroupName $vmScaleSetResourceGroupName -VMScaleSetName $vmScaleSetName)
Write-Output "Reimaging VM instances"
foreach ( $vmInstanceName in $vmInstances ) {
# Check if there is at least one healthy VM
while( $($vmInstances).ProvisioningState -Contains "Updating" ) {
Write-Output "Waiting for all VMs to become Succeeded"
Start-Sleep -Seconds 60
}
# Upgrade the selected InstanceID
Write-Output "Upgrading $($vmInstanceName.Name)"
Update-AzureRmVmssInstance -ResourceGroupName $vmScaleSetResourceGroupName -VMScaleSetName $vmScaleSetName -InstanceId "$($vmInstanceName.InstanceID)"
# Reimage the selected InstanceID
Write-Output "Reimaging $($vmInstanceName.Name)"
Set-AzureRmVmssVM -Reimage -ResourceGroupName $vmScaleSetResourceGroupName -VMScaleSetName $vmScaleSetName -InstanceId "$($vmInstanceName.InstanceID)"
# Cooldown period before starting the next VM
Start-Sleep -Seconds 360
}
if ( $frontDoorName -and $frontDoorResourceGroupName ) {
Write-Output "Purging Front Door Cache"
Remove-AzFrontDoorContent -ResourceGroupName $frontDoorResourceGroupName -Name $frontDoorName -ContentPath "/*"
}