How to Create Service Principles in Azure¶
To use service principles while running Azure commands in Azure DevOps pipelines, you will need to first create a service principle and grant it the necessary permissions in Azure. Then, you can use the service principle's credentials to authenticate and authorize the Azure commands that you want to run in your Azure DevOps pipelines.
Here is an example of how you can create a service principle and use it in an Azure DevOps pipeline:¶
-
Sign in to the Azure portal and navigate to the Azure Active Directory page.
-
Click on "App registrations" and then click on the "New registration" button.
-
Give your service principle a name and select "Accounts in this organizational directory only" as the supported account type. Click on the "Register" button to create the service principle.
-
Click on the service principle that you just created, and then click on the "Certificates & secrets" tab.
-
Click on the "New client secret" button, give the secret a description, and select an expiration time. Click on the "Add" button to create the secret.
-
Copy the secret value, as you will need it later or Store it in a Key-Vault
-
Navigate to the resource or resources that you want to grant the service principle access to.
-
Click on the "Access control (IAM)" tab, and then click on the "Add role assignment" button.
-
Select the role that you want to assign to the service principle, and then type in the name of the service principle in the "Select" field. Click on the "Save" button to assign the role to the service principle.
-
To use the service principle in your Azure DevOps pipeline, you will need to pass the service principle's client ID and client secret as environment variables. Here is an example of how you can do this:
-
In your Azure DevOps project, navigate to the "Pipelines" page and click on the pipeline that you want to edit.
-
Click on the "Variables" tab, and then click on the "Add" button.
-
Add two new variables with the names "AZURE_CLIENT_ID" and "AZURE_CLIENT_SECRET", and set the values to the service principle's client ID and client secret, respectively.
-
In your pipeline tasks, use the service principle's client ID and client secret to authenticate and authorize the Azure commands that you want to run. For example, you can use the following command to authenticate using the service principle:
az login - service-principal -u $AZURE_CLIENT_ID -p $AZURE_CLIENT_SECRET - tenant $TENANT_ID
Note
-
Replace TENANT_ID with the ID of your Azure Active Directory tenant.
-
Don't forget to store AZURE_CLIENT_ID & AZURE_CLIENT_SECRET in Key-Vault for Future Use.