1

I'm trying to get Azure Billing data of my subscription data by using Powershell.

mainly checked the Doc from MSDN https://learn.microsoft.com/ja-jp/rest/api/consumption/usagedetails/list

and a sample as below. https://www.cloudnative.at/2017/12/22/generate-an-azure-consumption-report-with-the-consumption-rest-api-and-powershell/

$loginUri = "https://login.microsoft.com"
$body =@{
    client_id = XXXX
    client_secrect = XXXXXXXX
    resource    =  "https://management.core.windows.net"
    grant_type = "client_credentials"
}

$oauth = Invoke-RestMethod -Method Post -Uri $loginUrl/$TenantID/oauth2/token?api-version=1.0 -Body $body 

# SubscriptionID and Billing Period
$SubscriptionId = '<Your subscription GUID here>'
$billingperiod = '202006-1'

#Create the REST-URL
$usageURL =     "https://management.azure.com/subscriptions/$subscriptionid/providers/Microsoft.Billing/billingPeriods/$billingperiod/providers/Microsoft.Consumption/usageDetails?api-version=2017-11-30"

After I got the authentication token successfully, got error when running request uri like

“AuthenticationFailed”, the client 'XXXXXX' with object id 'XXXX' does not have authorization to perform action 'Microsoft.Consumption/usageDetial/read' over scope '/subscriptions/XXXX' or the scope is invalid. If access was recently granted, please refresh your credential.

Might because I didn't use APPID and genarated APPkey to get credentials, instead using client_secret of application as I get token in Graph API?

Eric Chen
  • 53
  • 1
  • 8

2 Answers2

3

If you want to access Azure billing api with Azure AD application, we need to assign Azure RABC role(Billing Reader, Reader, Owner, or Contributor role) to the AD application.For more details, please refer to the document enter image description here

For example(I assign Contributor role)

Step 1: login to your azure portal
Step 2: find Subscriptions in left side menu bar and click.
enter image description here

step 3: Click on Access Control IAM and then click on Add.enter image description here

Step 4: In Add Permission window, select contributor for role. In select input box, type the app name you created in Azure AD (Created in Azure Active Directory)and select it. In my case I created Azure Resource Management.enter image description here

Step 5:After you have given successful permission, click on Refresh in your subscription window and you will see your app showing in the list. See below example. enter image description here

step6: Powershell script

$tenantId="76a1f773...b-86b9-d1ced3e15cda"
$clientId="0159ec7d-f...-a680-c4d40ab7a36c"
$clientSecret="o4eq4jj...I26uz26W~"
$secSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force

$pscredential = New-Object System.Management.Automation.PSCredential ($clientId, $secSecret)
Connect-AzAccount -ServicePrincipal -Credential $pscredential -Tenant $tenantId

$dexResourceUrl="https://management.azure.com/"
$context = Get-AzContext
$token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, $dexResourceUrl).AccessToken


$SubscriptionId = '3465e081-85b6-4b54-a3e1-15675acb615f'
$billingperiod = '202010-1'

#Create the REST-URL
$usageURL ="https://management.azure.com/subscriptions/$subscriptionid/providers/Microsoft.Billing/billingPeriods/$billingperiod/providers/Microsoft.Consumption/usageDetails?api-version=2017-11-30"

$header = @{
    'Authorization' = "Bearer $($token)"
    "Content-Type" = "application/json"
}
 
$UsageData = Invoke-RestMethod `
    -Method Get `
    -Uri $usageURL `
    -ContentType application/json `
    -Headers $header 

ConvertTo-Json $UsageData
rAJ
  • 1,295
  • 5
  • 31
  • 66
Jim Xu
  • 21,610
  • 2
  • 19
  • 39
  • If it is useful for you, could you please accept it as an answer? It may help more people who have the similar issue – Jim Xu Aug 11 '20 at 07:20
  • Thank you Jim! it’s working after the permission added. I will need to get and combine with RateCard API for whole a billing report, if you have example for that as well, could you kindly introduce me? – Eric Chen Aug 11 '20 at 08:16
0

Having followed the instructions here I get the following error when making the actual API request:

Invoke-RestMethod : {"error":{"code":"500","message":"An error occurred during processing this request. Use this request id
    '17f6fdea-xxxx-xxxx-xxxx-a8c314d770ee' for follow-up."}}
    At C:\$Downloads\billingapitest.ps1:45 char:14
    + $UsageData = Invoke-RestMethod `
    +              ~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
        + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Any ideas how to resolve?

Thanks

Darren

============================================

I filed a ticket with MS support. Just prior to the session that had been scheduled to demonstrate the issue, I tested the Powershell script one more time and found that it was now working!