-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_identity_to_database.ps1
More file actions
31 lines (26 loc) · 1.21 KB
/
add_identity_to_database.ps1
File metadata and controls
31 lines (26 loc) · 1.21 KB
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
Import-Module -Name SQLServer -ErrorAction Stop
# Get automation variables
$UserAssignedIdentityId = Get-AutomationVariable -Name 'UserAssignedIdentityId'
$SqlServer = Get-AutomationVariable -Name 'SqlServer'
$Database = Get-AutomationVariable -Name 'Database'
$IdentityName = Get-AutomationVariable -Name 'IdentityName'
$IdentityId = Get-AutomationVariable -Name 'IdentityId'
# Convert GroupClientId to encoded sid
$SID = "0x" + [System.BitConverter]::ToString(([guid]$IdentityId).ToByteArray()).Replace("-", "")
# Idempotent SQL command
$Query = @"
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = '$IdentityName')
BEGIN
CREATE USER [$IdentityName] WITH DEFAULT_SCHEMA=[dbo], SID=$SID, TYPE=E;
EXEC sp_addrolemember 'db_datareader', [$IdentityName];
END
"@
$ErrorActionPreference = 'Stop'
Disable-AzContextAutosave -Scope Process
Connect-AzAccount -Identity -AccountId $UserAssignedIdentityId
$Token = ConvertFrom-SecureString (Get-AzAccessToken -AsSecureString -ResourceUrl https://database.windows.net).Token -AsPlainText
Invoke-Sqlcmd -ServerInstance $SqlServer `
-Database $Database `
-Query $Query `
-AccessToken $Token
Write-Output "✅ [$IdentityName] ensured in [$Database] with SID: $SID"