Skip to content

Instantly share code, notes, and snippets.

@sajayantony
Last active March 9, 2023 20:52
Show Gist options
  • Save sajayantony/8980ec9d330d52232ecf949609ba5891 to your computer and use it in GitHub Desktop.
Save sajayantony/8980ec9d330d52232ecf949609ba5891 to your computer and use it in GitHub Desktop.

Configure ACR cache with Docker Hub token

Create a DockerHub Reaonly Access Token.

Create readonly token in the security tab - https://hub.docker.com/settings/security

Create a Keyvault to hold this access token

This is optional and you can use an existing keyvault

#!/bin/bash

# Set variables
KEYVAULT_NAME=mykeyvaultname
RESOURCE_GROUP=myresourcegroupname
LOCATION=location
USERNAME=myusername
PASSWORD=mypassword

# Create resource group (if it doesn't exist)
az group create --name $RESOURCE_GROUP --location $LOCATION

# Create Key Vault
az keyvault create --name $KEYVAULT_NAME --resource-group $RESOURCE_GROUP --location $LOCATION

# Set username secret and get secret URI
USERNAME_SECRET_URI=$(az keyvault secret set --vault-name $KEYVAULT_NAME --name username --value $USERNAME --query id -o tsv)

# Set password secret and get secret URI
PASSWORD_SECRET_URI=$(az keyvault secret set --vault-name $KEYVAULT_NAME --name password --value $PASSWORD --query id -o tsv)

# Output secret URIs
echo "Secret URIs:"
echo "username: $USERNAME_SECRET_URI"
echo "password: $PASSWORD_SECRET_URI"

Create a credential set

REGISTRY=myregistry
SOURCE_REPO=docker.io/myregistry/private-artifacts
TARGET_REPO=ptc-private-artifacts
CACHE_RULE=dockerhub-repo-rule
CRED_SET=myregistry-dockerhub-creds
SOURCE_LOGIN_SERVER=docker.io

# Create credential set to access source registry

 az acr credential-set create -r $REGISTRY -n $CRED_SET 
    -l $SOURCE_LOGIN_SERVER\
    -u $USERNAME_SECRET_URI 
    -p $PASSWORD_SECRET_URI

Assign permissions to Keyvault

## Get the principal Id of system identity used to access keyvault. 

PRINCIPAL_ID=$(az acr credential-set show 
                -n $CRED_SET 
                -r $REGISTRY  \
                --query 'identity.principalId' 
                -o tsv)

## Assign premissions for the credential set access the KeyVault secret

az keyvault set-policy --name $KEYVAULT_NAME \
    --object-id $PRINCIPAL_ID \
    --secret-permissions get

Create the Cache rule with Credential Set

# Create and associate the cache rule with a cred set

az acr cache create -r $REGISTRY -n $CACHE_RULE 
    -s $SOURCE_REPO -t $TARGET_REPO 
    -c $CRED_SET

Pull your image

az acr login -n $REGISTRY
docker pull $REGISTRY.azurecr.io/$TARGET_REPO:$TAG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment