Using the Azure ARM REST API – Get Subscription Information


In the fist blog post over using the Azure ARM REST API I explained how to retrieve the Access Token needed for the further authentication against the Azure ARM REST API.

In this blog post I’m going to explain how you can use that Access Token and start communicating with Azure using simple web calls.

How to use the Access Token for Authentication?

It took some time to find the correct location about how to use the Azure REST APIs but a good starting point is the Azure Reference on MSDN.

For the authentication part I found information on a blog post from David Ebbo called “Calling the Azure ARM API using plain REST

The interesting part for us is how the Request Header should look like.

image

So this shows us that the when we have the Access Token we need to create a web Request Header with the following info:

Authorization Bearer “[AccessToken]”

 

Get information about a subscription

Ok now we know how to use the Access Token we can start with a simple get info about the Azure Subscription. And again you can find info on retrieving that info on the Azure Reference links.

For retrieving the Subscription information we need to use the following request URI.

 

image

Let’s do a web request call using PowerShell Invoke-RestMethod cmdlet first.

#requires -Version 3

# ---------------------------------------------------
# Script: C:\Scripts\GetAzureSubscriptionRESTAPI.ps1
# Version:
# Author: Stefan Stranger
# Date: 10/28/2016 15:16:25
# Description: Get Azure Subscription Info using plain REST API calls.
# Comments:
# Changes:  
# Disclaimer: 
# This example is provided "AS IS" with no warranty expressed or implied. Run at your own risk. 
# **Always test in your lab first**  Do this at your own risk!! 
# The author will not be held responsible for any damage you incur when making these changes!
# ---------------------------------------------------


#region variables SPN ClientId and Secret
$ClientID       = '[ClientID]' #ApplicationID
$ClientSecret   = '[ClientSecret]'  #key from Application
$tennantid      = '[TennantID]'
$SubscriptionId = '[Subscription]'
#endregion
 

#region Get Access Token
$TokenEndpoint = {https://login.windows.net/{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
#endregion

#region Get Azure Subscription
$SubscriptionURI = "https://management.azure.com/subscriptions/$SubscriptionID" +'?api-version=2016-09-01'

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

Invoke-RestMethod @params
#endregion

When running above PowerShell script we receive the following info about the Azure Subscription.

image

Because we are using plain REST API web calls we can use all kind of tools, like for instance Bash scripts.

As you know Microsoft Loves Linux and we can use Bash on Windows (if you are on the Windows 10 Insider builds) to create a Bash script and use Curl to retrieve the Azure Subscription information.

Remarks:

  • I installed jq, a lightweight and flexible command-line JSON processor to parse the JSON output from curl, using apt-get install jq on Bash on Windows.
  • If you are creating the getazuresubscription.sh Bash script on Bash on Windows you need to make sure you save the file as unix file type.
    In VIM you can do that with :set ff=unix

getazuresubscription.sh file:

#!/bin/bash

# bash script to retrieve Azure Subscription information using plain Azure ARM REST API web requests

#Azure Subscription variables
ClientID="[ClientID]" #ApplicationID
ClientSecret="[ClientSecret]"  #key from Application
TennantID="[TennantID]"
SubscriptionID="[SubscriptionID]"

accesstoken=$(curl -s --header "accept: application/json" --request POST "https://login.windows.net/$TennantID/oauth2/token" --data-urlencode "resource=https://management.core.windows.net/" --data-urlencode "client_id=$ClientID" --data-urlencode "grant_type=client_credentials" --data-urlencode "client_secret=$ClientSecret" | jq -r '.access_token')

#Use AccessToken in Azure ARM REST API call for Subscription Info
subscriptionURI="https://management.azure.com/subscriptions/$SubscriptionID?api-version=2016-09-01"

curl -s --header "authorization: Bearer $accesstoken" --request GET $subscriptionURI | jq .

When you run above script from Bash on Windows you get the following output returned:

basharmrestapi

How cool is that?

In the last example of this blog post we are going to use Javascript to do the same as the previous examples.

I use Visual Studio Code to develop most of my scripts lately, you can also use that for the PowerShell and Bash scripts creation if you want. It even runs on Linux and a Mac Smile

 

image

GetAzureSubscription.js file:

/*
    Author: Stefan Stranger
    Date: 10/24/2016
    Description: Use Javascript to retrieve Azure Subscription information.
    More info: https://blogs.technet.microsoft.com/stefan_stranger/2016/10/21/using-the-azure-arm-rest-apin-get-access-token/
*/
var request, options;
request = require('request');

//Helper Function
function AzureARMAccessToken(ClientID, ClientSecret, TennantID, callback) {
    options = {
        url: 'https://login.windows.net/' + TennantID + '/oauth2/token', //URL to hit
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'accept': 'application/json'
        },
        body: 'resource=' + encodeURIComponent('https://management.core.windows.net/') + '&client_id=' + ClientID + '&grant_type=client_credentials&client_secret=' + encodeURIComponent(ClientSecret),

    };
    //Start the request
    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            callback(body);
        }
        else
            console.log(error);


    });
}


//Function to Get Azure Subscription Information
function GetAzureSubscription(clientID, clientSecret, tennantID, subscriptionID) {
    AzureARMAccessToken(clientID, clientSecret, tennantID, function (data) {
        var jsonData = JSON.parse(data);
        var accessToken = 'bearer ' + jsonData.access_token
        //Get StorageAccount info
        options = {
            url: 'https://management.azure.com/subscriptions/' + subscriptionID + '?api-version=2016-09-01',
            method: 'GET',
            headers: {
                'Authorization': accessToken,
                'accept': 'application/json'
            },
        };
        //Start the request
        request(options, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                var jsonData = JSON.parse(body);
                console.log(jsonData);
            }
            else
                console.log(error);


        });

    })
}

//Main
myClientID = "[ClientID]";
myClientSecret = "[ClientSecret]";
myTennantID = "[TennnantID]";
mySubscriptionID = "[SubscriptionID]"


GetAzureSubscription(myClientID, myClientSecret, myTennantID, mySubscriptionID);

I hope the above examples showed why it is cool to use Azure (ARM) REST APIs to manage Azure. In the next blog post I’m going to explore the Azure (ARM) REST API a little more.

Have fun!

References:

Comments (0)

Skip to main content