When using Azure, there are several reasons why you may be required to create a Service Principal. Such as
- Kubernetes
- Ansible
- Custom Applications
While Microsoft's Official Documentation tells you everything you need to know, we wanted to provide you with a quick and safe way to create a new Service Principal without using the Azure Portal and in a way that can be programmatically integrated into your existing IaC automation. Follow the directions below to create a Service Principal in Azure using the Azure CLI.
Note: This article was tested on Windows 10.
SPONSOR: Need to stop and start your development VMs on a schedule? The Azure Resource Scheduler let's you schedule up to 10 Azure VMs for FREE! Learn more HERE
Use the Azure CLI to create a new Service Principal in the target Azure Subscription.
$Azure_SP = az ad sp create-for-rbac `
--role "contributor" `
--name "iac-sp" `
--years 3
*Note:
-
When you don't supply a value for --role, then the Service Principal will be granted contributor rights across the entire Subscription. Additionally,the credentials are valid for 1 year by default*
-
If you see the following error: AKV10032: Invalid issuer. Expected one of https://sts.windows.net/0f300d03-624b-418d-bd13-f0dd744dbb4d/, https://sts.windows.net/f8cdef31-a31e-4b4a-93e4-5f571e91255a/, https://sts.windows.net/e2d54eb5-3869-4f70-8578-dee5fc7331f4/, found https://sts.windows.net/fbf7b187-7806-45ad-8d53-e31308109ee5/.
Run the following command before creating the service principle
az account set --subscription {SubscriptionID}
You should see the following output.
Changing "iac-sp" to a valid URI of "http://iac-sp", which is the required format used for service principal names
Creating a role assignment under the scope of "/subscriptions/00000000-0000-0000-0000-000000000000"
Retrying role assignment creation: 1/36
Retrying role assignment creation: 2/36
Retrying role assignment creation: 3/36
The Password that was automatically generated by Azure for the Service Principal is retrievable from the $Azure_SP variable.
You can view it out using the following command.
($Azure_SP | ConvertFrom-Json).password
You can use the following syntax below to store the Password in a variable and then add it to an existing Azure Key Vault.
$IaC_SP_Password = ($Azure_SP | ConvertFrom-Json).password
az keyvault secret set `
--name "iac-sp-password" `
--vault-name "myiacvault" `
--value "$IaC_SP_Password" `
--output none