0
votes

I am trying to use Azure Application Insights REST API call to get some summary information using Powershell. ( https://docs.microsoft.com/en-us/rest/api/monitor/alertsmanagement/alerts/getsummary )

So I went ahead and created App Registration in Azure AD (Called it AppInsightsRESTTest), assigned it Permission (App Insights-->Data-->Read) using the delegation option. I generated the Secret Key as well for it. And now I copied the Application ID and the Secret for this App and used it in the powershell below. I also added this App that I registered in Azure AD to my App Insights Instance as a CONTRIBUTOR role.

#SPN ClientId and Secret
$ClientID       =   "25325f5d-XXXXXXXXXXXXX26fef568d" #Key from Azure AD App ID Created
$ClientSecret   = "uX[CNk[XXXXXXXXXXXXgGcN4" #Secret key from Azure AD
$tennantid      = "fa061982-XXXXXXXXXXX1ce727"  #Directory ID for THREE PROJECt
$SubscriptionID = "d2e4beXXXXXXXXXXXXXXX686542c"

$TokenEndpoint = {https://login.microsoftonline.com/{0}/oauth2/token} -f $tennantid 
$ARMResource = "https://management.core.windows.net/";

$Body = @{
        'resource'= $ARMResource
        'client_id' = $ClientID
        'grant_type' = 'client_credentials'
        'client_secret' = $ClientSecret
}

$params = @{
    ContentType = 'application/x-www-form-urlencoded'
    Headers = @{'accept'='application/json'}
    Body = $Body
    Method = 'Post'
    URI = $TokenEndpoint
}

$token = Invoke-RestMethod @params

$token | select access_token, @{L='Expires';E={[timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($_.expires_on))}} | fl *


$SubscriptionURI = "https://management.azure.com/subscriptions/$SubscriptionID" +'/providers/Microsoft.AlertsManagement/alertsSummary?groupby=alertRule&api-version=2018-05-05'

$params = @{
    ContentType = 'application/x-www-form-urlencoded'
    Headers = @{
    'authorization'="Bearer $($Token.access_token)"
    }
    Method = 'Get'
    URI = $SubscriptionURI
}

Invoke-RestMethod @params

The above code returns me the Token, but the Invoke method returns empty value and no Json. If I try the same from browser using the AUTHO BEARER TOKEN it returns me the correct Json with appropriate data. Can someone help me with what could I have missed here that my powershell is not returning me anything?

Any help on this?

1

1 Answers

-1
votes

I got this one resolved turns out that I had to do 2 things:- Once I register the App on Azure AD, I should go to SUBSCRIPTION page and Grant the App I registered above with a READER permission for LOG ANALYTICS. Once that was done above powershell started working and returning the results. So bascailly you have to do : 1. Assign the app READER permission (thru IAM on Subscription page) for the
Log Analytics Reader.

No need to Assign the Application Insights READER access.