Here's my TL;DR on Azure Service Principals, with a full example of creating one to push docker images to Azure Container Registry.
First, you need an Azure Container Registry. So, go make one. And, once you're done go to its page in the UI and click Overview > JSON View
. See that Resource ID
? Copy that. That will become the scope
or the Azure thing we want to give to give our principal access to. Scopes can be at various levels. In this example, I'm very finely scoping down to ONLY this container registry resource. This principal will have no permissions anywhere else. You can go up levels in the scope hierarchy if you want, and say, provide access to all resources in a resource group
or even a subscription
. My resource ID looks a bit like this: /subscriptions/1d6a...982f/resourceGroups/my-container-registry/providers/Microsoft.ContainerRegistry/registries/registryname
.
Also, store the name of your registry if you want to push an image to it later.
Second, you need to determine what permissions you want to give to your principal. I wanted it to be able to generally contribute to my container registry -- pushing and pulling images. So, I choose the Contributor
role. To see what Roles are available on the container registry, click Access control (IAM)
from the left menu and then click Roles
on the right. It'll show the list of available roles for that service. The UI says that Contributor
gives "full access to manage all resources, but does not allow you to assign roles in Azure RBAC, manage assignments in Azure Blueprints, or share image galleries."
Now, I have the resource I want to assign the principal to. I also know what role that principal will play -- and thus what permissions it will have. Next, I need to make the principal, giving it a name
and assigning it the Contributor
role to just this resource. It was pretty easy using the Azure CLI, az
:
az ad sp create-for-rbac \
--name my-registry-bot \
--role Contributor \
--scopes /subscriptions/1d6a...982f/resourceGroups/my-container-registry/providers/Microsoft.ContainerRegistry/registries/registryname
The output of that command is some JSON:
{
"appId": "fake-appid",
"displayName": "my-registry-bot",
"password": "fake-password",
"tenant": "fake-tenant"
}
I called the principal, my-registry-bot
because I want to use it for CI/CD. I also hid the real return values. Just copy yours as you need to. Okay, that was easy. Now, to use my new principal to upload my newly created docker image we follow these steps:
# log in to azure using my new principal, which is identified by the fake-appid param
az login --service-principal -u fake-appid -p fake-password --tenant fake-tenant
# log in to azure container registry using the principal
az acr login --name my-registry-bot
# push the image
docker push myregistryname.azurecr.io/dockerImage:dockerTag