Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

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.

Note: If you don't want to use your own credentials you can use article Microsoft Azure Rest API using PowerShell Part 2.

Microsoft Azure Portal App registration event grid partner registrations appdynamics function app application gateways azure active directory rest api azure powershell.png

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

Microsoft Azure Portal Rest API powershell automation Azure Active Directory App registrations Users Groups external Identities Roles and administrators Azure Ad Connect.png

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.

Microsoft Azure Portal Powershell Rest API Register an application accounts in this organizational directory only single tenant app registrations azure ad directory multitenant redirect URI AAD blade.png

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.

Microsoft Azure Portal App registrations rest api powershell Authentication certificates & secrets endpoints app registrations azure ad active directory resources Roles and administrators api permissions.png

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.

 Microsoft azure portal powershell rest api app registrations certificates & secrets new client secrets certificates token configuration api permissions expose an api owners manifest roles and administrations.png

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.

Microsoft Azure portal Powershell Rest api azure certificates & secrets add a client secrets expires in 1 year never token configuration branding authentication api permissions expose an api certificates.png

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

Microsoft Powershell portal azure rest api automation postman powershell certificates & secrets certificates client secrets no certificates https scheme app roles owners  roles and administrators app registrations.png

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. 

Microsoft Azure Rest API Powershell Subscriptions event grid subscriptions service bus resource groups subscription id my role owner .png

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.

Microsoft Azure Rest API Powershell RBAC role-based access control permissions resources subscription id add role assignment contributer access control (IAM) assign access to contributer owner deny assignment members.png

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.

Microsoft Azure Powershell Rest API authentication subscriptionID TenentID applicationid secret post method invoke-restmethod access_token oauth2 api-version client_credentials client_id client_secret bearer.png

 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.

Microsoft Azure Powershell rest API postman Resource Group list subscription id api-version method get contenttype appliaction json invoke-restmethod location select-object management.azure.com uri parameters responses.png

 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.

Microsoft Azure Powershell rest api resource group create update subscription id location tags headers body method put contenttype application json uri invoke-restmethod provisioningstate management.azure.com.png

 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.

Microsoft Azure Rest API Powershell Resource group get information uri parameter powershell splatting contenttype application json method get headers authorization bearer token host invoke-restmethod select-object.png

 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.

Microsoft Azure Rest API powershell Delete resource group information contenttype application json method delete headers authentication bearer token host management.azure.com invoke-restmethod uri.png

 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 

Go Back

Comment

Blog Search

Page Views

6106899

Follow me on Blogarama