-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbootstrap-sql.ps1
65 lines (49 loc) · 1.42 KB
/
bootstrap-sql.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
#!/usr/bin/env pwsh
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$identityName,
[Parameter(Mandatory = $true)]
[string]
$identityClientId,
[Parameter(Mandatory = $true)]
[string]
$sqlSaConnectionString
)
$ErrorActionPreference = "Stop"
if (-Not (Get-Module -ListAvailable -Name SqlServer)) {
Install-Module -Name SqlServer -Force -Scope CurrentUser
}
function ConvertTo-Sid {
param (
[string]$objectId
)
[guid]$guid = [System.Guid]::Parse($objectId)
foreach ($byte in $guid.ToByteArray()) {
$byteGuid += [System.String]::Format("{0:X2}", $byte)
}
return "0x$byteGuid"
}
function Grant-AadObject {
param (
[string]$objectName,
[string]$objectId,
[string]$objectType
)
$sid = ConvertTo-Sid "$objectId"
$grantQuery = @"
IF EXISTS (SELECT name FROM sys.database_principals WHERE name = '$objectName')
BEGIN
DROP USER [$objectName];
END
CREATE USER [$objectName] WITH default_schema=[dbo], SID=$sid, TYPE=$objectType;
ALTER ROLE db_datareader ADD MEMBER [$objectName];
ALTER ROLE db_datawriter ADD MEMBER [$objectName];
ALTER ROLE db_ddladmin ADD MEMBER [$objectName];
GO
"@
Invoke-Sqlcmd -ConnectionString $sqlSaConnectionString -Query $grantQuery
}
# Object type for Azure AD Users is 'E' and for Azure AD Groups is 'X'
Grant-AadObject "$identityName" "$identityClientId" "E"