Create service principal programmatically in Azure Python API

Question

How can I, using the Azure Python API, create a full set of credentials that can later be used to start and deallocate all VMs in a named resource group, without any other permissions?

I have thoroughly researched the example code and both official and unofficial documentation, but I don't even know where to start...

I know I will need a tenant ID, client ID, client secret and subscription ID. Which of those can I make using an API, and how would I go about assigning roles to allow for starting/deallocating VMs of an existing resource group?

Sample code highly sought after, but will take any hint!

Solution

Your need the azure-graphrbac package to create a Service Principal:

The closer to a sample might be this unittest:

For role and permissions, you need azure-mgmt-authorization:

Best sample for this one, is probably the sub-part of this sample:

"msi_identity" is a synonym of "service principal" in your context.

Note that all of this is supported by the CLI v2.0:

It might be interested to test the CLI in --debug mode and sniffing in the code repo at the same time:

(full disclosure, I work at MS in the Azure SDK for Python team)