Professional Documents
Culture Documents
Today, I'll explain how to automate your Azure login in order to allow your scripts to run
without any supervision.
Disclaimer: many of these tasks should be running using the Azure Automation service because
of better integration and smoother on boarding. There's a ton of ready-made RunBooks in our
RunBook Gallery to do most of the default tasks such as VM maintenance etc. This post is about
scripts running outside that safe environment.
To automate our tasks we need an Active Directory (AD) application and a Service Principal.
The AD application contains the credentials (an application id and either a password or
certificate). The service principal contains the role assignment (permissions on the subscription).
You can use the same AD application to create many service principals with different
permissions.
Execute the following commands one at a time to ensure you don't miss out something. I've also
attached the output from these commands for clarity
Open the PowerShell ISE or any other PowerShell scripting tool (Visual Studio code, command
line etc)
Login-AzureRmAccount
If you don't know your subscription id or name, use the following command to list all your
subscription and choose the right one
Get-AzureRmSubscription
$azureAdApplication
Feel free to ignore the IdentifierUris and HomePage parameters. Just stick something the
resembles a URI and feel safe in the thought that they are never verified or used by your
application.
New-AzureRmADServicePrincipal -ApplicationId
$azureAdApplication.ApplicationId
https://azure.microsoft.com/en-us/documentation/articles/role-based-access-built-in-roles/
This was the last step. Make a note of ApplicationID and the password you used earlier as we'll
need them to automate our script execution next
To run any script against Azure, you need to first authenticate. If we are to automate things, we
don't want any part of the script to require manual intervention. And this is where our
ApplicationID and ServicePrincipal come handy.
The following script is an example of how you would use these to login and run an arbitrary
command. This is a very basic example that can become the basis for what you create next.
NOTE: at the time of writing this post, there's a bug where the Service Principal is missing
permissions to the latest Graph API causing an error to appear when you authenticate and run
scripts using this approach. The error, attached below, can be safely ignored.
This is due to be fixed soon and you can follow its progress on GitHub here.
Conclusion
It only takes 4 extra steps to create and use a Service Principal. The benefit of this approach is
that you can easily manage and audit access to your Azure resources while you automate things.