如何从 Azure Powershell Runbook 调用 API?出现错误

How to call API from an Azure Powershell Runbook? Getting Error

提问人:Michael Shepard 提问时间:11/1/2023 最后编辑:Michael Shepard 更新时间:11/6/2023 访问量:64

问:

我正在尝试使用 Powershell Runbook 在 Azure 自动化帐户中调用 API,当我尝试 GET 方法时收到 405 错误,当我尝试 POST 时收到 499 错误。

$uri = "https://xxxxxxxx-xxxxxxxx-prod-api.azurewebsites.net/api/PortfolioExport?PortfolioBatchDate=9/9/9999"
$tenantId = "xxxxxxxx-xxxx-xxxx-xxxx-7181039d1ed4"
$clientId = "xxxxxxxxxxxx-xxxx-xxxx-xxxx-5268b21e2920"
$clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxx~~U7n06yxQlc49"
$resource = "https://xxxxx.com/xxxxx.riskanalysis.app"

$tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$body = @{
     grant_type = "client_credentials"
     client_id = $clientId
     client_secret = $clientSecret
     resource = $resource
     audience = $resource # Specify the audience parameter here
 }
 $response = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -Body $body
 $accessToken = $response.access_token

 $headers = @{
     Authorization = "Bearer $accessToken"
 }

 Invoke-RestMethod -Method Get -Uri $uri -Headers $headers

这是我在尝试运行上述代码时收到的错误...

Invoke-RestMethod : The remote server returned an error: (405) Method Not Allowed.
At line:26 char:2
+  Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

尝试使用开机自检时,消息如下

Invoke-RestMethod : The remote server returned an error: (499).

在第 26 行 字符:2

  • Invoke-RestMethod -Method POST -uri $uri -Headers $headers
  •  + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
    eption
     + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
    
    
    

我们有一个逻辑应用,由于超时时间而无法运行,这就是我尝试使用自动化帐户路线的原因。这是逻辑应用 JSON,它运行正常但无法完成。我尝试使用此代码作为在 Runbook 中调用 API 的参考,因此可能我没有正确执行。

{
    "definition": {
        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
        "actions": {
            "HTTP": {
                "inputs": {
                    "authentication": {
                        "audience": "https://xxxxx.com/xxxxx.riskanalysis.app",
                        "clientId": "xxxxxxxxxxxx-xxxx-xxxx-xxxx-5268b21e2920",
                        "secret": "xxxxxxxxxxxxxxxxxxxxxxxx~~U7n06yxQlc49",
                        "tenant": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx-7181039d1ed4",
                        "type": "ActiveDirectoryOAuth"
                    },
                    "method": "POST",
                    "uri": "https://xxxxxxxx-xxxxxxxx-prod-api.azurewebsites.net/api/PortfolioExport?PortfolioBatchDate=9/9/9999"
                },
                "limit": {
                    "timeout": "PT15M"
                },
                "runAfter": {},
                "type": "Http"
            }
        },
        "contentVersion": "1.0.0.0",
        "outputs": {},
        "parameters": {},
        "triggers": {
            "Recurrence": {
                "evaluatedRecurrence": {
                    "frequency": "Month",
                    "interval": 1,
                    "startTime": "2022-06-01T06:00:00Z",
                    "timeZone": "Central Standard Time"
                },
                "recurrence": {
                    "frequency": "Month",
                    "interval": 1,
                    "startTime": "2022-06-01T06:00:00Z",
                    "timeZone": "Central Standard Time"
                },
                "type": "Recurrence"
            }
        }
    },
    "parameters": {}
}

调用 sql 存储过程的 Runbook 的第一部分:First part of the runbook that calls an sql stored procedure:

# Instantiate the connection to the SQL Database
$sqlConnection = new-object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Data Source=xxxxxxxxxxx.database.windows.net;Initial Catalog=xxxxxxx;Integrated Security=False;User ID=xxxxxxxxxxxxxxxx;Password=xxxxxxxxxxxx;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False"
$sqlConnection.Open()
Write-Output "Azure SQL database connection opened"
# Define the SQL command to run
$sqlCommand = new-object System.Data.SqlClient.SqlCommand
$sqlCommand.CommandTimeout = 0
$sqlCommand.Connection = $sqlConnection
Write-Output "Issuing command to run stored procedure"
# Execute the SQL command
$sqlCommand.CommandText= 'DECLARE @ReportDate datetime; SET @ReportDate = GETDATE(); EXEC Reporting.PortfolioBuild2 @ReportDate'
$result = $sqlCommand.ExecuteNonQuery()
Write-Output "Stored procedure execution completed"
# Close the SQL connection
$sqlConnection.Close()
Write-Output "Run completed"
Write-Output "Run started"
# Instantiate the connection to the SQL Database
$sqlConnection = new-object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Data Source=xxxxxxxxxxx.database.windows.net;Initial Catalog=xxxxxxx;Integrated Security=False;User ID=xxxxxxxxxxxxxxxx;Password=xxxxxxxxxxxx;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False"
$sqlConnection.Open()
Write-Output "Azure SQL database connection opened"
# Define the SQL command to run
$sqlCommand = new-object System.Data.SqlClient.SqlCommand
$sqlCommand.CommandTimeout = 0
$sqlCommand.Connection = $sqlConnection
Write-Output "Issuing command to run stored procedure"
# Execute the SQL command
$sqlCommand.CommandText= 'DECLARE @ReportDate datetime; SET @ReportDate = GETDATE(); EXEC Reporting.PortfolioBuild2 @ReportDate'
$result = $sqlCommand.ExecuteNonQuery()
Write-Output "Stored procedure execution completed"
# Close the SQL connection
$sqlConnection.Close()
Write-Output "Run completed"
Write-Output "Run started"
# Instantiate the connection to the SQL Database
$sqlConnection = new-object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Data Source=xxxxxxxxxxx.database.windows.net;Initial Catalog=xxxxxxx;Integrated Security=False;User ID=xxxxxxxxxxxxxxxx;Password=xxxxxxxxxxxx;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False"
$sqlConnection.Open()
Write-Output "Azure SQL database connection opened"
# Define the SQL command to run
$sqlCommand = new-object System.Data.SqlClient.SqlCommand
$sqlCommand.CommandTimeout = 0
$sqlCommand.Connection = $sqlConnection
Write-Output "Issuing command to run stored procedure"
# Execute the SQL command
$sqlCommand.CommandText= 'DECLARE @ReportDate datetime; SET @ReportDate = GETDATE(); EXEC Reporting.PortfolioBuild2 @ReportDate'
$result = $sqlCommand.ExecuteNonQuery()
Write-Output "Stored procedure execution completed"
# Close the SQL connection
$sqlConnection.Close()
Write-Output "Run completed"
Write-Output "Run started"
# Instantiate the connection to the SQL Database
$sqlConnection = new-object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Data Source=xxxxxxxxxxx.database.windows.net;Initial Catalog=xxxxxxx;Integrated Security=False;User ID=xxxxxxxxxxxxxxxx;Password=xxxxxxxxxxxx;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False"
$sqlConnection.Open()
Write-Output "Azure SQL database connection opened"
# Define the SQL command to run
$sqlCommand = new-object System.Data.SqlClient.SqlCommand
$sqlCommand.CommandTimeout = 0
$sqlCommand.Connection = $sqlConnection
Write-Output "Issuing command to run stored procedure"
# Execute the SQL command
$sqlCommand.CommandText= 'DECLARE @ReportDate datetime; SET @ReportDate = GETDATE(); EXEC Reporting.PortfolioBuild2 @ReportDate'
$result = $sqlCommand.ExecuteNonQuery()
Write-Output "Stored procedure execution completed"
# Close the SQL connection
$sqlConnection.Close()
Write-Output "Run completed"

逻辑应用代码:Logic app code:

 "definition": {
     "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
     "actions": {
         "HTTP": {
             "inputs": {
                 "authentication": {
                     "audience": "https://xxxxxxxxxxxxxx/xxxxxxxxxxxx.riskanalysis.app",
                     "clientId": "xxxxxxxxxxxxxxa-a2a5-5268b21e2920",
                     "secret": "xxxxxxxxxxxxxxweIkcS3qkq7~~U7n06yxQlc49",
                     "tenant": "xxxxxxxxxxxxxxx-a6a9-7181039d1ed4",
                     "type": "ActiveDirectoryOAuth"
                 },
                 "method": "POST",
                 "uri": "https://xxxxxxxxxxxxxxxxxxxxx-api.azurewebsites.net/api/PortfolioExport?PortfolioBatchDate=9/9/9999"
             },
             "limit": {
                 "timeout": "PT15M"
             },
             "runAfter": {},
             "type": "Http"
         }
     },
     "contentVersion": "1.0.0.0",
     "outputs": {},
     "parameters": {},
     "triggers": {
         "Recurrence": {
             "evaluatedRecurrence": {
                 "frequency": "Month",
                 "interval": 1,
                 "startTime": "2022-06-01T06:00:00Z",
                 "timeZone": "Central Standard Time"
             },
             "recurrence": {
                 "frequency": "Month",
                 "interval": 1,
                 "startTime": "2022-06-01T06:00:00Z",
                 "timeZone": "Central Standard Time"
             },
             "type": "Recurrence"
         }
     }
 },
 "parameters": {}
}
azure-web-app-service azure-logic-apps azure-runbook

评论

0赞 Daredevil 11/1/2023
“远程服务器返回错误:(405) 不允许方法”,表示服务器不允许您正在使用的 HTTP 方法(在本例中为 GET)。
0赞 Michael Shepard 11/2/2023
当我使用 Post 时......我收到以下错误:Invoke-RestMethod:远程服务器返回错误:(499)。在第 26 行 char:2 + Invoke-RestMethod -Method POST -Uri $uri -Headers $headers + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc eption + FullyQualifiedErrorId:WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
0赞 Michael Shepard 11/2/2023
我猜这是某种超时。如果是这种情况,有没有办法防止超时发生?
0赞 Ikhtesam Afrin 11/3/2023
@MichaelShepard使用函数在逻辑应用中的 URL 调用函数?
0赞 Michael Shepard 11/5/2023
@IkhtesamAfrin 我正在尝试将 2 个逻辑应用转换为 Runbook,因为 Microsoft 对逻辑应用施加了时间限制。第一部分调用一个 Azure SQL 存储过程,我已经成功完成了该存储过程。第二部分应调用已创建的 API,用于转换为 xlsx 文件。第二部分是我在添加运行手册时遇到的问题。我应该将 Runbook 拆分为 2 个,还是应该只调用第 2 部分已经存在的逻辑应用?

答: 暂无答案