DSCResources/MSFT_xSQLAOGroupEnsure/MSFT_xSQLAOGroupEnsure.psm1

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
$currentPath = Split-Path -Parent $MyInvocation.MyCommand.Path
Write-Verbose -Message "CurrentPath: $currentPath"

Import-Module $currentPath\..\..\xSQLServerHelper.psm1 -Verbose:$false -ErrorAction Stop

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [parameter(Mandatory = $true)]
        [ValidateSet('Present','Absent')]
        [System.String]
        $Ensure,

        [parameter(Mandatory = $true)]
        [System.String]
        $AvailabilityGroupName,
        
        [System.String]
        $SQLServer = $env:COMPUTERNAME,

        [ValidateNotNull()] 
        [System.String]
        $SQLInstanceName= 'MSSQLSERVER',

        [parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $SetupCredential
    )

    $sql = Connect-SQL -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName -SetupCredential $SetupCredential
    
    $vConfigured = Test-TargetResource -Ensure $Ensure -AvailabilityGroupName $AvailabilityGroupName -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName -SetupCredential $SetupCredential

    $returnValue = @{
        Ensure = $vConfigured
        AvailabilityGroupName = $sql.AvailabilityGroups[$AvailabilityGroupName]
        AvailabilityGroupNameListener = $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.name
        AvailabilityGroupNameIP = $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.availabilitygrouplisteneripaddresses.IPAddress
        AvailabilityGroupSubMask =  $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.availabilitygrouplisteneripaddresses.SubnetMask
        AvailabilityGroupPort =  $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityGroupListeners.portnumber
        AvailabilityGroupNameDatabase = $sql.AvailabilityGroups[$AvailabilityGroupName].AvailabilityDatabases.name
        BackupDirectory = ''
        SQLServer = $SQLServer
        SQLInstanceName = $SQLInstanceName
    }

    $returnValue
}

function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [ValidateSet('Present', 'Absent')]
        [System.String]
        $Ensure,

        [parameter(Mandatory = $true)]
        [System.String]
        $AvailabilityGroupName,

        [System.String]
        $AvailabilityGroupNameListener = $AvailabilityGroupName,

        [System.String[]]
        $AvailabilityGroupNameIP,

        [System.String[]]
        $AvailabilityGroupSubMask,

        [System.UInt32]
        $AvailabilityGroupPort = '1433',

        [ValidateSet('None', 'ReadOnly', 'ReadIntent')]
        [System.String]
        $ReadableSecondary = 'ReadOnly',

        [ValidateSet('Primary', 'Secondary')]
        [System.String]
        $AutoBackupPreference = 'Primary',
        
        [System.UInt32]
        $BackupPriority = '50',
        
        [System.UInt32]
        $EndPointPort = '5022',

        [System.String]
        $SQLServer = $env:COMPUTERNAME,

        [System.String]
        $SQLInstanceName = 'MSSQLSERVER',
        
        [parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $SetupCredential
    )

    $null = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo')
    $null = [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SmoExtended')
   
    $sql = Connect-SQL -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName -SetupCredential $SetupCredential

    if (($AvailabilityGroupNameIP -and !$AvailabilityGroupSubMask) -or (!$AvailabilityGroupNameIP -and $AvailabilityGroupSubMask))
    {
        throw 'AvailabilityGroupNameIP and AvailabilityGroupSubMask must both be passed for Static IP assignment.'
    }

    switch ($Ensure)
    {
        'Present'
        {
            Grant-ServerPerms -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName -AuthorizedUser 'NT AUTHORITY\SYSTEM' -SetupCredential $SetupCredential
            New-ListenerADObject -AvailabilityGroupNameListener $AvailabilityGroupNameListener -SetupCredential $SetupCredential -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName
 
            $FailoverCondition = 3
            $HealthCheckTimeout = 30000
            $ConnectionModeInPrimary = 'AllowAllConnections'    

            $ConnectionModeInSecondaryRole = switch ($ReadableSecondary)
            {
                'None'
                {
                    'AllowNoConnections'
                }
                
                'ReadOnly'
                {
                    'AllowAllConnections'
                }
                
                'ReadIntent'
                {
                    'AllowReadIntentConnectionsOnly'
                }
                
                Default 
                {
                    'AllowAllConnections'
                }
            } 

           # Get Servers participating in the cluster
           # First two nodes will account for Syncronous Automatic Failover, Any additional will be Asyncronous
           try
           {
                $nodes = Get-ClusterNode -cluster $sql.ClusterName -Verbose:$false | Select-Object -ExpandProperty name
                $syncNodes = $nodes | Select-Object -First 2
                $asyncNodes = $nodes | Select-Object -Skip 2
                $availabilityGroup = New-Object -typename Microsoft.SqlServer.Management.Smo.AvailabilityGroup -ArgumentList $SQL, $AvailabilityGroupName
                $availabilityGroup.AutomatedBackupPreference = $AutoBackupPreference
                $availabilityGroup.FailureConditionLevel = $FailoverCondition
                $availabilityGroup.HealthCheckTimeout = $HealthCheckTimeout
           }
           catch
           {
                throw "Failed to connect to Cluster Nodes from $($sql.ClusterName)"
           }

           # Loop through Sync nodes Create Replica Object Assign properties and add it to AvailabilityGroup
           foreach ($node in $syncNodes)
           { 
                Try
                {
                    $Replica = New-Object -typename Microsoft.SqlServer.Management.Smo.AvailabilityReplica -ArgumentList $availabilityGroup, $node
                    $Replica.EndpointUrl = "TCP://$($node):$EndPointPort"
                    $Replica.FailoverMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaFailoverMode]::Automatic
                    $Replica.AvailabilityMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaAvailabilityMode]::SynchronousCommit
                    # Backup Priority Gives the ability to set a priority of one secondany over another valid values are from 1 - 100
                    $Replica.BackupPriority = $BackupPriority
                    $Replica.ConnectionModeInPrimaryRole = $ConnectionModeInPrimary
                    $replica.ConnectionModeInSecondaryRole = $ConnectionModeInSecondaryRole 
                    $availabilityGroup.AvailabilityReplicas.Add($Replica)
                }
                catch
                {
                    throw "Failed to add $Replica to the Availability Group $AvailabilityGroupName"
                }         
            }

            # Loop through ASync nodes Create Replica Object Assign properties and add it to AvailabilityGroup
            foreach ($node in $AsyncNodes)
            {
                try
                {
                    $asyncReplica = New-Object -typename Microsoft.SqlServer.Management.Smo.AvailabilityReplica -ArgumentList $availabilityGroup, $node
                    $asyncReplica.EndpointUrl = "TCP://$($node):$EndPointPort"
                    $asyncReplica.FailoverMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaFailoverMode]::Manual
                    $asyncReplica.AvailabilityMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaAvailabilityMode]::ASynchronousCommit
                    $asyncReplica.BackupPriority = $BackupPriority
                    $asyncReplica.ConnectionModeInPrimaryRole =  $ConnectionModeInPrimary
                    $asyncReplica.ConnectionModeInSecondaryRole = $ConnectionModeInSecondaryRole 
                    $AvailabilityGroup.AvailabilityReplicas.Add($asyncReplica)
                }
                catch
                {
                    Write-Error "Failed to add $asyncReplica to the Availability Group $AvailabilityGroupName"
                }
            }
        
            try
            {
                $AgListener = New-Object -typename Microsoft.SqlServer.Management.Smo.AvailabilityGroupListener -ArgumentList $AvailabilityGroup, $AvailabilityGroupNameListener
                $AgListener.PortNumber =$AvailabilityGroupPort
            }
            catch
            {
                Write-Error -Message ('{0}: Failed to Create AG Listener Object' -f ((Get-Date -format yyyy-MM-dd_HH-mm-ss)))
            }
         
         
            if ($AvailabilityGroupNameIP)
            {
                foreach ($IP in $AvailabilityGroupNameIP)
                {
                    $AgListenerIp = New-Object -typename Microsoft.SqlServer.Management.Smo.AvailabilityGroupListenerIPAddress -ArgumentList $AgListener
                    $AgListenerIp.IsDHCP = $false
                    $AgListenerIp.IPAddress = $IP
                    $AgListenerIp.SubnetMask = $AvailabilityGroupSubMask
                    $AgListener.AvailabilityGroupListenerIPAddresses.Add($AgListenerIp)
                    New-VerboseMessage -Message "Added Static IP $IP to $AvailabilityGroupNameListener..."
            
                }
            }
            else
            {
                # Utilize Dynamic IP since no Ip was passed
                $AgListenerIp = New-Object -typename Microsoft.SqlServer.Management.Smo.AvailabilityGroupListenerIPAddress -ArgumentList $AgListener
                $AgListenerIp.IsDHCP = $true
                $AgListener.AvailabilityGroupListenerIPAddresses.Add($AgListenerIp)
                New-VerboseMessage -Message "Added DynamicIP to $AvailabilityGroupNameListener..."
            }
         
            try
            {
                $AvailabilityGroup.AvailabilityGroupListeners.Add($AgListener);
            }
            catch
            {
                throw "Failed to Add $AvailabilityGroupNameListener to $AvailabilityGroupName..."
            }    

            # Add Availabilty Group to the SQL connection
            try
            {
                $SQL.AvailabilityGroups.Add($availabilityGroup)
                New-VerboseMessage -Message "Added $availabilityGroupName Availability Group to Connection"  
            }
            catch
            {
                throw "Unable to Add $AvailabilityGroup to $SQLServer\$SQLInstanceName"
            }
           
            # Create Availability Group
            try
            {
                $availabilityGroup.Create()

                New-VerboseMessage -Message "Created Availability Group $availabilityGroupName"
            }
            catch
            {
                throw "Unable to Create $AvailabilityGroup on $SQLServer\$SQLInstanceName"
            }
        }

        'Absent'
        { 
            try
            {
                 $sql.AvailabilityGroups[$AvailabilityGroupName].Drop()

                 New-VerboseMessage -Message "Dropped $AvailabilityGroupName" 
            }
            catch
            {
                 throw "Unable to Drop $AvailabilityGroup on $SQLServer\$SQLInstanceName"
            }
        }
    }
}

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [parameter(Mandatory = $true)]
        [ValidateSet('Present', 'Absent')]
        [System.String]
        $Ensure,

        [parameter(Mandatory = $true)]
        [System.String]
        $AvailabilityGroupName,

        [System.String]
        $AvailabilityGroupNameListener,

        [System.String[]]
        $AvailabilityGroupNameIP,

        [System.String[]]
        $AvailabilityGroupSubMask,

        [System.UInt32]
        $AvailabilityGroupPort,

        [ValidateSet('None', 'ReadOnly', 'ReadIntent')]
        [System.String]
        $ReadableSecondary ='ReadOnly',

        [ValidateSet('Primary', 'Secondary')]
        [System.String]
        $AutoBackupPreference = 'Primary',
        
        [System.UInt32]
        $BackupPriority = '50',
        
        [System.UInt32]
        $EndPointPort = '5022',

        [System.String]
        $SQLServer = $env:COMPUTERNAME,

        [System.String]
        $SQLInstanceName = 'MSSQLSERVER',
        
        [parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $SetupCredential
    )

    $sql = Connect-SQL -SQLServer $SQLServer -SQLInstanceName $SQLInstanceName -SetupCredential $SetupCredential

    $result = $false

    switch ($Ensure)
    {
        'Present'
        {
            $availabilityGroupPresent = $sql.AvailabilityGroups.Contains($AvailabilityGroupName)
            if ($availabilityGroupPresent)
            {
                $result = $true
            }
        }

        'Absent'
        {
            if (!$sql.AvailabilityGroups[$AvailabilityGroupName])
            {
                $result = $true
            }
        }
    }

    return $result
}

Export-ModuleMember -Function *-TargetResource