簡體   English   中英

如何使用具有托管標識的自動化帳戶運行手冊運行 Azure SQL Server 存儲過程?

[英]How to run an Azure SQL Server Stored Procedure using an Automation Account Runbook with Managed Identity?

我正在嘗試使用自動化帳戶中的 PowerShell Runbook 來運行 SQL Server DB 索引和統計維護,以激活名為AzureSQLMaintenance的存儲過程。

由於我不想使用標准 SQL Server 身份驗證,因此我嘗試使用托管身份。

在線我發現一些 Microsoft 文檔在此處此處的 Microsoft 技術社區上非常接近要點,但是兩個線程都缺少一些部分。 這篇博客文章給了我一個很好的線索,但它缺少托管身份驗證

經過幾天的測試,我終於設法讓它工作,所以我會寫下整個過程,以防有人需要做同樣的事情:

  1. Account Settings > Identity System Assigned Managed Identity 必須設置為On ,我們需要Object (principal) Id ,所以記得標記它
  2. 在我的 Azure SQL 數據庫服務器中,在Settings > Azure Active Directory下,我們需要檢查Azure Active Directory admin的值。 就我而言,這是一個組
  3. Azure Active Directory中,編輯上一步中個性化的組,並將在步驟 1 中獲得的Object (principal) Id添加為組的成員
  4. 需要在自動化帳戶中創建Powershell Runbook
  5. powershell Runbook 代碼需要看起來像
Write-Output "Run started"

# Instantiate the connection to the SQL Database
$sqlConnection = new-object System.Data.SqlClient.SqlConnection

# Connect to the the account used the Managed Identity
Connect-AzAccount -Identity

# Get a Token
$token = (Get-AzAccessToken -ResourceUrl https://database.windows.net ).Token

# Initialize the connection String
$sqlConnection.ConnectionString = "Data Source=db-server-name.database.windows.net;Initial Catalog=<db-name>;Connect Timeout=60" 

# Set the Token to be used by the connection
$sqlConnection.AccessToken = $token

# Open the connection
$sqlConnection.Open()

Write-Output "Azure SQL database connection opened"

# Define the SQL command to run
$sqlCommand = new-object System.Data.SqlClient.SqlCommand

# Allow Long Executions
$sqlCommand.CommandTimeout = 0

# Associate the created connection
$sqlCommand.Connection = $sqlConnection

Write-Output "Issuing command to run stored procedure"

# Execute the SQL command
$sqlCommand.CommandText= 'exec [dbo].[AzureSQLMaintenance] @parameter1 = ''param1Value'', @parameter2 = ''param2Value'' '
$result = $sqlCommand.ExecuteNonQuery()

Write-Output "Stored procedure execution completed"

# Close the SQL connection
$sqlConnection.Close()

Write-Output "Run completed"

此時,在 Runbook 上運行測試:在我的情況下,它運行良好,即使需要一段時間(這就是參數$sqlCommand.CommandTimeout = 0的原因)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM