Skip to content

Instantly share code, notes, and snippets.

@dev-sareno
Last active October 9, 2023 05:11
Show Gist options
  • Save dev-sareno/51bb00bf9117d69e39d9f6f578662934 to your computer and use it in GitHub Desktop.
Save dev-sareno/51bb00bf9117d69e39d9f6f578662934 to your computer and use it in GitHub Desktop.
ECR credentials auto-renewal with Cron

EC2 Instance Profile (IAM Role)

IAM Role Trust Relationship:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "ec2.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

IAM Permission:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "ECRFullAccess",
            "Effect": "Allow",
            "Action": [
                "ecr:*"
            ],
            "Resource": [
                "arn:aws:ecr:ap-southeast-2:xxxxxxxxx:repository/my-image"
            ]
        },
        {
            "Sid": "GetAuthorizationToken",
            "Effect": "Allow",
            "Action": [
                "ecr:GetAuthorizationToken"
            ],
            "Resource": "*"
        }
    ]
}
$ mkdir -p /opt/cron
$ cat <<EOF > /opt/cron/k3s-ecr-credentails-auto-renewal.sh
#!/bin/bash

set -euxo pipefail

ecr=xxxxxxxxx.dkr.ecr.ap-southeast-2.amazonaws.com
ecrPassword=\$(aws ecr get-login-password --region ap-southeast-2)
kubectl create secret docker-registry ecr \
  --docker-username=AWS \
  --docker-password=\$ecrPassword \
  --docker-email=dev.sareno@gmail.com \
  --docker-server=\$ecr \
  --dry-run=client \
  -n default \
  -o yaml | kubectl apply -f -
echo "ECR login credentials have been renewed successfully!"
EOF
$ chmod +x /opt/cron/k3s-ecr-credentails-auto-renewal.sh
$ crontab -l > ecr
$ echo "# Renew ECR login credentials every 6 hours" >> ecr
$ echo "0 */6 * * * /opt/cron/k3s-ecr-credentails-auto-renewal.sh" >> ecr
$ crontab ecr
$ rm ecr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment