apiVersion: batch/v1beta1
kind: CronJob  
metadata:
  name: refresh-aws-ecr-credential-cronjob
spec:
  schedule: "* */3 * * *"  # refresh every 3h
  jobTemplate:
    spec:
      template:
        spec:
          containers:    
          - image: pcloud/aws-ecr-credential-helper
            imagePullPolicy: IfNotPresent 
            name: aws-ecr-credential-helper 
            command:
            - /bin/sh   
            - -c        
            - |-
              SECRET_NAME=$AWS_REGION-ecr-registry;
              echo $SECRET_NAME;
              TOKEN=$(aws ecr get-login --region $AWS_REGION --registry-ids $AWS_ACCOUNT_ID | cut -d' ' -f6);
              echo "ENV variables setup done.";
              kubectl delete secret --ignore-not-found $SECRET_NAME;
              kubectl create secret docker-registry $SECRET_NAME --docker-server=https://$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com --docker-username='AWS' --docker-password=$TOKEN --docker-email=$EMAIL;
              echo "Done!";
            env:
            - name: AWS_ACCOUNT_ID
              value: "your-aws-account-id"
            - name: AWS_REGION
              value: ap-southeast-1
            - name: AWS_ACCESS_KEY_ID
              valueFrom:
                secretKeyRef:
                  name: aws-credential
                  key: AWS_ACCESS_KEY_ID
            - name: AWS_SECRET_ACCESS_KEY
              valueFrom:
                secretKeyRef:
                  name: aws-credential
                  key: AWS_SECRET_ACCESS_KEY
          restartPolicy: OnFailure
  failedJobsHistoryLimit: 1
  successfulJobsHistoryLimit: 3