sql-server - 如何使用具有托管标识的自动化帐户 Runbook 运行 Azure SQL Server 存储过程?

标签 sql-server azure

我正在尝试运行 SQL Server 数据库索引和统计信息维护,并在自动化帐户中使用 PowerShell Runbook 激活名为 AzureSQLMaintenance 的存储过程。

由于我不想使用标准 SQL Server 身份验证,因此我尝试使用托管身份。

在网上,我发现一些 Microsoft 文档非常接近 Microsoft 技术社区 here 上的要点。和 here ,但是两个线程都缺少一些片段。 this blog post给了我一个非常好的线索。但缺少托管身份验证

最佳答案

经过几天的测试,我终于设法让它发挥作用,所以我会把整个过程写下来,以防有人需要做同样的事情:

  1. 帐户设置 > 身份下,系统分配的托管身份必须设置为开启,并且我们需要 Object (principal) Id ,所以记得记下来
  2. 在我的 Azure SQL 数据库服务器的设置 > Azure Active Directory 下,我们需要检查 Azure Active Directory admin 的值。就我而言,这是一个团体
  3. Azure Active Directory 中,编辑上一步中指定的组并添加 Object (principal) Id在步骤 1 中作为群组成员获得
  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 的原因)

关于sql-server - 如何使用具有托管标识的自动化帐户 Runbook 运行 Azure SQL Server 存储过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72230503/

相关文章:

sql - 将数据从 SQL Server Express 导出到 CSV(需要引用和转义)

sql - 使用 DATEADD 后如何转换值

c# - 如何从 SQL Server 获取下一个标识值

azure - 在 Azure 数据工厂复制事件中使用 'Additional columns' 时,如果该列已存在于源中,它是否会在接收器端复制该列?

c# - 尝试访问 Azure Graph API 时出现权限不足错误

azure - 如何列出 Azure 数据湖第 2 代中按 Azure 数据工厂中的上次修改日期筛选的所有路径?

.net - 是否有类似于 Sql Server 表的 FileSystemWatcher 之类的东西?

选择名为 YEAR 的列时出现 SQL 错误

Azure 开发运营 : Add Azure Container Registry in Build Pipeline from different account

database - Azure SQL 数据库下载 .bacpac