-
Notifications
You must be signed in to change notification settings - Fork 0
/
SetSqlVmIp.ps1
88 lines (78 loc) · 2.98 KB
/
SetSqlVmIp.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
param (
[Object]$RecoveryPlanContext
)
Write-Output $RecoveryPlanContext
$AutomationVariableName = 'PrivateIpSqlDb'
$AutomationAccountName = 'asrdraccount'
if($RecoveryPlanContext.FailoverDirection -ne 'PrimaryToSecondary')
{
Write-Output 'Script is ignored since Azure is not the target'
}
else
{
$VMinfo = $RecoveryPlanContext.VmMap | Get-Member | Where-Object MemberType -EQ NoteProperty | select -ExpandProperty Name
$vmMap = $RecoveryPlanContext.VmMap
Write-Output ("Found the following VMGuid(s): `n" + $VMInfo)
if ($VMInfo -is [system.array])
{
$VMinfo = $VMinfo[0]
Write-Output "Found multiple VMs in the Recovery Plan"
}
else
{
Write-Output "Found only a single VM in the Recovery Plan"
}
$RGName = $RecoveryPlanContext.VmMap.$VMInfo.ResourceGroupName
Write-OutPut ("Name of resource group: " + $RGName)
Try
{
"Logging in to Azure..."
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
"Selecting Azure subscription..."
Select-AzureRmSubscription -SubscriptionId $Conn.SubscriptionID -TenantId $Conn.tenantid
}
Catch
{
$ErrorMessage = 'Login to Azure subscription failed.'
$ErrorMessage += " `n"
$ErrorMessage += 'Error: '
$ErrorMessage += $_
Write-Error -Message $ErrorMessage `
-ErrorAction Stop
}
foreach($VMID in $VMinfo)
{
Try
{
$VMi = $vmMap.$VMID
$VM = Get-AzureRmVm -ResourceGroupName $RGName -Name $VMi.RoleName
$nics = Get-AzureRmNetworkInterface -ResourceGroupName $VM.ResourceGroupName
foreach ($nic in $nics)
{
if($nic.VirtualMachine.Id.Equals($VM.Id))
{
Write-Output ("Found a matching nic for this VM:")
Break
}
else
{
# ignore,not a match
}
}
$PRIVIP = $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAddress
Set-AzureRmAutomationVariable -AutomationAccountName $AutomationAccountName -Name $AutomationVariableName -ResourceGroupName $VM.ResourceGroupName -Value $PRIVIP -Encrypted $False
Write-Output ("Set the Runbook variable with the Private IP of the SQL Server VM : " + $PRIVIP)
}
Catch
{
$ErrorMessage = 'Failed to set the Runbook variable with the Private IP of the SQL Server VM.'
$ErrorMessage += " `n"
$ErrorMessage += 'Error: '
$ErrorMessage += $_
Write-Error -Message $ErrorMessage `
-ErrorAction Stop
}
}
}