Skip to content

Instantly share code, notes, and snippets.

@zxkane
Last active April 26, 2021 09:55
Show Gist options
  • Save zxkane/33a58621abfea19815c2955231998007 to your computer and use it in GitHub Desktop.
Save zxkane/33a58621abfea19815c2955231998007 to your computer and use it in GitHub Desktop.
Push a container image to all ECR regions(create the repo if necessary)
#!/bin/bash -xe
create_repo() {
local name=$1
local region=$2
# create ecr repo
aws ecr create-repository --region $region --repository-name "$name" --image-tag-mutability IMMUTABLE --image-scanning-configuration scanOnPush=true --encryption-configuration encryptionType=AES256 2>/dev/null
# set repo permission
read -r -d '' POLICY_TEXT << EOM
{
"Version": "2008-10-17",
"Statement": [
{
"Sid": "public statement",
"Effect": "Allow",
"Principal": "*",
"Action": [
"ecr:BatchCheckLayerAvailability",
"ecr:BatchGetImage",
"ecr:GetDownloadUrlForLayer"
]
}
]
}
EOM
aws ecr set-repository-policy --region $region --repository-name "$name" --policy-text "$POLICY_TEXT" 2>/dev/null
}
push_to_ecr() {
local name=$1
local tag=$2
local region=$3
REGISTRYID=`aws ecr describe-repositories --region $region --repository-names $name --query 'repositories[].registryId' 2>/dev/null |jq -r '.[0]'`
REPO=`aws ecr describe-repositories --region $region --repository-names $name --query 'repositories[0].repositoryUri' --output text 2>/dev/null | sed -E 's/(.*\.amazonaws\.com(.cn)?).*/\1/'`
aws ecr get-login-password --region "$region" | docker login --username AWS --password-stdin $REPO
docker tag "$name:$tag" "$REPO/$name:$tag"
docker push "$REPO/$name:$tag"
}
push_repo() {
local name=$1
local tag=$2
local region=$3
EXISTINGREPO=`aws ecr describe-repositories --region $region --repository-names $name --query 'repositories[].repositoryName' 2>/dev/null|jq '.[]'|jq '.'`
if [[ -z $EXISTINGREPO ]]
then
create_repo "$name" "$region"
echo "The repo with name '$name' is created in region '$region'."
else
echo "The repo with name '$name' already exists in region '$region'."
fi
# push to ecr via docker
push_to_ecr "$name" "$tag" $region
}
REPONAME=$1
REPOTAG=$2
if [[ -z $REPONAME ]] || [[ -z $REPOTAG ]]
then
echo "pls specify REPONAME and REPOTAG."
exit -1
fi
export -f push_repo create_repo push_to_ecr
aws ec2 describe-regions --query 'Regions[].RegionName' --output json | jq '.[]'|jq '.'|xargs -I {} -n 1 bash -c 'push_repo "$@"' _ "$REPONAME" "$REPOTAG" {}
@zxkane
Copy link
Author

zxkane commented Apr 26, 2021

Publish local container image to ECR in all AWS regions.

The script will create a repository in each AWS region, then set the policy of repo to download by all AWS accounts.

Prerequisites

  • aws cli
  • jq
  • docker

Usage

./push-repo-to-all-ecr-regions.sh my-image-name 1.0.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment