我正在尝试运行 SQL Server 数据库索引和统计信息维护,并在自动化帐户中使用 PowerShell Runbook 激活名为 AzureSQLMaintenance
的存储过程。
由于我不想使用标准 SQL Server 身份验证,因此我尝试使用托管身份。
在网上,我发现一些 Microsoft 文档非常接近 Microsoft 技术社区 here 上的要点。和 here ,但是两个线程都缺少一些片段。 this blog post给了我一个非常好的线索。但缺少托管身份验证
最佳答案
经过几天的测试,我终于设法让它发挥作用,所以我会把整个过程写下来,以防有人需要做同样的事情:
- 在帐户设置 > 身份下,系统分配的托管身份必须设置为开启,并且我们需要
Object (principal) Id
,所以记得记下来 - 在我的 Azure SQL 数据库服务器的设置 > Azure Active Directory 下,我们需要检查
Azure Active Directory admin
的值。就我而言,这是一个团体 - 在 Azure Active Directory 中,编辑上一步中指定的组并添加
Object (principal) Id
在步骤 1 中作为群组成员获得 - 需要在自动化帐户中创建 Powershell Runbook
- 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
的原因)
关于sql-server - 如何使用具有托管标识的自动化帐户 Runbook 运行 Azure SQL Server 存储过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72230503/