Kudu zipdeploy with POWERSHELL throwing The remote server returned an error: (500) Internal Server Error - azure

We are trying to deploy web app using POWER SHELL with KUDU ZIPDEPLOY, and it's failing with (500) Internal Server Error.
Interestingly it is working fine with CURL command.
The main difference is, in CURL I don't have use PROXY, but POWER SHELL it is asking for PROXY details. I guess this might be I am deploying from organization network.
$username = "`*********"
$password = "********"
$pair = "$($username):$($password)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = #{
Authorization = $basicAuthValue
}
$deployUri = "https://testexploreazurewebsites.scm.azurewebsites.net/api/zipdeploy?isAsync=true"
$proxyUri = [Uri]$null
$proxy = [System.Net.WebRequest]::GetSystemWebProxy()
if ($proxy)
{
$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
$proxyUri = $proxy.GetProxy($deployUri)
}
$sourceFilePath = "FilePath.zip"
$responseHeaders = Invoke-WebRequest -Uri $deployUri -ContentType "multipart/form-data" -Method Post -Proxy $proxyUri -ProxyUseDefaultCredentials -Headers $Headers `
-InFile $sourceFilePath `
-TimeoutSec 600000
It was working good till few days back, suddenly stopped working.
Any help please?
Updates and answer
From Kudu log files, the error description is : Missing content-type boundary.
Followed SF post powershell invoke-restmethod multipart/form-data to solve it.

Related

Azure AutomationAccount DSC scripts debug

I am running a DSC script from an Azure automation account to configure Windows VMs. It downloads files from a storage account in Azure to hosts for more configurations. If I hardcode the storage SAS token, it works fine. But I would like to get the SAS token in the DSC script. I use managed identity of the Automation account and assigned proper IAM access in storage account. I am able to get the SAS token in a test runbook script, but not in DSC script.
I got the main part of the code from
https://learn.microsoft.com/en-us/azure/automation/enable-managed-identity-for-automation
The error I am getting indicates that the SAS token is not generated correctly, but I can't find a way to see what the error msgs are from this part of the code in DSC when it executed.
any help/suggestion is appreciated!
Configuration DSCtest {
Import-DscResource -ModuleName 'PSDesiredStateConfiguration'
$resource= "?resource=https://management.azure.com/"
$url = $env:IDENTITY_ENDPOINT + $resource
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("X-IDENTITY-HEADER", $env:IDENTITY_HEADER)
$Headers.Add("Metadata", "True")
$accessToken = Invoke-RestMethod -Uri $url -Method 'GET' -Headers $Headers
$Atoken = $accessToken.access_token
Write-Output $Atoken
$toDate = (Get-Date).AddDays(4).toString("yyyy-MM-ddT00:00:00Z")
$params = #{canonicalizedResource="/file/storageacnt/exec";signedResource="c";signedPermission="rcw";signedProtocol="https";signedExpiry=$toDate}
$jsonParams = $params | ConvertTo-Json
$sasResponse = Invoke-WebRequest -Uri https://management.azure.com/subscriptions/xxxxxxxxxxxx/resourceGroups/rg-xxxxx/providers/Microsoft.Storage/storageAccounts/storageaccnt/listServiceSas/?api-version=2017-06-01 -Method POST -Body $jsonParams -Headers #{Authorization="Bearer $Atoken"} -UseBasicParsing
$sasContent = $sasResponse.Content | ConvertFrom-Json
$sasCred = $sasContent.serviceSasToken
write-host $sasCred
$sasToken = "?$sasCred"
Node LocalHost {
....

ExpiredAuthenticationToken in FunctionApp

I have a powershell script that connects to the ADO API and shows me a pool of agents. When I run it locally it works for me, but unfortunately there is already a bug in Function App
401 Unauthorized
{
"error": {
"code": "ExpiredAuthenticationToken",
"message": "The access token expiry UTC time '12/22/2022 2:49:41 PM' is earlier than current UTC time '12/22/2022 2:53:08 PM'."
}
}
This is a new generated PAT and it is active.
Script:
$personalToken = "t0k3n"
$patToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($personalToken)"))
$repoHeader = #{"Authorization"="Basic $patToken"}
Write-Output $repoHeader
$repoUrl = [string]::Format("https://dev.azure.com/org/_apis/distributedtask/pools?api-version=5.1")
Write-Output $repoUrl
$output = Invoke-RestMethod -Uri $repoUrl -Method Get -ContentType "application/json; charset=utf-8; api-version=6.0" -Headers $repoHeader -MaximumRedirection 10
Write-Output $output
foreach ($outputValue in $output.value)
{
Write-Output $outputValue.name
}
I have no idea why this works locally and not in Function App
This may seem strange.. But it was enough to refresh the page, because Cloud Shell has a certain time of operation, after which it throws you out of the session..

my Azure ML api rest return an empty object

My issue
I try using REST API for machine learning. The following PowerShell doesn't fail, but return an empty objet, whatever the API I am testing.
my SPN has contributor permission, I made grant consent and I checked I get a token.
the doc I was using:
https://learn.microsoft.com/fr-fr/rest/api/azureml/quotas/list
I tested several other GET API as well.
I don't know what to do more. Any idea?
My Powershell code
$tenant_id = "XXXXXXXXXXXXXXXXXXX"
$ApplicationId = "XXXXXXXXXXXXXXX"
$spn_client_secret = "XXXXXXXXXXXXX"
$subscriptionid="XXXXXXXXXXXX"
$uri = "https://login.microsoftonline.com/$tenant_id/oauth2/token"
$BodyText = "grant_type=client_credentials&client_id=$ApplicationId&resource=https://management.azure.com&client_secret=$spn_client_secret"
# GET TOKEN
$Response = Invoke-RestMethod -Method POST -Body $BodyText -Uri $URI -ContentType application/x-www-form-urlencoded
$aad_access_token = $Response.access_token
# tested, I effectively have a token
# READ ml
$urllist = "https://management.azure.com/subscriptions/$subscriptionid/providers/Microsoft.MachineLearningServices/locations/westeurope/quotas?api-version=2021-03-01-preview"
$headers = #{"Authorization" = "Bearer " + $aad_access_token}
Invoke-RestMethod -Method GET -HEADERS $headers -Uri $urllist -ContentType application/x-www-form-urlencoded
I found what happend and I am a little bit confused.
The resource was empty, because I completely forgot to create a compute!

Erorr exporting Azure sql database to blob storage with powershell

I'm trying to use Azure management API to export a SQL database to a bacpac file in a blob storage. The process seems fairly simple: obtain a token, and then:
$sqlAzureBackupHeaders = #{
Authorization = "Bearer $accessToken"
}
$sqlAzureBackupParams = #{
storageKey = "<key-goes-here>",
storageUri = "http://mystorageacct.blob.core.windows.net/my-blob-container/export-name.bacpac",
storageKeyType = "StorageAccessKey",
administratorLogin = "<sql-user>",
administratorLoginPassword = "<sql-password>",
authenticationType = "SQL"
}
$sqlAzureApiUri = "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Sql/servers/<server-name>/databases/<database-name>/export?api-version=2014-04-01"
Invoke-RestMethod -Uri $sqlAzureApiUri -Method Post -Headers $sqlAzureBackupHeaders -Body $sqlAzureBackupParams
This results in an error:
Invoke-RestMethod : Receivera:InternalServiceFaultThe server was unable to process the request due to an internal error. For more
information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the
<serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing
as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.
At D:\Users\protec-admin\Desktop\run-backups.ps1:140 char:1
+ Invoke-RestMethod -uri $sqlAzureApiUri -Method Post -Headers $sqlAzur ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I tried using Invoke-WebRequest and converting body to json string - with the same result.
When I try the same call using Postman, it works fine, so there's something with making the call from powershell that's not working correctly.
How can I get this working from powershell?
According to my test, the rest API just accept the json body. Please use ConvertTo-Json to convert the body to json.
For example
$headers=#{"Authorization" = "Bearer "+$token}
$body=#{
"storageKeyType"= "StorageAccessKey";
"storageKey"= "<your storage account access key>";
"storageUri"= "https://blobstorage0516.blob.core.windows.net/sample/testbacpac2.bacpac";
"administratorLogin"= "<SQL admin>";
"administratorLoginPassword"= "<SQL admin passsword>";
"authenticationType"= "SQL"
}|ConvertTo-Json
$sqlAzureApiUri = "https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.Sql/servers/<server-name>/databases/<database-name>/export?api-version=2014-04-01"
Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $body -UseBasicParsing -ContentType "application/json"

Unable to access admin URL of Azure Functions

I am using powershell and trying to access Azure functions Administration using api.
I am trying to get list of all functions created under $appName
Certainly i am changing $appName with actual Azure Function name before call
I also got valid $authToken before this call.
Below URL:
$Functions = Invoke-RestMethod -Method GET -Headers #{Authorization = ("Bearer {0}" -f $authToken)} -Uri "https://$appName.azurewebsites.net/admin/functions"
and the error in my powershell execution is :
Invoke-RestMethod :
The underlying connection was closed: An unexpected error occurred on a send.
At KeyFA.ps1:36 char:18
+ ... Functions = Invoke-RestMethod -Method GET -Headers #{Authorization = ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I tried make it POST instead of GET but same error.
I tried access this url in broswer and the error in my broswer is :
http 401 means unauthorized.
Then i also tried access this URL from postman with Bearer auth correctly set but get below errors:
Could not get any response
There was an error connecting to
https://appname_comes_here.azurewebsites.net/admin/functions/
What am i not doing correctly?
Not able to fix this error. Is the url discontinued by Azure function site now?
Due to you just post the partial PowerShell code and the error information seems to be a network issue, I don't know what real issue you got is and how to fix it.
So I just post my work PowerShell script at here, you can refer to my code to fix your issue.
$appName = "<your app name>"
$userName='<your app credential user name>'
$userPWD='<your app credential user password>'
$apiBaseUrl = "https://$($appName).scm.azurewebsites.net/api"
$appBaseUrl = "https://$($appName).azurewebsites.net"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $userName,$userPWD)))
$jwt = Invoke-RestMethod -Uri "$apiBaseUrl/functions/admin/token" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method GET
$Functions = Invoke-RestMethod -Method GET -Headers #{Authorization = ("Bearer {0}" -f $jwt)} -Uri "$appBaseUrl/admin/functions"
Note: you can follow the figures below to get the $userName and $userPWD values.
Fig 1. On Azure portal, open the Platform features tab of your Function App and click the Deployment Center link
Fig 2. Select the FTP option in the first step of SOURCE CONTROL and click the Dashboard button to copy the values of Username and Password, but just use the part of Username with $ prefix as $userName in my script

Resources