0
0
AzureHow-ToBeginner · 4 min read

How to Create a Service Principal in Azure: Step-by-Step Guide

To create a service principal in Azure, use the az ad sp create-for-rbac command in Azure CLI. This command creates an identity with specific permissions that apps or services can use to access Azure resources securely.
📐

Syntax

The basic syntax to create a service principal is:

  • az ad sp create-for-rbac --name <name> --role <role> --scopes <scope>

Where:

  • --name is the unique name for the service principal.
  • --role defines the permission level (e.g., Contributor, Reader).
  • --scopes limits the permissions to specific Azure resources.
bash
az ad sp create-for-rbac --name <name> --role <role> --scopes <scope>
💻

Example

This example creates a service principal named myAppSP with Contributor role on the subscription scope:

bash
az ad sp create-for-rbac --name myAppSP --role Contributor --scopes /subscriptions/00000000-0000-0000-0000-000000000000
Output
{ "appId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "displayName": "myAppSP", "name": "http://myAppSP", "password": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "tenant": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }
⚠️

Common Pitfalls

Common mistakes when creating service principals include:

  • Not specifying a unique --name, causing conflicts.
  • Assigning overly broad roles like Owner instead of least privilege roles.
  • Forgetting to set the correct --scopes, which can lead to security risks.
  • Not saving the appId and password immediately, as the password is shown only once.
bash
## Wrong: No scope specified (gives full subscription access)
az ad sp create-for-rbac --name myAppSP --role Contributor

## Right: Specify scope for limited access
az ad sp create-for-rbac --name myAppSP --role Contributor --scopes /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myResourceGroup
📊

Quick Reference

ParameterDescription
--nameUnique name for the service principal
--roleRole assigned (e.g., Contributor, Reader)
--scopesResource scope for permissions
--sdk-authOutputs credentials in JSON for SDK authentication
--yearsSet credential expiration in years

Key Takeaways

Use az ad sp create-for-rbac to create a service principal with specific roles and scopes.
Always assign the least privilege role needed to improve security.
Specify the scope to limit access to only required resources.
Save the output credentials immediately; the password is shown only once.
Use --sdk-auth option for easy integration with Azure SDKs.