繁体   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