my Azure ML api rest return an empty object - azure

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!

Related

connecting to azure rest api using powershell resulting in StatusCode : 203 StatusDescription : Non-Authoritative Information

I am able to connect fine to azure API's using a PAT token in postman, however am not able to authenticate using powershell.
After playing around with different authorization passing I am still stuck with getting the html page for the sign in returned. Here is a sample request I am making
Invoke-RestMethod https://feeds.dev.azure.com/xx/x/_apis/packaging/Feeds/x/Packages -Headers #{Authorization="Token :xxx"}
After much searching I came across https://www.opentechguides.com/how-to/article/azure/201/devops-rest-powershell.html. Here is a simplified snippet that allowed my request to go through successfully.
#enter your token in pat token
$pat = "xxx"
# Create header with PAT
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$header = #{authorization = "Basic $token"}
#enter your url in projects url
$projectsUrl = "https://feeds.dev.azure.com/xx/x/_apis/packaging/Feeds/x/Packages -Headers"
$projects = Invoke-RestMethod -Uri $projectsUrl -Method Get -ContentType "application/json" -Headers $header

PowerShell- Use Credentials instead of Basic Bas64 with Token to Invoke-RestMethod against AzureDevops

I have PowerShell scripts that I run to kick off a build in Azure DevOps as well as doing lots of things in Azure DevOps using the Rest API. I am currently using the token that is converted to Base64 using basic in the header to authenticate. If there a way of using -Credentials (Get-Credentials) with the token instead of a base64 header encoded token when using Invoke-RestMethod? Below is a sample for connecting with the Base64 token and Basic.
Sample script that lists Projects:
$token = "##############################################"
$UriOrg = "https://dev.azure.com/myADO/"
$AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($token)")) }
$uriProcess = $UriOrg + "_apis/process/processes?api-version=5.1"
Invoke-RestMethod -Uri $uriProcess -Method get -Headers $AzureDevOpsAuthenicationHeader
Although Get-Credential is designed to get a credential using a username and password, you can of course also use it to have someone enter the token..
Something like
$cred = Get-Credential -Message 'Please enter the AzureDevops Token in the Password field' -UserName 'AzureDevops'
if ($cred) {
$token = $cred.GetNetworkCredential().Password
$authHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($token)")) }
$UriOrg = 'https://dev.azure.com/myADO/'
$uriProcess = $UriOrg + "_apis/process/processes?api-version=5.1"
Invoke-RestMethod -Uri $uriProcess -Method Get -Headers $authHeader
}
Another option would be to create your own form where it is also possible to enter the Uri for the organization, because Get-Credential does not accept usernames like https://dev.azure.com/myADO/

Update defaultBranch of build definition via Azure DevOps API

I need to update the defaultBranch of build definition via Azure API.
The is the documentation for PUT request:
https://learn.microsoft.com/en-us/rest/api/azure/devops/build/definitions/update?view=azure-devops-rest-5.1
The problem is that I don't know the minimum list pf params I need to send in order to create a working request.
I tried to export the actual request from the browser and modify only this field - status code is 200 but nothing was changed. I don't want to pass all filed I just want to modify the defaultBranch.
In the link you provided you have Request Body section, you can see there what you need to pass. I like to get the definition first (with Get API), change what I want, and then perform the update.
In PowerShell:
$pat = "YOUR-PAT"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,"$pat")))
$headers = #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$url = "https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.1"
$build = Invoke-RestMethod -Uri $url -Method Get -ContentType application/json -Headers $headers
$newDefaultBranch = "test-branch"
$build.repository.defaultBranch = $newDefaultBranch
$json = $build | ConvertTo-Json -Depth 10
$response = Invoke-RestMethod -Uri $url -Method Put -ContentType application/json -Headers $headers -Body $json

How to authenticate for https://management.azure.com api?

I want to retrieve data on my DNS zones through a API call:
$api = "?api-version=2018-05-01"
$pat = "Bearer $env:System_AccessToken"
Write-Host "### PAT ###"
Write-Host $pat
$DNSInformation = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Network/dnsZones/$zoneName/$recordType/$relativeRecordSetName$api"
Write-Host "###"
Write-Host $DNSInformation
Write-Host "###"
$x = Invoke-RestMethod -Uri $DNSInformation -Headers #{Authorization = $pat } -Method Get
When I run this script I get:
The remote server returned an error: (401) Unauthorized.
When I navigate to the URL I get:
error: {
code: "AuthenticationFailed",
message: "Authentication failed. The Authorization header is missing."
}
I think the issue is that I can't use the $env:System_AccessToken token to get on the management api. But I can't find information what kind of authentication is needed.
As the error mentions, the authorization header is incorrect.
$URI = "https://management.azure.com/providers/microsoft.resources/checkresourcename?api-version=2014-01-01"
Invoke-RestMethod -Uri $URI -Method GET -Headers $authHeader
You can use a couple of approaches to create your header:
As you mentioned - Azure Powershell to check resource names
By creating Bearer token : Powershell Script to delete unused resources in Azure

How to fix "401 Unauthorized" error in PUT Invoke-RestMethod (trying to replace stored procedure)

I'm trying to manage CosmosDB resources using REST API and PowerShell.
My code works fine when I use GET and POST, but when I try to replace an existing object using PUT, I get 401 error.
My code registers stored procedure when it doesn't exist and should update it when the SP already exists.
So when I create a new SP, I use the following variables:
$Verb = "POST"
$ResourceType = "sprocs"
$ResourceLink = "dbs/$DBName/colls/$CollName"
$queryUri = "$CosmosDBEndPoint$ResourceLink/$ResourceType"
get auth header:
...
$authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb -resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
and then call REST method:
$header = #{authorization=$authHeader;"x-ms-version"="2017-02-22";"x-ms-date"=$dateTime}
$contentType= "application/json"
Invoke-RestMethod -Method $Verb -ContentType $contentType -Uri $queryUri -Headers $header -Body $body
It works great and creates what it should.
And, when I need to replace existing object (SP in my case), I change variables like this:
$Verb = "PUT"
$ResourceType = "sprocs"
$ResourceLink = "dbs/$DBName/colls/$CollName"
$ItemName = "SP_Name"
$queryUri = "$CosmosDBEndPoint$ResourceLink/$ResourceType/$ItemName"
generate auth header just like in case with POST (only verb is different):
...
$authHeader = Generate-MasterKeyAuthorizationSignature -verb $Verb -resourceLink $ResourceLink -resourceType $ResourceType -key $MasterKey -keyType "master" -tokenVersion "1.0" -dateTime $dateTime
...
and the invoke REST method with new URI (which includes now name of SP to be changed):
$header = #{authorization=$authHeader;"x-ms-version"="2017-02-22";"x-ms-date"=$dateTime}
$contentType= "application/json"
Invoke-RestMethod -Method $Verb -ContentType $contentType -Uri $queryUri -Headers $header -Body $body
Which is throws me 401 Unauthorized, so it seems that auth header isn't right. Can't figure out what I should change there.
From here it looks like the resource or the value in the resource you are trying to change does not support a PUT action. You can confirm manually;
https://learn.microsoft.com/en-us/rest/api/cosmos-db/
or by going to;
https://resources.azure.com/
So the key was to change variables this way:
$ResourceType = "sprocs"
$ItemName = "SP_Name"
$ResourceLink = "dbs/$DBName/colls/$CollName/$ResourceType/$ItemName"
and then generate auth header.
I.e. resource link variable must contain the full path to the replaced object.

Resources