Making Azure Management API Calls with Azure Automation Runbooks

Created in Code
1 min readFeb 10, 2019

--

For most of your time using Azure Automation Runbooks you can use the standard AzureRm Powershell modules. Occasionally though you’ll find something that needs you to dig a little deeper and directly access the REST apis.

That’s simple enough, you just need to pass an access key and luckily you can use your RunAs account for this. The code you need is below:

$connection = Get-AutomationConnection -Name AzureRunAsConnection$loginresults=Login-AzureRmAccount -ServicePrincipal -Tenant $connection.TenantID `-ApplicationId $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint$context = Get-AzureRmContext$SubscriptionId = $context.Subscription$cache = $context.TokenCache$cacheItem = $cache.ReadItems()$AccessToken=($cacheItem | Where-Object { $_.Resource -eq “https://management.core.windows.net/" })[0].AccessTokenWrite-Output -InputObject @{AccessToken = $AccessToken; SubscriptionId = $SubscriptionId }

I find it easiest to save this in it’s own runbook named “Get-AzureManagementAccessToken” and then call it whenever I need to access an api call like this:

$accessDetails = .\Get-AzureManagementAccessToken.ps1$AccessToken = $accessDetails.AccessToken$SubscriptionId = $accessDetails.SubscriptionId$headerParams = @{‘Authorization’=”Bearer $AccessToken”}$url = “https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/..."$results = Invoke-RestMethod -Uri $url -Headers $headerParams -Method Get -ContentType ‘application/json’

The same principle can be used for the graph api, just change https://management.core.windows.net/ to https://graph.microsoft.com/ when retrieving the access token from the cache.

--

--

Created in Code

C#/ASP.NET — Chatbots, AI, Machine Learning and the Web