Monday, August 2, 2021

 <#

 

.SYNOPSIS

 

This script is used to create, update and delete resources using Azure REST methods.

This is helpful to make deployments idempotent which is a requisite for Azure.

 

#>

 

 

param (

    [Parameter(Mandatory=$true)][string]$TenantId,

    [Parameter(Mandatory=$true)][string]$SubscriptionId,

    [string]$ClientId = "1b730954-1685-4b74-9bfd-dac224a7b894", # PowerShell Client Id

    [string]$ClientSecret = "",

    [string]$Resource = "https://management.core.windows.net/",

    [string]$environment = "AzureCloud",

    [string]$RequestAccessTokenUri = "https://login.microsoftonline.com/$TenantId/oauth2/token"

)

 

function getPayload() {

$encoded=[System.Web.HttpUtility]::UrlEncode($ClientSecret)

$payload = "grant_type=client_credentials&client_id=$ClientId&client_secret=$encoded&resource=$Resource"

return $payload

}

 

function getToken(){

$payload = getPayload

$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -body $payload -ContentType 'application/x-www-form-urlencoded'

Write-Host "Print Token $Token" -ForegroundColor Green

return $Token

}

 

function getResourceGroups(){

$Token = getToken

# Get Azure Resource Groups

$ResourceGroupApiUri = "https://management.azure.com/subscriptions/$SubscriptionId/resourcegroups?api-version=2017-05-10"

$Headers = @{}

$Headers.Add("Authorization","$($Token.token_type) "+ " " + "$($Token.access_token)")

$ResourceGroups = Invoke-RestMethod -Method Get -Uri $ResourceGroupApiUri -Headers $Headers

Write-Host "Print Resource groups $ResourceGroups" -ForegroundColor Green

Write-Output $ResourceGroups

return $ResourceGroups

}

Write-Host TenantId=$TenantId SubscriptionId=$SubscriptionId ClientId=$ClientId ClientSecret=$ClientSecret

getResourceGroups

 

<# Sample output

value

-----

{@{id=/subscriptions/<obfuscated>/resourceGroups/cloud-shell-storage-southcentralus; name=cloud-shell-storage-southcentralus; location=southcentralus; properties=}, @{id=/subscriptions/<obfuscated>/resourceGroups/SFQuickstartRG; name=SFQuickstartRG; location=southc...

{@{id=/subscriptions/<obfuscated>/resourceGroups/cloud-shell-storage-southcentralus; name=cloud-shell-storage-southcentralus; location=southcentralus; properties=}, @{id=/subscriptions/<obfuscated>/resourceGroups/SFQuickstartRG; name=SFQuickstartRG; location=southc...

 

#>


No comments:

Post a Comment