Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Microsoft Azure Rest API using PowerShell

Using Microsoft Azure REST API is great way to automate Azure Resources and operations. Some times I have found PowerShell Az module is not present on remote servers and I need to automate azure things, Rest API is very handy at the time when features which are not available on PowerShell module AZ. I had already written a project using Rest API earlier - Powershell Azure Inventory GUI Utility. Here in this article I will be using Powershell to authenticate and consume Microsoft Azure Rest API.

First step is, to authenticate Azure Rest API, You will need to create and use Service Principle (App registrations) to connect to Azure. To create a new Service Principle, Either search for service App Registrations or Go to Azure Active Directory and select App Registrations.

In the Azure Active Directory >> App Registrations click on the New Registration to create new Service Principle.

Provide a the user-facing display name for this application, it can be changed later. Choose Accounts in this orgnizational directory only (Your AAD only - Single tenant) to use this application or access this API, and click Register.

Once App registration is created, check the Endpoint tab and note down GUID Application (client) ID. This id I will use later as user name.

Next go to Certificates & secrets to create password. Click on New client secret. A secret string that the application uses to prove its identity when requesting a token. Also can be referred to as application password.

 

Provide a description for the client secret and mention when secret key (password credential) will expires, in 1 year, in 2 years or Never and click Add.

Copy the Value of newly created secret, I will use it later.

App registrations - Service Principle is created successfully, Next step provide this service principle RBAC access to authenticate to Azure Rest API. Find and Select the subscriptions on which you want to assign permissions. 

In the subscriptions, Choose Access Control (IAM) and click on Add role assignment to Grant access to resources, Select the Role, I am selecting Contributor role. (By default Assign Access to is User, group, or service principal). Type the service principal name in the Select. click on it, it will show in the selected members and click Save button.

Open Powershell, below is the script to authenticate to Azure Rest API. feed information in subscriptionId, tenantId, applicationId and secret. which is already collected as shown from above and below example screenshots. All the parameters used in the script, its information is available on https://docs.microsoft.com/en-us/rest/api/azure/. It uses oauth2 for authentication. OAuth 2 is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service, such as Facebook, GitHub, Azure and many more. It works by delegating user authentication to the service that hosts the user account, and authorizing third-party applications to access the user account. OAuth 2 provides authorization flows for web and desktop applications, and mobile devices.

Once I authenticate to Azure Rest API, I get Bearer access token (It comes with expiry time), which I will keep utilizing it again and again (until expires) to perform the tasks on Azure in next script.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#Microsoft Azure Rest API authentication
#https://docs.microsoft.com/en-us/rest/api/azure/
$subscriptionId = '9e22xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$tenantId = '3b80xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
'
$applicationId = '2e47xxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$secret='.9Dyd2U3yM2YD8Wn58XG~bX.z-V.PwN.M0'

$param = @{
    #Uri = "https://login.microsoftonline.com/$tenantId/oauth2/token?api-version=1.0";
    Uri = "https://login.microsoftonline.com/$tenantId/oauth2/token?api-version=2020-06-01";
    Method = 'Post';
    Body = @{ 
        grant_type = 'client_credentials'; 
        resource = 'https://management.core.windows.net/'; 
        client_id = $applicationId; 
        client_secret = $secret
    }
}

$result = Invoke-RestMethod @param
$token = $result.access_token

Once I get bearer token I will keep using it throughout the script, whenver I want to get information, create any resource or delete resource on Azure. In this script I will completly focus on Resource group lifecycle. This script will fetch the list of Resource Groups from Azure with Rest API. The guide for listing Resource Group is https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/list. All the information available on Microsoft docs what API version, URI, URI parameters to use and how to use it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#Get the list of Resource Groups
#https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/list
$param_RGList = @{
    Uri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups?api-version=2020-06-01"
    ContentType = 'application/json'
    Method = 'GET'
    headers = @{
        authorization = "Bearer $token"
        host = 'management.azure.com'
    }
}

$rgList = Invoke-RestMethod @param_RGList
$rgList.value | Select-Object name, location, id

Next is the example of, creating a new Resource Group, Rest API information is available on https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/createorupdate. Mention the new Resource Group Name, method is PUT, In the body I have mentioned location and tags in json format for new resource group.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#Create or update subscriptionId and resource group name
#https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/createorupdate
$newResourceGroupName = 'TestResourceGroup'

$param_NewResourceGroup = @{
    Uri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/${newResourceGroupName}?api-version=2020-06-01"
    ContentType = "application/json"
    Method = 'PUT'
    headers=@{
    authorization="Bearer $token"
    host = 'management.azure.com'
    }
    body = '
        {
            "location": "eastus",
            "tags": {
                "owner": "http://vcloud-lab.com"
            }
        }
    '
}

Invoke-RestMethod @param_NewResourceGroup

Below is the example of the getting information for single Resource Group. https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/get.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#Get Resource Group Information
#https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/get
$param_RGInfo = @{
    Uri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/$($newResourceGroupName)?api-version=2020-06-01"
    ContentType = 'application/json'
    Method = 'GET'
    headers = @{
        authorization = "Bearer $token"
        host = 'management.azure.com'
    }
}

$rgInfo = Invoke-RestMethod @param_RGInfo
$rgInfo | Select-Object name, location, tags, id

In the Last example delete rest api method, where resource group is deleted. For this docs url is https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/delete. Just note, I only authenticated once in the start and throughout I used same bearer token (until expires) to do the operations throughout in Azure using other Azure Rest API urls.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#Delete Resource Group Information
#https://docs.microsoft.com/en-us/rest/api/resources/resourcegroups/delete
$param_DeleteResourceGroup = @{
    Uri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/${newResourceGroupName}?api-version=2020-06-01"
    ContentType = "application/json"
    Method = 'Delete'
    headers=@{
        authorization = "Bearer $token"
        host = 'management.azure.com'
    }
}
Invoke-RestMethod @param_DeleteResourceGroup

Download this script here and it is also available on github.com.

Useful Articles
MICROSOFT AZURE ERROR REGISTERING RESOURCE PROVIDERS CODE AUTHORIZATION FAILED
INSTALLING MICROSOFT AZURE POWERSHELL
Create your Microsoft Azure 12 Months Free Account
Powershell Azure Inventory GUI Utility 
PART 1 : MICROSOFT AZURE CREATION AND CONFIGURATION OF VPN TUNNEL SERIES
PART 2 : MICROSOFT AZURE CREATING RESOURCE GROUP 
PART 3 : MICROSOFT AZURE CREATING AND ADMINISTERING VIRTUAL NETWORK (VNET) 
PART 3.1 : MICROSOFT AZURE POWERSHELL CREATING AND ADMINISTERING VIRTUAL NETWORK (VNET)
PART 4 : MICROSOFT AZURE CREATING AND ADMINISTRATING LOCAL NETWORK GATEWAY VPN
PART 4.1 : MICROSOFT AZURE POWERSHELL CREATING AND ADMINISTRATING LOCAL NETWORK GATEWAY 



This post first appeared on Tales From Real IT System Administrators World And Non-production Environment, please read the originial post: here

Share the post

Microsoft Azure Rest API using PowerShell

×

Subscribe to Tales From Real It System Administrators World And Non-production Environment

Get updates delivered right to your inbox!

Thank you for your subscription

×