Skip to content

Instantly share code, notes, and snippets.

@shmileee
Last active September 8, 2023 11:38
Show Gist options
  • Save shmileee/56e6baa021dc9da56ac700d43a3b8345 to your computer and use it in GitHub Desktop.
Save shmileee/56e6baa021dc9da56ac700d43a3b8345 to your computer and use it in GitHub Desktop.
Mirror all private images from DockerHub organisation to ECR
#!/bin/bash
ecr_url="<account id>.dkr.ecr.<region>.amazonaws.com"
# set username, password, and organization
dockerhub_username="<user>"
dockerhub_password="<password>"
dockerhub_organization="<org>"
dockerhub_api_url="https://hub.docker.com/v2"
dockerhub_token=$(curl -s -H "Content-Type: application/json" -X POST -d \
'{"username": "'${dockerhub_username}'", "password": "'${dockerhub_password}'"}' \
https://hub.docker.com/v2/users/login/ | jq -r .token)
dockerhub_repositories=$(curl -s -H "Authorization: JWT ${dockerhub_token}" \
"${dockerhub_api_url}/repositories/${dockerhub_organization}/?page_size=100" | jq -r \
'.results[] | select(.is_private) | .name')
for repo in ${dockerhub_repositories}; do
echo -e "=== WORKING ON REPOSITORY ${repo} ==="
ecr_repository=$(aws-vault exec appsilon-infra-sso -- \
aws ecr describe-repositories | jq --arg v "$repo" -r \
'.repositories[] | select(.repositoryName == $v) | .repositoryName')
if [ "$ecr_repository" != "$repo" ]; then
echo "$repo does not exist in ECR yet, skipping";
continue
fi
dockerhub_tags=$(curl -s -H "Authorization: JWT ${dockerhub_token}" \
"${dockerhub_api_url}/namespaces/${dockerhub_organization}/repositories/${repo}/images" | jq -r \
'.results[].tags[].tag')
for tag in ${dockerhub_tags}; do
echo -e "=== WORKING ON ${repo}:${tag} ==="
ecr_tag=$(aws-vault exec appsilon-infra-sso -- \
aws ecr list-images --repository-name "${repo}" | grep -o \"$tag\" | tr -d '"')
if [ "${ecr_tag}" != "${tag}" ]; then
echo -e "===PULLING==="
docker pull "${dockerhub_organization}/${repo}:${tag}"
echo -e "===RETAGGING==="
docker tag "${dockerhub_organization}/${repo}:${tag}" "${ecr_url}/${repo}:${tag}"
echo "${repo}:${tag} retagged to ${ecr_url}/${repo}:${tag}"
echo -e "===PUSHING==="
docker push "${ecr_url}/${repo}:${tag}"
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment