powershell - 无法在启用 MSI 的函数应用中使用 PowerShell 连接到 Azure SQL

标签 powershell azure-sql-database azure-functions azure-synapse azure-managed-identity

最近创建了一个正在运行的函数应用。该函数应用托管 C# 和 PowerShell 函数,该函数在启用 MSI 的情况下按预期工作

PowerShell代码如下,完整代码在 Github

Write-Output "PowerShell Timer trigger function executed at:$(get-date)";

# Get MSI AUTH
$endpoint = $env:MSI_ENDPOINT
$secret = $env:MSI_SECRET
$sqlTokenURI = "https://database.windows.net&api-version=2017-09-01"
$header = @{'Secret' = $secret}
$authenticationResult = Invoke-RestMethod -Method Get -Headers $header -Uri ($endpoint +'?resource=' +$sqlTokenURI)

# CONNECT TO SQL
$SqlServer = $env:SQL_SERVER_NAME
$SqlServerPort = 1433
$Database = "azuredwmonitordb"
$Conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=tcp:$($SqlServer),1433; Initial Catalog=$($Database);")
$Conn.AccessToken = $authenticationResult.access_token

# Open the SQL connection 
$Conn.Open() 

$Cmd=new-object system.Data.SqlClient.SqlCommand("SELECT @@SERVERNAME", $Conn) 
$Cmd.CommandTimeout=120 

# Execute the SQL command 
$Ds=New-Object system.Data.DataSet 
$Da=New-Object system.Data.SqlClient.SqlDataAdapter($Cmd) 
[void]$Da.fill($Ds) 

# Output the count 
$Ds.Tables.Column1 

# Close the SQL connection 
$Conn.Close()

两个函数实现相同的逻辑:

  1. 从提供商处检索身份验证 token
  2. 使用 token 连接到 Azure SQL 服务器

但是,当使用 PowerShell 函数时,第一步有效,但在第二步中尝试建立连接时,出现以下错误:

Exception while executing function: Functions.dm_pdw_exec_sessions. Microsoft.Azure.WebJobs.Script: PowerShell script error. System.Management.Automation: Exception calling "Open" with "0" argument(s): "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.". .Net SqlClient Data Provider: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON

我过去曾见过这样的情况:Azure SQL 服务器没有正确启用 AAD 身份验证(用户不在 master 中),但这里的情况并非如此。

最佳答案

问题出在资源 URI 中 - 它缺少正斜杠。而不是:

https://database.windows.net

应该是

https://database.windows.net/

因此,将您的 $sqlTokenURI 更改为此,它应该可以工作:

$sqlTokenURI =“https://database.windows.net/&api-version=2017-09-01

关于powershell - 无法在启用 MSI 的函数应用中使用 PowerShell 连接到 Azure SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49785682/

相关文章:

c# - 如何执行Azure队列触发的大量持久函数?

Azure - 从 EA 门户获取订阅列表及其状态

internet-explorer - 进行自动化时调用 onkeyup 函数

sql-server - 如何在 SQL Server 存储过程中对用户定义的表类型执行 ForEach?

c# - Azure Function 的自定义触发器和绑定(bind)

Azure函数-无法加载文件或程序集

python - 使用 Powershell 通过 Web 请求从序列中检索数字

python - 将唯一指纹附加到文件

stored-procedures - 如何将存储过程部署到 SQL Azure 中的联合数据库

reporting-services - Azure 数据库是否支持 SSRS?