Search code examples
amazon-web-servicesamazon-ecr

Pull image from AWS ECR with apikey


I use this configuration for cron job to get temporary token from AWS ECR:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: {{ .Values.cronjob.name }}
spec:
  schedule: "0 */6 * * *"
  successfulJobsHistoryLimit: 0
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: grafana
          containers:
            - command:
                - /bin/sh
                - -c
                - |-
                  TOKEN=`aws ecr get-login-password --region ${REGION} | cut -d' ' -f6`
                  kubectl delete secret -n default --ignore-not-found $SECRET_NAME
                  kubectl create secret -n default docker-registry $SECRET_NAME \
                  --docker-server=$ECR_REPOSITORY \
                  --docker-username=AWS \
                  --docker-password=$TOKEN \
                  --namespace=default
                  kubectl patch serviceaccount default -p '{"imagePullSecrets":[{"name":"'$SECRET_NAME'"}]}' -n default
              envFrom:
              - secretRef:
                  name: mockup-secret-env
              - configMapRef:
                  name: application-mockup-configuration-configmap-env
              image: {{ .Values.cronjob.image }}
              imagePullPolicy: IfNotPresent
              name: {{ .Values.cronjob.name }}
          restartPolicy: Never

Is it passible to pull images just with apikey without the need to generate a temporary token?


Solution

  • So that is exactly what the API key is for that you get from AWS. You simply need to login to the ECR registry, via the Docker CLI:

    docker login --username AWS --password "${TOKEN}" ${aws_account_id}.dkr.ecr.${REGION}.amazonaws.com
    

    Then you can push your image with the Docker CLI:

    docker push ${aws_account_id}.dkr.ecr.${REGION}.amazonaws.com/<image-name>
    

    More Info

    The AWS Private registry authentication documentation is clear that you must pull a token since the Docker CLI does not support authentication/authorization with AWS IAM. However, the token last for 12 hours, so you could cache the token for that long to reduce your network request for tokens for each registry. Also each different private registry requires a different token.

    However, you can also use the AWS CLI V2 to push and pull images, that should only require the IAM key and secret.

    For pushing see put.