-
Notifications
You must be signed in to change notification settings - Fork 17
/
azure-az-sql-create.ps1
655 lines (548 loc) · 22.2 KB
/
azure-az-sql-create.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
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
<#
.SYNOPSIS
powershell script to list or create a new Azure SQL server and / or database in Azure Resource Manager
.DESCRIPTION
powershell script to list or create a new Azure SQL server and / or database in Azure Resource Manager
to enable script execution, you may need to Set-ExecutionPolicy Bypass -Force
Copyright 2017 Microsoft Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
requires azure powershell sdk (install-module Az)
script does the following:
logs into azure rm
checks location for validity and for availability of Azure SQL
checks for resource group and creates if not exists
checks resource group for azure sql servers
if sql server is specified, will query server for existing database
will generate / prompt for sql server name if one is not existing / specified
checks password for complexity requirements
creates sql server and database with firewall rules
on success displays connection string info
https://aka.ms/azure-az-sql-create.ps1
https://docs.microsoft.com/en-us/azure/sql-database/sql-database-get-started-powershell
https://docs.microsoft.com/en-us/azure/sql-database/sql-database-performance-guidance
https://docs.microsoft.com/en-us/azure/sql-database/sql-database-managed-instance-create-manage
minimum parameters : resource group, location, databaseName, adminPassword
.NOTES
File Name : azure-az-sql-create.ps1
Author : jagilber
History : 190127 add sql managed instances
180730 add all editions as validation set
.EXAMPLE
.\azure-az-sql-create.ps1 -resourceGroupName newResourceGroup -location eastus -databaseName myNewDatabase -adminPassword myNewP@ssw0rd
create a new sql database on an existing or new sql server
.EXAMPLE
.\azure-az-sql-create.ps1 -resourceGroupName newResourceGroup -location eastus -databaseName myNewDatabase -credentials (get-credential) -generateUniqueName
create a new sql database on a new random named sql server using prompted credentials
.EXAMPLE
.\azure-az-sql-create.ps1 -resourceGroupName existingResourceGroup -listAvailable
list available sql servers and databases in resource group existingResourceGroup
.EXAMPLE
.\azure-az-sql-create.ps1 -resourceGroupName existingResourceGroup -server sql-server-01 -listAvailable
list existing databases on sql-server-01 in resource group existingResourceGroup
.EXAMPLE
.\azure-az-sql-create.ps1 -resourceGroupName existingResourceGroup -server sql-server-01 -serviceTier Basic -databaseName TestDB
create a new sql database TestDB on sql-server-01 using service tier Basic
.PARAMETER resourceGroupName
required paramater for the resource group name for new database and sql server
.PARAMETER location
required paramater for the resource group name region location
.PARAMETER serverName
if specified, will be used for the sql server name.
will check and if not exists, create new sql server. if named sql server exists, existing sql server will be used.
if not specified, or not exists, will prompt for name or will generate random name if generateUniqueName is specified.
.PARAMETER databaseName
if specifed, will be used for the database name.
will check and if not exists, create new database.
if not specified, will generate random name if generateUniqueName is specified.
.PARAMETER adminUserName
if specified, will be used for sql administrator logon.
if not specified, 'sql-administrator' will be used.
NOTE: admin and administrator can NOT be used.
.PARAMETER adminPassword
requred parameter for the sql administrator password.
will be checked for current azure rm password complexity requirements.
.PARAMETER credentials
if specified, will be used for the sql administrator and password credentials
NOTE: use (get-credential) as the argument.
.PARAMETER generateUniqueName
if specified, will generate random sql server name which have to be globally unique
.PARAMETER nsgStartIpAllow
if specified, ip address will be the starting range of ip addresses to allow
.PARAMETER nsgEndIpAllow
if specified, ip address will be the ending range of ip addresses to allow
.PARAMETER maskPassword
if specified, will not display provided password in connection string output
.PARAMETER listAvailable
if specified, will list available sql servers and databases in resource gropup
.PARAMETER serviceTier
if specified, will use the provided service tier.
by default, will use cheapest tier 'Basic'
https://docs.microsoft.com/en-us/azure/sql-database/sql-database-performance-guidance
.PARAMETER sqlServerVersion
sql server version. default is 12.0
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$resourceGroupName,
[string]$location,
[string]$servername,
[string]$adminUserName = "sql-administrator",
[string]$adminPassword,
[pscredential]$credentials,
[string]$nsgStartIpAllow = "0.0.0.0",
[string]$nsgEndIpAllow = "255.255.255.255",
[string]$databaseName,
[switch]$generateUniqueName,
[switch]$maskPassword,
[switch]$listAvailable,
[string]$logFile,
[ValidateSet('Basic','None','Standard','Premium','DataWarehouse','Free','Stretch','GeneralPurpose','BusinessCritical')]
[string]$serviceTier = "Basic",
[string]$sqlServerVersion = "12.0"
)
$erroractionpreference = "Continue"
$warningPreference = "Continue"
$script:credential = $null
$script:servername = $servername
$script:databasename = $databaseName
$script:createSqlServer = $false
$script:createSqlDatabase = $false
# ----------------------------------------------------------------------------------------------------------------
function main()
{
log-info "$([System.DateTime]::Now):starting"
if (!(Get-Module Az -ListAvailable))
{
if ((read-host "powershell module azure az sdk (Az) is required for this script. is it ok to install?[y|n]") -imatch "y")
{
Install-Module Az
Import-Module Az
}
else
{
return
}
}
# see if we need to auth
authenticate-Az
if ($listAvailable)
{
list-availableSqlServers
return
}
if ($location)
{
log-info "checking location $($location)"
if (!(Get-AzLocation | Where-Object Location -Like $location) -or [string]::IsNullOrEmpty($location))
{
(Get-AzLocation).Location
write-warning "location: $($location) not found. supply -location using one of the above locations and restart script."
exit 1
}
}
log-info "checking for existing resource group $($resourceGroupName)"
# create resource group if it does not exist
$resourceGroupInfo = Get-AzResourceGroup -Name $resourceGroupName -ErrorAction SilentlyContinue
if (!$resourceGroupInfo)
{
if ($location)
{
log-info "creating resource group $($resourceGroupName) in location $($location)"
New-AzResourceGroup -Name $resourceGroupName -Location $location
}
else
{
log-info "resource group does not exist and location not specified. exiting"
exit 1
}
}
else
{
log-info "resource group $($resourceGroupName) already exists."
if (!$location)
{
$location = $resourceGroupInfo.Location
}
}
# make sure sql available in region
$sqlAvailable = Get-AzSqlCapability -LocationName $location
log-info "sql server capability in $($location) : $($sqlAvailable.Status)"
if (!$sqlAvailable)
{
log-info "sql not available in this region. exiting"
return
}
# verify edition
$editions = $sqlAvailable.SupportedServerVersions.supportedEditions.EditionName
if (!($editions -ieq $serviceTier))
{
log-info "please choose another service tier."
log-info "tiers available in this location:"
log-info $editions
return
}
# verify version
$versions = $sqlAvailable.SupportedServerVersions.ServerVersionName
if (!($versions -ieq $sqlServerVersion))
{
log-info "please choose another version."
log-info "versions available in this location:"
log-info $versions
return
}
$created = create-database
if (!$created -and $generateUniqueName)
{
# retry 1 time in case of server name issue or db exists on server specified and -generateUniqueName was passed
log-info "clearing server name and retrying 1 time"
$script:servername = ""
$created = create-database
}
if ($created)
{
if ($maskPassword -or !$script:createSqlServer)
{
$adminPassword = "{enter_sql_password_here}"
}
log-info "connection string ADO:`r`nServer=tcp:$($script:servername).database.windows.net,1433;Initial Catalog=$($script:databaseName);Persist Security Info=False;User ID=$($adminUserName);Password=$($adminPassword);MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
$odbcString = "connection string ODBC Native client:`r`nDRIVER=SQL Server Native Client 11.0;Server=tcp:$($script:servername).database.windows.net,1433;Database=$($script:databaseName);Uid=$($adminUserName)@$($script:servername);Pwd=$($adminPassword);Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;"
log-info $odbcString
return $odbcString
}
return $false
}
# ----------------------------------------------------------------------------------------------------------------
function authenticate-Az()
{
# make sure at least wmf 5.0 installed
if ($PSVersionTable.PSVersion -lt [version]"5.0.0.0")
{
log-info "update version of powershell to at least wmf 5.0. exiting..." -ForegroundColor Yellow
start-process "https://www.bing.com/search?q=download+windows+management+framework+5.0"
# start-process "https://www.microsoft.com/en-us/download/details.aspx?id=50395"
exit
}
# verify NuGet package
$nuget = get-packageprovider nuget -Force
if (-not $nuget -or ($nuget.Version -lt [version]::New("2.8.5.22")))
{
log-info "installing nuget package..."
install-packageprovider -name NuGet -minimumversion ([version]::New("2.8.5.201")) -force
}
$allModules = (get-module Az* -ListAvailable).Name
# install Az module
if ($allModules -inotcontains "Az")
{
# at least need profile, resources, sql
if ($allModules -inotcontains "Az.accounts")
{
log-info "installing az.accounts powershell module..."
install-module Az.accounts -force
}
if ($allModules -inotcontains "Az.resources")
{
log-info "installing Az.resources powershell module..."
install-module Az.resources -force
}
if ($allModules -inotcontains "Az.compute")
{
log-info "installing Az.compute powershell module..."
install-module Az.sql -force
}
Import-Module Az.accounts
Import-Module Az.resources
Import-Module Az.sql
}
else
{
Import-Module Az
}
# authenticate
try
{
Get-AzResourceGroup | Out-Null
}
catch
{
if(!(connect-Azaccount))
{
log-info "exception authenticating. exiting $($error | out-string)" -ForegroundColor Yellow
exit 1
}
}
#Save-AzContext -Path $profileContext -Force
}
# ----------------------------------------------------------------------------------------------------------------
function check-credentials()
{
try
{
log-info "checking adminUserName account name $($adminUsername)"
if ($adminUsername.ToLower() -eq "admin" -or $adminUsername.ToLower() -eq "administrator")
{
log-info "adminUserName cannot be 'admin' or 'administrator'. exiting"
return
}
log-info "using admin name: $($adminUserName)"
log-info "checking password"
if (!$credentials)
{
if ([string]::IsNullOrEmpty($adminPassword))
{
$script:credential = Get-Credential
}
else
{
$SecurePassword = $adminPassword | ConvertTo-SecureString -AsPlainText -Force
$script:credential = new-object Management.Automation.PSCredential -ArgumentList $adminUsername, $SecurePassword
}
}
else
{
$script:credential = $credentials
}
$adminUsername = $script:credential.UserName
$adminPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($script:credential.Password))
$count = 0
# uppercase check
if ($adminPassword -match "[A-Z]") { $count++ }
# lowercase check
if ($adminPassword -match "[a-z]") { $count++ }
# numeric check
if ($adminPassword -match "\d") { $count++ }
# specialKey check
if ($adminPassword -match "\W") { $count++ }
if ($adminPassword.Length -lt 8 -or $adminPassword.Length -gt 123 -or $count -lt 3)
{
Write-warning @"
azure password requirements at time of writing (3/2017):
The supplied password must be between 8-123 characters long and must satisfy at least 3 of password complexity requirements from the following:
1) Contains an uppercase character
2) Contains a lowercase character
3) Contains a numeric digit
4) Contains a special character.
correct password and restart script.
"@
exit 1
}
return $true
}
catch
{
log-info "exception: checking credentials $($error)"
$error.Clear()
return $false
}
}
# ----------------------------------------------------------------------------------------------------------------
function create-database()
{
$script:createSqlServer = $false
$script:createSqlDatabase = $false
$sqlServersAvailable = @(enum-sqlServers -sqlServer $script:servername -resourceGroup $resourceGroupName)
if (!$generateUniqueName -and $sqlServersAvailable.Count -gt 0 -and !$script:servername)
{
log-info $sqlServersAvailable
$script:servername = read-host "enter server name to use for new database"
}
elseif (!$script:servername -and $generateUniqueName)
{
$script:servername = "sql-server-$(Get-Random)"
log-info "server name not provided. using random name $($script:servername)"
}
if (!$script:serverName)
{
log-info "error: need server name or use -generateUniqueName. exiting"
return $false
}
if ($sqlServersAvailable.Count -lt 1 -or $sqlServersAvailable.ServerName -inotmatch $script:servername)
{
$script:createSqlServer = $true
}
if (!$script:databasename -and $generateUniqueName)
{
$script:databasename = "sql-database-$(Get-Random)"
log-info "database name not provided. using random name $($script:databasename)"
}
if (!$script:createSqlServer)
{
# for odbc string in case server wasnt created
$adminUserName = (enum-sqlServers -resourceGroup $resourceGroupName -sqlServer $script:servername).SqlAdministratorLogin
# if database name specified / generated and it exists, exit
$sqlDatabasesAvailable = @(enum-sqlDatabases -sqlServer $script:servername -resourceGroup $resourceGroupName)
if ($script:databasename -and $sqlDatabasesAvailable.DatabaseName -imatch $script:databasename)
{
log-info "error: database $($script:databaseName) already exists on server $($script:servername). exiting"
return $false
}
}
if ($script:databasename)
{
$script:createSqlDatabase = $true
}
# everything should be populated, if not exit
if (!$script:createSqlServer -and !$script:createSqlDatabase)
{
log-info "error:invalid configuration. see help. exiting"
return $false
}
log-info "using server name $($script:servername)"
log-info "creating sql server : $($script:createSqlServer) creating sql db : $($script:createSqlDatabase)"
$error.Clear()
try
{
if ($script:createSqlServer)
{
log-info "create a logical server"
if (!(check-credentials))
{
return $false
}
$ret = New-AzSqlServer -ResourceGroupName $resourceGroupName `
-ServerName $script:servername `
-Location $location `
-SqlAdministratorCredentials $script:credential `
-ServerVersion $sqlServerVersion
if ($error)
{
log-info "error creating sql server. returning: $($error)"
$error.Clear()
return $false
}
log-info "create a logical server result:"
log-info $ret
log-info "configure a server firewall rule"
$ret = New-AzSqlServerFirewallRule -ResourceGroupName $resourcegroupname `
-ServerName $script:servername `
-FirewallRuleName "AllowSome" -StartIpAddress $nsgStartIpAllow -EndIpAddress $nsgEndIpAllow
if ($error)
{
log-info "error creating sql server. returning: $($error)"
$error.Clear()
return $false
}
log-info "configure a logical server firewall result:"
log-info $ret
}
if ($script:createSqlDatabase)
{
log-info "creating empty database $($script:databasename)"
$ret = New-AzSqlDatabase -ResourceGroupName $resourceGroupName `
-ServerName $script:servername `
-DatabaseName $script:databaseName `
-RequestedServiceObjectiveName $serviceTier
if ($error)
{
log-info "error creating sql database. returning: $($error)"
$error.Clear()
return $false
}
log-info "create database result:"
log-info $ret
}
return $true
}
catch
{
log-info "error:$($error)"
return $false
}
}
# ----------------------------------------------------------------------------------------------------------------
function enum-sqlDatabases($sqlServer, $resourceGroup)
{
if (!$sqlServer)
{
return $false
}
log-info "checking sql dbs on server $($sqlServer)"
$sqlDatabasesAvaliable = @()
if (!$script:databasename)
{
$sqlDatabasesAvaliable = @(Get-AzSqlDatabase -ServerName $sqlServer -ResourceGroupName $resourceGroup -ErrorAction SilentlyContinue)
}
else
{
$sqlDatabasesAvaliable = @(Get-AzSqlDatabase -ServerName $sqlServer -ResourceGroupName $resourceGroup -DatabaseName $script:databasename -ErrorAction SilentlyContinue)
}
return $sqlDatabasesAvaliable
}
# ----------------------------------------------------------------------------------------------------------------
function enum-sqlServers($resourceGroup, $sqlServer)
{
log-info "checking for sql servers in resource group $($resourceGroup)"
$serverInfo = @()
if (!$sqlServer)
{
$serverInfo = @(Get-AzSqlServer -ResourceGroupName $resourceGroup -ErrorAction SilentlyContinue)
}
else
{
$serverInfo = @(Get-AzSqlServer -ServerName $sqlServer -ResourceGroupName $resourceGroup -ErrorAction SilentlyContinue)
}
return $serverInfo
}
# ----------------------------------------------------------------------------------------------------------------
function list-availableSqlServers()
{
$sqlServersAvailable = new-object Collections.ArrayList
if ($resourceGroupName -eq "*")
{
$resourceGroups = @((Get-AzResourceGroup).ResourceGroupName)
}
else
{
$resourceGroups = @($resourceGroupName)
}
foreach ($resourceGroup in $resourceGroups)
{
$serverInfo = @(enum-sqlServers -resourceGroup $resourceGroup)
foreach ($server in $serverInfo.ServerName)
{
log-info "--------------------------------"
log-info "--------------------------------"
log-info " SQL SERVER: $($server)"
log-info "--------------------------------"
log-info "--------------------------------"
$dbInfo = @(enum-sqlDatabases -sqlServer $server -resourceGroup $resourceGroup)
foreach ($db in $dbInfo)
{
log-info "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv"
log-info $db
log-info "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
}
$dbCount += $dbInfo.Count
}
$sqlCount += $serverInfo.Count
}
log-info "sql servers available: $($sqlCount) sql databases available: $($dbCount)"
}
# ----------------------------------------------------------------------------------------------------------------
function log-info($data)
{
$data = $($data | format-list * | out-string)
if ($data -imatch "error|warning|exception|fail|terminate")
{
Write-Warning $data
}
else
{
write-host $data
}
if ($logFile)
{
out-file -Append -InputObject $data -FilePath $logFile
}
}
# ----------------------------------------------------------------------------------------------------------------
main
log-info "$([System.DateTime]::Now):finished"