In this article, we are going to do a REST call towards an Azure API using powershell script. For this, we should have a Service Principal to get an access token (via Oauth2 Client Credentials Grant) for our API.
Refer this to learn how to create & use Service Principal: Authenticating using a Service Principal
We will call Azure Rest API to get all the resources from Resource Group: Resources – List By Resource Group
Powershell script to call Azure Rest API
Fill the parameters & run the below command to retrieve Azure resources:
# ----------------- define variables -----------------
$client_id =\"<>\"
$tenant_id= \"<<Directory ID"
$client_secret=\"<>\"
$subscriptionId=\"<>\"
$ResourceGroupName=\"<>\"
$Resourceurl = \"https://management.core.windows.net/\"
# ----------------- Login as a Service Pricipal -----------------
$secret = ConvertTo-SecureString $client_secret -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential($client_id, $secret)
Add-AzureRmAccount -Credential $Cred -TenantId $tenant_id -ServicePrincipal
# ----------------- Generating token -----------------
$RequestAccessTokenUri = \"https://login.microsoftonline.com/$tenant_id/oauth2/token\"
$body = \"grant_type=client_credentials&client_id=$client_id&client_secret=$client_secret&resource=$Resourceurl\"
$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType \'application/x-www-form-urlencoded\'
# ----------------- Calling Rest API -----------------
$uri = \"https://management.azure.com/subscriptions/\" + $subscriptionId + \"/resourcegroups/\" + $ResourceGroupName + \"/resources?api-version=2019-10-01\"
$Headers = @{ }
$Headers.Add(\"Authorization\", \"$($Token.token_type) \" + \" \" + \"$($Token.access_token)\")
$allresources = Invoke-RestMethod -Method Get -Uri $uri -Headers $Headers
$allresources.value | ft name,location,type,id