Created
April 15, 2015 11:29
-
-
Save stuartpreston/a697bd300cb83669d9ed to your computer and use it in GitHub Desktop.
Some help for those using Powershell to automate Azure Resource Manager but don't want to install the Azure Powershell Cmdlets or ADAL, enter credentials in a web browser popup or set up an application as a Service Principal....
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.Synopsis | |
Retrieves a token object from the Azure OAUTH2 service without launching a credentials window. | |
.DESCRIPTION | |
Retrieves a token object that can later be used to authorise requests against the Microsoft Azure Resource Manager REST API. | |
.EXAMPLE | |
Get-AzureOauth2Token -username '[email protected]' -password 'P2ssw0rd' | |
#> | |
Function Get-AzureOauth2Token | |
{ | |
Param( | |
[Parameter(Mandatory=$True)] | |
[string]$username, | |
[Parameter(Mandatory=$True)] | |
[string]$password, | |
[string]$servicePrincipal = "1950a258-227b-4e31-a9cf-717495945fc2" | |
) | |
$encodedUsername = [Security.SecurityElement]::Escape($username) | |
$encodedPassword = [Security.SecurityElement]::Escape($password) | |
$url = "https://login.windows.net/Common/oauth2/token" | |
$data = @" | |
resource=https%3A%2F%2Fmanagement.core.windows.net%2F&client_id=$servicePrincipal&grant_type=password&username=$encodedUsername&password=$encodedPassword&scope=openid" | |
"@ | |
return Invoke-RestMethod -Uri $url -Method Post -Body $data | |
} | |
<# | |
.Synopsis | |
Retrieves the accessible Azure subscriptions, given a valid access token. | |
.DESCRIPTION | |
Lists the available Azure subscriptions via the Microsoft Azure Resource Manager REST API. | |
.EXAMPLE | |
Get-AzureSubscriptions -accessToken 'access_token' | |
#> | |
Function Get-AzureSubscriptionRest | |
{ | |
Param( | |
[Parameter(Mandatory=$True)] | |
[string]$accessToken | |
) | |
$url = "https://management.azure.com/subscriptions?api-version=2015-01-01" | |
$headers = @{Authorization=("Bearer {0}" -f $accessToken)} | |
$rest = Invoke-RestMethod -Uri $url -Method Get -ContentType "application/json" -Headers $headers | |
return $rest.value | |
} | |
# display valid Azure subscriptions | |
$oauth2token = Get-AzureOauth2Token -username "[email protected]" -password "P2ssw0rd" | |
Get-AzureSubscriptionRest -accessToken $oauth2token.access_token | Format-Table subscriptionId, displayName, state |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment