Menu

Virtual Geek

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

Azure Rest API connect with Powershell and create resources

Powershell Microsoft Azure Rest API postman configuration automation application platform interface invoke-webrequest invoke-restmethod.png

I had a task to explore and deploy resources in Microsoft Azure using Rest API. Very good and detailed documentation is provided by Microsoft for Azure Rest API here https://learn.microsoft.com/en-us/rest/api/azure/

In this example I will use PowerShell to automate Azure Rest API and create Resource Group and Storage Account. For the new resource group name, location and storage account name I have provided in variables.

Next authentication and authorization purpose I am using Azure subscription id, tenant id, App Registrations (Service Principal) client id and client secret. Using this I will get oauth2 token which I will keep on reuse (until it expires). I will use the token as bearer in headers to create the resources further.

While creating Resource Group you will need to provide its name, location in the body and same thing is for Storage Account. In the PowerShell core cmdlet Invoke-RestMethod (WebRequest) is used to connect and perform the actions over Rest API.

Download PowerShellAzureRestApiExample.ps1 here or this script is also available on github.com.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
#Documentation
#https://learn.microsoft.com/en-us/rest/api/azure/
#https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-client-creds-grant-flow#get-a-token

# Define the resources - resource group and storage account details
$resourceGroupName = "prod.vcloud-lab.com"
$resourceGroupLocation = "West US"
$storageAccountName = "vcloudlabsaprod"

# Define your Azure subscription ID and an access token
$subscriptionId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$tenantId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$clientId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$clientSecret = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'

# Body information for http authentication
$body = @{
    grant_type    = "client_credentials"
    client_id     = $clientId
    client_secret = $clientSecret
    resource      = "https://management.azure.com/"
}

# Create 
$response = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantId/oauth2/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body 
$accessToken = $response.access_token

# Headers for the API requests
$headers = @{
    "Authorization" = "Bearer $accessToken"
    "Content-Type"  = "application/json"
}

Write-Host 'Creating Resource Group in Azure'
#https://learn.microsoft.com/en-us/rest/api/resources/resource-groups?view=rest-resources-2021-04-01
#https://learn.microsoft.com/en-us/rest/api/resources/resource-groups/create-or-update?view=rest-resources-2021-04-01&tabs=HTTP
# Create the resource group
$resourceGroupUri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/$($resourceGroupName)?api-version=2021-04-01"
$resourceGroupBody = @{
    location = $resourceGroupLocation
} | ConvertTo-Json

$rgResponse = Invoke-RestMethod -Method Put -Uri $resourceGroupUri -Headers $headers -Body $resourceGroupBody

Start-Sleep -Seconds 10

while ($rgResponse.properties.provisioningState -ne 'Succeeded') {
    Start-Sleep -Seconds 2
}

Write-Host 'Creating Storage Account in Azure'
#https://learn.microsoft.com/en-us/rest/api/storagerp/storage-sample-create-account
# Create the storage account
$storageAccountUri = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Storage/storageAccounts/$($storageAccountName)?api-version=2021-04-01"
$storageAccountBody = @{
    location = $resourceGroupLocation
    kind     = "StorageV2"
    sku      = @{
        name = "Standard_LRS"
    }
} | ConvertTo-Json

Invoke-RestMethod -Method Put -Uri $storageAccountUri -Headers $headers -Body $storageAccountBody

Start-Sleep -Seconds 10

Write-Host "Resource group and storage account created successfully."

<#

###################################
# Delete method with different token scope example
###################################

#https://learn.microsoft.com/en-us/rest/api/resources/resource-groups/delete?view=rest-resources-2021-04-01&tabs=HTTP
#https://learn.microsoft.com/en-us/rest/api/resources/resources/list-by-resource-group?view=rest-resources-2021-04-01

#Get resources information inside resource group
$resourceGroupResourcesUri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/$resourceGroupName/resources?api-version=2021-04-01"
$resourcesResponse = Invoke-RestMethod -Method Get -Uri $resourceGroupResourcesUri -Headers $headers 


# Delete resource group
$resourceGroupUri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/$($resourceGroupName)?api-version=2021-04-01" ##?forceDeletionTypes=Microsoft.Compute/virtualMachines,Microsoft.Compute/virtualMachineScaleSets&api-version=2021-04-01
Invoke-RestMethod -Method Delete -Uri $resourceGroupUri -Headers $headers 

# Only works for virtual machines and vmss
#$allResourcesType = $resourcesResponse.value.type -join ','
#$resourceGroupUri = "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/$($resourceGroupName)?forceDeletionTypes=$allResourcesType&api-version=2021-04-01" 

#>

<# Another Way to get access token
    #https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-client-creds-grant-flow#get-a-token
    #curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'client_id=00001111-aaaa-2222-bbbb-3333cccc4444&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=A1bC2dE3f...&grant_type=client_credentials' 'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
    
    $body = @{
        client_id     = $clientId
        client_secret = $clientSecret
        scope      = "https://graph.microsoft.com/.default"
        grant_type    = "client_credentials"
    } #| ConvertTo-Json -Compress
    
    $bodyEncoded = ($body.GetEnumerator() | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join "&"

    $response = Invoke-WebRequest -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -Method Post -Body $bodyEncoded -ContentType 'application/x-www-form-urlencoded'
    $token = $response.Content | ConvertFrom-Json
    $token.access_token
#>

Useful Articles
Create a Azure Virtual Network with Subnet using PowerShell
Azure add create a Subnet to existing Virtual Network using PowerShell
Remove Azure Virtual Network Subnet using PowerShell
Create key vault and secrets with access policies in Microsoft Azure
Working With Azure Key Vault Using Azure PowerShell and AzureCLI
Use Key Vault secret identifier url to get the secret value using Powershell
Use a Azure VM system assigned managed identity to access Azure Key Vault
Create Azure Key Vault Certificates on Azure Portal and Powershell
Export certificates from Azure Key Vault using PowerShell

Go Back

Comment

Blog Search

Page Views

12273565

Follow me on Blogarama