Skip to content

Instantly share code, notes, and snippets.

@yuya-takeyama
Last active May 26, 2020 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuya-takeyama/5f37f5d4626e8a1a9d3524bcb5d683b5 to your computer and use it in GitHub Desktop.
Save yuya-takeyama/5f37f5d4626e8a1a9d3524bcb5d683b5 to your computer and use it in GitHub Desktop.
Mirror images used in Kubernetes cluster into ECR
#!/bin/bash
set -eu
set -o pipefail
aws_profile="$1"
aws_region="$2"
function mirror-ecr-images() {
set -e
local aws_profile="$1"
local aws_region="$2"
local aws_account_id; aws_account_id="$(aws --profile "$aws_profile" sts get-caller-identity | jq .Account -r)"
local ecr_host_name; ecr_host_name="${aws_account_id}.dkr.ecr.${aws_region}.amazonaws.com"
aws --profile "$aws_profile" ecr get-login-password \
| docker login --username AWS --password-stdin "$ecr_host_name"
for image in $(kubectl get pods --all-namespaces -o json | jq '.items[].spec.containers[].image' -r | grep -v "$ecr_host_name" | sort | uniq); do
local mirror_repo_name; mirror_repo_name="mirror/$(echo "$image" | awk -F : '{ print $1 }')"
local absolute_mirror_image_name="$ecr_host_name/mirror/$image"
AWS_PAGER="" aws --profile "$aws_profile" ecr create-repository --repository-name "$mirror_repo_name" || :
docker pull "$image"
docker tag "$image" "$absolute_mirror_image_name"
docker push "$absolute_mirror_image_name"
done
}
mirror-ecr-images "$aws_profile" "$aws_region"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment