apiVersion: v1
kind: ServiceAccount
metadata:
  name: ecr-update-sa
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: app
  name: ecr-update-role
rules:
- apiGroups: [""]
  resources: ["secrets"]
  # resourceNames: ["aws-registry"]
  verbs: ['create','delete']
---
# This role binding allows "jane" to read pods in the "default" namespace.
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: ecr-update-role
  namespace: app
subjects:
- kind: ServiceAccount
  name: ecr-update-sa # Name is case sensitive
  namespace: app
roleRef:
  kind: Role #this must be Role or ClusterRole
  name: ecr-update-role # this must match the name of the Role or ClusterRole you wish to bind to
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: ecr-update
  namespace: app
spec:
  schedule: "* */8 * * *"
  successfulJobsHistoryLimit: 1
  suspend: false
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: ecr-update-sa
          restartPolicy: OnFailure
          containers:
          - name: update-ecr
            image: amazon/aws-cli:2.0.6 
            env:
            - name: AWS_DEFAULT_REGION
              value: eu-central-1
            - name: AWS_SECRET_ACCESS_KEY
              value: QWERTYQWERTYQWERTY
            - name: AWS_ACCESS_KEY_ID
              value: QWERTYQWERTYQWERTY
            command:
            - /bin/bash
            - -c
            - |-
              # Installing kubectl
              curl -SsL https://dl.k8s.io/release/v1.20.0/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl ; chmod +x /usr/local/bin/kubectl
              ACCOUNT=998611063711      # custom script | your aws account id  
              REGION=eu-central-1      # custom script | your aws account region of choice 
              SECRET_NAME=aws-registry  # custom script | name of secret 
              EMAIL=anymail.doesnt.matter@email.com   # custom script | any email address
              TOKEN=$(aws ecr get-login-password --region ${REGION})   # custom script | this will call AWS ECr to gewt login password and store it in TOKEN
              echo "ENV variables setup done."
              kubectl delete secret --ignore-not-found $SECRET_NAME   # custom script | delte previous secret if any
              kubectl create secret docker-registry $SECRET_NAME \
              --docker-server=https://${ACCOUNT}.dkr.ecr.${REGION}.amazonaws.com \
              --docker-username=AWS \
              --docker-password="${TOKEN}" \
              --docker-email="${EMAIL}"
              echo "Secret created by name. $SECRET_NAME"
              echo "All done."
