Skip to content

Instantly share code, notes, and snippets.

@guessi
Last active September 18, 2023 07:11
Show Gist options
  • Save guessi/89eb1a8227d3ffea06e10ecd9d890b0f to your computer and use it in GitHub Desktop.
Save guessi/89eb1a8227d3ffea06e10ecd9d890b0f to your computer and use it in GitHub Desktop.
Refresh ECR Token for Kubernetes - Resolve ECR Token Expired Issue
#!/bin/bash
# prerequisite:
# - ec2 instance should attached proper iam role
# - awscli
# - kubectl
# Usage:
#
# define the following variales in your environment (root account)
# - ECR_ACCOUNT
# - ECR_REGION
# - SECRET_NAME
#
# $ cp <script-file> /etc/cron.hourly/refresh_ecr_token
# $ chmod +x /etc/cron.hourly/refresh_ecr_token
# define ecr related information
ECR_ACCOUNT="${ECR_ACCOUNT:-123456789012}"
ECR_REGION="${ECR_REGION:-ap-northeast-1}"
SECRET_NAME="${SECRET_NAME:-ecr-auth}"
DOCKER_REGISTRY="https://${ECR_ACCOUNT}.dkr.ecr.${ECR_REGION}.amazonaws.com"
refresh_token() {
# get latest ecr login token via awscli
TOKEN=$(aws ecr get-authorization-token \
--region="${REGION}" \
--output text \
--query 'authorizationData[].authorizationToken' | \
base64 -d | cut -d':' -f2)
# abort if token retrieval failed
if [ -z "${TOKEN}" ]; then
echo "==> Abort, get token failed"
exit 1
fi
# remove previous created secret (any failure will be ignored)
kubectl delete secret --ignore-not-found "${SECRET_NAME}" || true
# refresh ecr token with new token
kubectl create secret docker-registry "${SECRET_NAME}" \
--docker-server="${DOCKER_REGISTRY}" \
--docker-username=AWS \
--docker-password="${TOKEN}" \
--docker-email="no-reply@example.com"
}
refresh_token "${ECR_REGION}"
@rabbagliettiandrea
Copy link

Thank you so much @guessi, that's very simple and clever :)

@guessi
Copy link
Author

guessi commented Sep 25, 2021

@rabbagliettiandrea happy to know the script help someone around the world~ 😃

@manish436
Copy link

manish436 commented Mar 23, 2022

Thanks @guessi, small change I made to make it working on mac just added single quote around --query 'authorizationData[].authorizationToken'

@guessi
Copy link
Author

guessi commented Mar 24, 2022

@manish436 Thanks for report and now it's fixed 🎉

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