-
Notifications
You must be signed in to change notification settings - Fork 300
/
Copy pathconfigure-sql-server-win-step.yml
289 lines (240 loc) · 10 KB
/
configure-sql-server-win-step.yml
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
#################################################################################
# Licensed to the .NET Foundation under one or more agreements. #
# The .NET Foundation licenses this file to you under the MIT license. #
# See the LICENSE file in the project root for more information. #
#################################################################################
parameters:
# Windows only parameters
- name: instanceName
type: string
default: MSSQLSERVER
- name: user
type: string
default: $(user)
- name: saUser
type: string
default: $(saUser)
- name: SQLRootPath
type: string
default: ''
- name: fileStreamDirectory
type: string
default: ''
- name: x64AliasRegistryPath
type: string
default: $(x64AliasRegistryPath)
- name: x86AliasRegistryPath
type: string
default: $(x86AliasRegistryPath)
- name: SQLAliasName
type: string
default: $(SQLAliasName)
- name: SQLAliasPort
type: string
default: $(SQLAliasPort)
- name: enableLocalDB
type: boolean
default: false
- name: localDbAppName
type: string
default: $(LocalDbAppName)
- name: localDbSharedInstanceName
type: string
default: $(LocalDbSharedInstanceName)
# Common parameters
- name: password
type: string
default: $(password)
- name: condition
type: string
default: and(succeeded(), eq(variables['Agent.OS'], 'Windows_NT'))
steps:
# windows only steps
- powershell: |
try
{
# enable TCP
Import-Module "sqlps"
$smo = 'Microsoft.SqlServer.Management.Smo.'
$wmi = new-object ($smo + 'Wmi.ManagedComputer').
# List the object properties, including the instance names.
$Wmi
# Enable the TCP protocol on the default instance.
$Tcp = $wmi.GetSmoObject("ManagedComputer[@Name='$env:COMPUTERNAME']/ ServerInstance[@Name='${{parameters.instanceName }}']/ServerProtocol[@Name='Tcp']")
$Tcp.IsEnabled = $true
$Tcp.Alter()
# Enable the NP protocol on the default instance.
$Np = $wmi.GetSmoObject("ManagedComputer[@Name='$env:COMPUTERNAME']/ ServerInstance[@Name='${{parameters.instanceName }}']/ServerProtocol[@Name='Np']")
$Np.IsEnabled = $true
$Np.Alter()
$Tcp
}
catch
{
$error[0] | format-list -force
throw
}
New-NetFirewallRule -DisplayName "SQL TCP Ports" -Direction Inbound –Protocol TCP –LocalPort 1433 -Action allow
$sqlSrvPath = (Get-WmiObject win32_service | ?{$_.DisplayName -eq 'SQL Server (${{parameters.instanceName }})'} | select @{Name="Path"; Expression={$_.PathName.split('"')[1]}}).Path
New-NetFirewallRule -DisplayName "sqlservr.exe" -Program "$sqlSrvPath"
displayName: 'Enable TCP, NP & Firewall [Win]'
condition: ${{parameters.condition }}
retryCountOnTaskFailure: 2
- powershell: |
$password = "${{parameters.password }}"
if ( "generated_placeholder" -eq $password )
{
$password = [guid]::NewGuid().ToString()
}
$machineName = $env:COMPUTERNAME
if ("${{parameters.instanceName }}" -ne "MSSQLSERVER"){
$machineName += "\${{parameters.instanceName }}"
}
Write-Host $machineName
Import-Module "sqlps"
$tries = 0
while ($true) {
$tries++
try {
Invoke-Sqlcmd -ServerInstance "$machineName" @"
CREATE LOGIN [${{parameters.user }}] WITH PASSWORD=N'$password',
DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF;
CREATE USER [${{parameters.user }}] FROM LOGIN [${{parameters.user }}];
ALTER SERVER ROLE [sysadmin] ADD MEMBER [${{parameters.user }}];
ALTER LOGIN [${{parameters.saUser }}] ENABLE;
ALTER LOGIN [${{parameters.saUser }}] WITH PASSWORD = '$password';
"@
break
} catch {
if ($tries -ge 5) {
Write-Host "##[error]Failed to create database user after $tries tries."
break
}
Write-Host "Failed to connect to server. Retrying in 5 seconds..."
Start-Sleep -Seconds 5
}
}
displayName: 'Create SQL user [Win]'
condition: ${{parameters.condition }}
env:
SQL_USER: ${{parameters.user }}
SQL_PASSWD: ${{parameters.password }}
- ${{ if ne(parameters.SQLRootPath, '') }}:
- powershell: |
#Enable FileStream
$instance = "${{parameters.instanceName }}"
$wmi = Get-WmiObject -Namespace "${{parameters.SQLRootPath }}" -Class FilestreamSettings | where {$_.InstanceName -eq $instance}
$wmi.EnableFilestream(3, $instance)
$machineName = $env:COMPUTERNAME
if ("${{parameters.instanceName }}" -ne "MSSQLSERVER"){
$machineName += "\${{parameters.instanceName }}"
}
#Change the access level for FileStream for SQLServer
Set-ExecutionPolicy Unrestricted
Import-Module "sqlps"
Invoke-Sqlcmd -ServerInstance "$machineName" @"
EXEC sp_configure filestream_access_level, 2;
RECONFIGURE;
"@
displayName: 'Enable FileStream [Win]'
condition: ${{parameters.condition }}
env:
SQL_USER: ${{parameters.user }}
SQL_PASSWD: ${{parameters.password }}
- ${{ if ne(parameters.FileStreamDirectory, '') }}:
- powershell: |
New-Item -Path ${{ parameters.fileStreamDirectory }} -ItemType Directory
displayName: 'Create FileStreamFolder'
retryCountOnTaskFailure: 1
condition: ${{parameters.condition }}
continueOnError: true
- powershell: |
$SQLServerName = ("{0}" -f [System.Net.Dns]::GetHostByName($env:computerName).HostName)
Write-Host FQDN is: $SQLServerName
if ((Test-Path -Path ${{parameters.x64AliasRegistryPath }}) -ne $true) {
New-Item ${{parameters.x64AliasRegistryPath }}
}
if ((Test-Path -Path ${{parameters.x86AliasRegistryPath }}) -ne $true) {
New-Item ${{parameters.x86AliasRegistryPath }}
}
$TCPAliasName = "DBMSSOCN, $SQLServerName, ${{parameters.SQLAliasPort }}"
New-ItemProperty -Path ${{parameters.x86AliasRegistryPath }} -Name ${{parameters.SQLAliasName }} -PropertyType string -Value $TCPAliasName
New-ItemProperty -Path ${{parameters.x64AliasRegistryPath }} -Name ${{parameters.SQLAliasName }} -PropertyType string -Value $TCPAliasName
displayName: 'Setup SQL Alias [Win]'
condition: ${{parameters.condition }}
- powershell: |
# Create Certificate
$computerDnsName = [System.Net.Dns]::Resolve($null).HostName
$certificate = New-SelfSignedCertificate -DnsName $computerDnsName,localhost -CertStoreLocation cert:\LocalMachine\My -FriendlyName test99 -KeySpec KeyExchange
# Get path to Private key (used later)
$keyPath = $certificate.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
$machineKeyPath = "$env:ProgramData\Microsoft\Crypto\RSA\MachineKeys\$keyPath"
# Add certificate to trusted roots
$store = new-object System.Security.Cryptography.X509Certificates.X509Store(
[System.Security.Cryptography.X509Certificates.StoreName]::Root,
"localmachine"
)
$store.open("MaxAllowed")
$store.add($certificate)
$store.close()
# Get SQL Server instances and add the Certificate
$instances = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL'
foreach ($instance in $instances){
$instance | ForEach-Object {
$_.PSObject.Properties | Where-Object { $_.Name -notmatch '^PS.*' } | ForEach-Object {
Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$($_.Value)\MSSQLServer\SuperSocketNetLib" -Name Certificate -Value $certificate.Thumbprint.ToLower()
# Grant read access to Private Key for SQL Service Account
if ($($_.Name) -eq "MSSQLSERVER") {
icacls $machineKeyPath /grant "NT Service\MSSQLSERVER:R"
} else {
icacls $machineKeyPath /grant "NT Service\MSSQL`$$($_.Name):R"
}
}
}
}
displayName: 'Add SQL Certificate [Win]'
condition: ${{parameters.condition }}
- powershell: |
# You need to restart SQL Server for the change to persist
# -Force takes care of any dependent services, like SQL Agent.
# Note: if the instance is named, replace MSSQLSERVER with MSSQL$ followed by
# the name of the instance (e.g. MSSQL$MYINSTANCE)
$serviceName = "${{parameters.instanceName }}"
$InstancePrefix = 'MSSQL$'
if ( "${{parameters.instanceName }}" -ne "MSSQLSERVER" )
{
$serviceName = $InstancePrefix+"${{parameters.instanceName }}"
}
Restart-Service -Name "$serviceName" -Force
Restart-Service -Name MSSQLSERVER* -Force
displayName: 'Restart SQL Server [Win]'
condition: ${{parameters.condition }}
- powershell: |
$arrService = Get-Service -Name "SQLBrowser"
$arrService
if ($arrService.Status -eq 'Stopped') {
Write-Host 'Attempt to run the service ...'
# updating the startup type to make sure it's not disabled
Set-Service -StartupType Automatic $arrService.Name
$arrService.Start()
$arrService.WaitForStatus('Running', '00:00:30')
if ($arrService.Status -eq 'Running') {
$arrService
} else {
Write-Error 'Timed out waiting for service to start.'
}
}
displayName: 'Start Sql Server Browser [Win]'
condition: ${{parameters.condition }}
- ${{ if parameters.enableLocalDB }}:
- powershell: |
#script to enable local db
SqlLocalDB info
#SqlLocalDB create ${{parameters.localDbAppName }}
SqlLocalDB info ${{parameters.localDbAppName }}
SqlLocalDB share ${{parameters.localDbAppName }} ${{parameters.LocalDbSharedInstanceName }}
SqlLocalDB start ${{parameters.localDbAppName }}
SqlLocalDB info ${{parameters.localDbAppName }}
sqlcmd -S "(localdb)\.\${{parameters.LocalDbSharedInstanceName }}" -q "SELECT @@VERSION"
displayName: 'Enable LocalDB [Win]'
condition: ${{parameters.condition }}