Azure Function to Authenticate Azure PowerShell into the ARM APIs

Whilst working through a problem with a colleague I thought this would be a useful snippet to pop out there for ISVs who are deploying small scale tenant services or want to poll services and run Azure management processes in response to events. (This can be useful if your application design prevents you from using Autoscaling or VM Scale Sets in Azure, but you need to have some kind of flexibility in operations).

Literally copy and paste this into a powershell function, and define a service principal with the right permissions to connect to the subscription - then put SP_AppID and SP_Secret into your functionapp settings.


 # Define an AppService setting SP_AppID to be the Azure AD Service Principal applicationid
# Define the AppService setting SP_Secret to be an Azure AD Service Principal Secret
$secpasswd = ConvertTo-SecureString $ENV:SP_Secret -AsPlainText -Force 
$mycreds = New-Object System.Management.Automation.PSCredential ($ENV:SP_AppID, $secpasswd) 
$result = Login-AzureRmAccount -ServicePrincipal -Tenant $ENV:SP_Tenant -Credential $mycreds 
# Now do / deploy whatever you need to with the AzureRm Powershell cmdlets

You can host this on an Azure Functions Consumption Plan so this will cost you a minimal amount for hosting administrative processes.

The use case my colleague (Mike Ormond) was interested in was dynamic deployment of an entire application tenant in response to an authenticated web request.

In this case we would have fired the New-AzureRmResourceGroupDeployment cmdlet.

New-AzureRmResourceGroupDeployment -ResourceGroupName $rg -TemplateFile $templatefile -Force -TemplateParameterFile $tempparamfile 

And voila, a dynamically deployed application tenant, based on a template, you can now manage that subscription fully via ARM from your Azure Functions.

Now imagine if this function was bound via a storage queue to fire upon signup of a new tenant via a mgmt portal (say someone signs up with a credit card for your app).

That's all for now :)