DEV Community

Abhishek Gupta for Microsoft Azure

Posted on • Updated on

Quick tip: How to get your Kubernetes cluster service principal and use it to access other Azure services?

So, you have a Kubernetes cluster on Azure (AKS) which needs to access other Azure services like Azure Container Registry (ACR)? You can use your AKS cluster service principal for this.

All you need to do is delegate access to the required Azure resources to the service principal. Simply create a role assignment using az role assignment create to do the following:

  • specify the particular scope, such as a resource group
  • then assign a role that defines what permissions the service principal has on the resource

It looks something like this:

az role assignment create --assignee $AKS_SERVICE_PRINCIPAL_APPID --scope $ACR_RESOURCE_ID --role $SERVICE_ROLE
Enter fullscreen mode Exit fullscreen mode

Notice that the --assignee here is nothing but the service principal and you're going to need it.

When you create an AKS cluster in the Azure portal or using the az aks create command from the Azure CLI, Azure can automatically generate a service principal. Alternatively, you can create one your self using az ad sp create-for-rbac --skip-assignment and then use the service principal appId in --service-principal and --client-secret (password) parameters in the az aks create command.

You can use a handy little query in the az aks show command to locate the service principal quickly!

az aks show --name $AKS_CLUSTER_NAME --resource-group $AKS_CLUSTER_RESOURCE_GROUP --query servicePrincipalProfile.clientId -o tsv
Enter fullscreen mode Exit fullscreen mode

This will the service principal appId! You can use it to grant permissions. For e.g. if you want to allow AKS to work with ACR, you can grant the acrpull role:

az role assignment create --assignee $AKS_SERVICE_PRINCIPAL_APPID --scope $ACR_RESOURCE_ID --role acrpull
Enter fullscreen mode Exit fullscreen mode




Here is the list of commands for your reference:

If you found this article helpful, please like and follow! Happy to get feedback via @abhi_tweeter or just drop a comment :-)

Top comments (0)