Create Service Principle
The object of this post is to create a service principal that is used to build services in Azure from CLI. To be able to do this, we log in using az login and use user with role Owner. This is one time and just ot create a Service Principal that is going to be used in the future.
Below code creates a service principal developerCli with built-in role Contributor on a level (scope) of subscription. A new certificate is created for this service principal.
az ad sp create-for-rbac --name developerCli `
--role Contributor `
--scopes /subscriptions/00000000-0000-0000-0000-000000000000 `
--create-cert
The scope is quite wide and not best practice. This can be fine tuned by adding more scopes as a space delimited list to the –scope.
The output is similar to this one:
{
"appId": "10000000-0000-0000-0000-000000000000",
"displayName": "developerCli",
"fileWithCertAndPrivateKey": "C:\\Users\\marko\\tmpupgm31k_.pem",
"password": null,
"tenant": "20000000-0000-0000-0000-000000000000"
}
In Azure Console, the new Service Principal can be found under service Microsoft Entra ID -> drop down menu Manage -> App registrations ->All applications.
It makes sense to rename PEM file that was generated. For simplicity I will rename it to match the name of the Service Principal. Perhaps also a good idea to move the file. If you do so, move it before you start your work with this Service Principal because this file is being read at every az command.
Test Service Principle
Now the Service Principal can be tested:
az login --service-principal `
-u 10000000-0000-0000-0000-000000000000 `
-p C:\marko\keys\developerCli.pem `
--tenant 20000000-0000-0000-0000-000000000000
Value for tenant can either be tenant id from the output when Service Principal was created or publisher domain – value with suffix .onmicrosoft.com.
If all goes well a JSON object is returned:
[
{
"cloudName": "AzureCloud",
"homeTenantId": "20000000-0000-0000-0000-000000000000",
"id": "30000000-0000-0000-0000-000000000000",
"isDefault": true,
"managedByTenants": [],
"name": "Test",
"state": "Enabled",
"tenantId": "20000000-0000-0000-0000-000000000000",
"user": {
"name": "10000000-0000-0000-0000-000000000000",
"type": "servicePrincipal"
}
}
]
Value Test is the subscription this Service Principal is created in.