I am trying to import json file saved in local directory (desktop) to Azure DevOps Library Variable Group using Azure DevOps Rest api.
This is the script.
$jsonbody = Get-Content -Path "C:variable1.json" | Out-String
# Define organization name and PAT
$organization = ""
$token = "{PAT}"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$url="https://dev.azure.com/$organization/_apis/distributedtask/variablegroups?api-version=7.1-preview.2"
$head = @{ Authorization =" Basic $token" }
Invoke-RestMethod -Uri $url -Method Post -Headers $head -Body $jsonbody -ContentType application/json
This is the error message that I receive.
Invoke-RestMethod : The remote server returned an error: (401)
Unauthorized. At line:6 char:1 + Invoke-RestMethod -Uri $url -Method
Post -Headers $head -Body $jsonbo … ++ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I tried different rest api but received the same error message.
$jsonbody = Get-Content -Path "C:variable1.json" | Out-String
# Define organization name and PAT
$organization = ""
$token = "{PAT}"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$url="https://dev.azure.com/$organization/_apis/projects?api-version=7.1-preview.4"
$head = @{ Authorization =" Basic $token" }
Invoke-RestMethod -Uri $url -Method GET -Headers $head -ContentType application/json
PAT token has full access.
These are the documents that I followed.
I can use the same PAT token to publish packages to Azure DevOps artefact feed (Nuget and NPM).
Any help would be appreciated on why the PAT token is not working when using rest api.
2
Answers
Initially, I generated PAT token with Full Access in my DevOps Portal like this:
Now, I ran below PowerShell script to list projects by calling Azure DevOps Rest API through PAT token:
Response:
Similarly, you can use below script to import Json file saved in local directory to Azure DevOps Library Variable Group using Azure DevOps Rest Api:
Response:
To confirm that, I checked the same in Azure DevOps portal where variable group imported successfully like this:
If still the error persists, try creating new PAT token with Full Access and use above mentioned scripts to call DevOps REST API.
Reference:
How to call Azure Devops REST API from PowerShell (opentechguides.com)
Could you double-check if your PAT has full access?
You can use PAT-Get-REST API to get the value of
scope
.Also you can follow the document 1 you mentioned above to check the Scopes in Azure Devops page.
Besides you can create a new PAT with custom defined scopes and then try to use the new PAT to invoke REST APIS.
Authorize the scope of access associated with this token.
example:
Hope it can help you.