Access the Azure Container Registry using Azure Managed Identity programatically
- Install the MSI to the VM
2. Get the ARM access token from the MSI endpoint
response=$(curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F' -H Metadata:true -s) access_token=$(echo $response | python -c 'import sys, json; print (json.load(sys.stdin)["access_token"])') client_id=$(echo $response | python -c 'import sys, json; print (json.load(sys.stdin)["client_id"])')
3. Get the refresh token from “https://$REGISTRY/oauth2/exchange” at first and then use the refresh token to get the access token for ACR
REGISTRY=" --- you have to fill this out --- "
REPOSITORY=" --- you have to fill this out --- "
AAD_ACCESS_TOKEN=$(az account get-access-token --query accessToken -o tsv)
ACR_REFRESH_TOKEN=$(curl -s -X POST -H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=access_token&service=$REGISTRY&access_token=$AAD_ACCESS_TOKEN" \
https://$REGISTRY/oauth2/exchange \
| jq '.refresh_token' \
| sed -e 's/^"//' -e 's/"$//')
echo "ACR Refresh Token obtained."
# Create the repo level scope
SCOPE="repository:$REPOSITORY:pull"
# to pull multiple repositories passing in multiple scope arguments.
#&scope="repository:repo:pull,push"
ACR_ACCESS_TOKEN=$(curl -s -X POST -H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=refresh_token&service=$REGISTRY&scope=$SCOPE&refresh_token=$ACR_REFRESH_TOKEN" \
https://$REGISTRY/oauth2/token \
| jq '.access_token' \
| sed -e 's/^"//' -e 's/"$//')
echo "ACR Access Token obtained."
4. Login to ACR with the access token obtained. Please be advised the username is “00000000–0000–0000–0000–000000000000”
docker login -u 00000000-0000-0000-0000-000000000000 -p $ACR_ACCESS_TOKEN $REGISTRY
docker pull $REGISTRY/$REPOSITORY
You could find more detail about login to ACR programatically in below
kubelet with cloud-provider as Azure also uses the similar approach