forked from dataplat/dbatools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd-DbaAgReplica.ps1
218 lines (177 loc) · 11.3 KB
/
Add-DbaAgReplica.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
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Add-DbaAgReplica {
<#
.SYNOPSIS
Adds a replica to an availability group on a SQL Server instance.
.DESCRIPTION
Adds a replica to an availability group on a SQL Server instance.
Automatically creates a database mirroring endpoint if required.
.PARAMETER SqlInstance
The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.
.PARAMETER SqlCredential
Login to the SqlInstance instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
.PARAMETER Name
The name of the replica. Defaults to the SQL Server instance name.
.PARAMETER AvailabilityMode
Sets the availability mode of the availability group replica. Options are: AsynchronousCommit and SynchronousCommit. SynchronousCommit is default.
.PARAMETER FailoverMode
Sets the failover mode of the availability group replica. Options are Automatic and Manual. Automatic is default.
.PARAMETER BackupPriority
Sets the backup priority availability group replica. Default is 50.
.PARAMETER Endpoint
By default, this command will attempt to find a DatabaseMirror endpoint. If one does not exist, it will create it.
If an endpoint must be created, the name "hadr_endpoint" will be used. If an alternative is preferred, use Endpoint.
.PARAMETER Passthru
Don't create the replica, just pass thru an object that can be further customized before creation.
.PARAMETER InputObject
Enables piping from Get-DbaAvailabilityGroup.
.PARAMETER ConnectionModeInPrimaryRole
Specifies the connection intent modes of an Availability Replica in primary role. AllowAllConnections by default.
.PARAMETER ConnectionModeInSecondaryRole
Specifies the connection modes of an Availability Replica in secondary role. AllowAllConnections by default.
.PARAMETER ReadonlyRoutingConnectionUrl
Sets the read only routing connection url for the availability replica.
.PARAMETER SeedingMode
Specifies how the secondary replica will be initially seeded.
Automatic enables direct seeding. This method will seed the secondary replica over the network. This method does not require you to backup and restore a copy of the primary database on the replica.
Manual requires you to create a backup of the database on the primary replica and manually restore that backup on the secondary replica.
.PARAMETER Certificate
Specifies that the endpoint is to authenticate the connection using the certificate specified by certificate_name to establish identity for authorization.
The far endpoint must have a certificate with the public key matching the private key of the specified certificate.
.PARAMETER WhatIf
Shows what would happen if the command were to run. No actions are actually performed.
.PARAMETER Confirm
Prompts you for confirmation before executing any changing operations within the command.
.PARAMETER EnableException
By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
.NOTES
Tags: AvailabilityGroup, HA, AG
Author: Chrissy LeMaire (@cl), netnerds.net
Website: https://dbatools.io
Copyright: (c) 2018 by dbatools, licensed under MIT
License: MIT https://opensource.org/licenses/MIT
.LINK
https://dbatools.io/Add-DbaAgReplica
.EXAMPLE
PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b
Adds sql2017b to the SharePoint availability group on sql2017a
.EXAMPLE
PS C:\> Get-DbaAvailabilityGroup -SqlInstance sql2017a -AvailabilityGroup SharePoint | Add-DbaAgReplica -SqlInstance sql2017b -FailoverMode Manual
Adds sql2017b to the SharePoint availability group on sql2017a with a manual failover mode.
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
param (
[DbaInstanceParameter[]]$SqlInstance,
[PSCredential]$SqlCredential,
[string]$Name,
[ValidateSet('AsynchronousCommit', 'SynchronousCommit')]
[string]$AvailabilityMode = "SynchronousCommit",
[ValidateSet('Automatic', 'Manual', 'External')]
[string]$FailoverMode = "Automatic",
[int]$BackupPriority = 50,
[ValidateSet('AllowAllConnections', 'AllowReadWriteConnections')]
[string]$ConnectionModeInPrimaryRole = 'AllowAllConnections',
[ValidateSet('AllowAllConnections', 'AllowNoConnections', 'AllowReadIntentConnectionsOnly')]
[string]$ConnectionModeInSecondaryRole = 'AllowAllConnections',
[ValidateSet('Automatic', 'Manual')]
[string]$SeedingMode = 'Automatic',
[string]$Endpoint,
[switch]$Passthru,
[string]$ReadonlyRoutingConnectionUrl,
[string]$Certificate,
[parameter(ValueFromPipeline, Mandatory)]
[Microsoft.SqlServer.Management.Smo.AvailabilityGroup]$InputObject,
[switch]$EnableException
)
process {
foreach ($instance in $SqlInstance) {
try {
$server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential -MinimumVersion 11
} catch {
Stop-Function -Message "Error occurred while establishing connection to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
}
if ($Certificate) {
$cert = Get-DbaDbCertificate -SqlInstance $server -Certificate $Certificate
if (-not $cert) {
Stop-Function -Message "Certificate $Certificate does not exist on $instance" -ErrorRecord $_ -Target $Certificate -Continue
}
}
$ep = Get-DbaEndpoint -SqlInstance $server -Type DatabaseMirroring
if (-not $ep) {
if ($Pscmdlet.ShouldProcess($server.Name, "Adding endpoint named $Endpoint to $instance")) {
if (-not $Endpoint) {
$Endpoint = "hadr_endpoint"
}
$ep = New-DbaEndpoint -SqlInstance $server -Name hadr_endpoint -Type DatabaseMirroring -EndpointEncryption Supported -EncryptionAlgorithm Aes -Certificate $Certificate
$null = $ep | Start-DbaEndpoint
}
}
if ((Test-Bound -Not -ParameterName Name)) {
$Name = $server.DomainInstanceName
}
if ($Pscmdlet.ShouldProcess($server.Name, "Creating a replica for $($InputObject.Name) named $Name")) {
try {
$replica = New-Object Microsoft.SqlServer.Management.Smo.AvailabilityReplica -ArgumentList $InputObject, $Name
$replica.EndpointUrl = $ep.Fqdn
$replica.FailoverMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaFailoverMode]::$FailoverMode
$replica.AvailabilityMode = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaAvailabilityMode]::$AvailabilityMode
if ($server.EngineEdition -ne "Standard") {
$replica.ConnectionModeInPrimaryRole = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaConnectionModeInPrimaryRole]::$ConnectionModeInPrimaryRole
$replica.ConnectionModeInSecondaryRole = [Microsoft.SqlServer.Management.Smo.AvailabilityReplicaConnectionModeInSecondaryRole]::$ConnectionModeInSecondaryRole
}
$replica.BackupPriority = $BackupPriority
if ($ReadonlyRoutingConnectionUrl) {
$replica.ReadonlyRoutingConnectionUrl = $ReadonlyRoutingConnectionUrl
}
if ($SeedingMode -and $server.VersionMajor -ge 13) {
$replica.SeedingMode = $SeedingMode
if ($SeedingMode -eq "Automatic") {
$serviceaccount = $server.ServiceAccount.Trim()
$saname = ([DbaInstanceParameter]($server.DomainInstanceName)).ComputerName
if ($serviceaccount) {
if ($serviceaccount.StartsWith("NT ")) {
$serviceaccount = "$saname`$"
}
if ($serviceaccount.StartsWith("$saname")) {
$serviceaccount = "$saname`$"
}
if ($serviceaccount.StartsWith(".")) {
$serviceaccount = "$saname`$"
}
}
if (-not $serviceaccount) {
$serviceaccount = "$saname`$"
}
$null = Grant-DbaAgPermission -SqlInstance $server -Type AvailabilityGroup -AvailabilityGroup $InputObject.Name -Login $serviceaccount -Permission CreateAnyDatabase
}
}
if ($Passthru) {
return $replica
}
$defaults = 'ComputerName', 'InstanceName', 'SqlInstance', 'AvailabilityGroup', 'Name', 'Role', 'RollupSynchronizationState', 'AvailabilityMode', 'BackupPriority', 'EndpointUrl', 'SessionTimeout', 'FailoverMode', 'ReadonlyRoutingList'
$InputObject.AvailabilityReplicas.Add($replica)
$agreplica = $InputObject.AvailabilityReplicas[$Name]
if ($InputObject.State -eq 'Existing') {
Invoke-Create -Object $replica
$null = Join-DbaAvailabilityGroup -SqlInstance $instance -SqlCredential $SqlCredential -AvailabilityGroup $InputObject.Name
$agreplica.Alter()
}
Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name ComputerName -value $agreplica.Parent.ComputerName
Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name InstanceName -value $agreplica.Parent.InstanceName
Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name SqlInstance -value $agreplica.Parent.SqlInstance
Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name AvailabilityGroup -value $agreplica.Parent.Name
Add-Member -Force -InputObject $agreplica -MemberType NoteProperty -Name Replica -value $agreplica.Name # backwards compat
Select-DefaultView -InputObject $agreplica -Property $defaults
} catch {
$msg = $_.Exception.InnerException.InnerException.Message
if (-not $msg) {
$msg = $_
}
Stop-Function -Message $msg -ErrorRecord $_ -Continue
}
}
}
}
}