最近创建了一个正在运行的函数应用。该函数应用托管 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()
两个函数实现相同的逻辑:
- 从提供商处检索身份验证 token
- 使用 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 中 - 它缺少正斜杠。而不是:
应该是
因此,将您的 $sqlTokenURI 更改为此,它应该可以工作:
$sqlTokenURI =“https://database.windows.net/&api-version=2017-09-01”
关于powershell - 无法在启用 MSI 的函数应用中使用 PowerShell 连接到 Azure SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49785682/