Connecting to the Azure REST API from an Azure Automation RunBook

I was looking for data that I couldn’t find in a PowerShell command, so I needed an access token to run a query against an Azure API.

I was stuck with the basic problem of how do I query the Azure REST endpoints from a RunBook. In my last post, I just learned that you can use the RunAs account for the AutomationAccount in an “Login-AzureRmAccount” session:

$connection = Get-AutomationConnection -Name AzureRunAsConnection
$loginresults=Login-AzureRmAccount -ServicePrincipal -Tenant $connection.TenantID `
-ApplicationId $connection.ApplicationID -CertificateThumbprint $connection.CertificateThumbprint

Taking that a step further, I can then get an access token from the logged in context, and use that with an REST API call:

$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[$cacheItem.Count -1].AccessToken
$resourceGroup="MyResourceGroup"

$headerParams = @{'Authorization'="Bearer $AccessToken"}
$url="https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Compute/virtualMachines?api-version=2018-06-01"
$results=Invoke-RestMethod -Uri $url -Headers $headerParams -Method Get
Write-Output $results.value

Hope that helps someone !

,

One Response to Connecting to the Azure REST API from an Azure Automation RunBook

  1. David June 15, 2020 at 6:53 am #

    This was exactly what I was looking for, thanks

Leave a Reply

Powered by WordPress. Designed by WooThemes