# CronJob used to run per 6 hour to renew ECR Password login
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: ecr-cred-helper
  namespace: default
spec:
  concurrencyPolicy: Allow
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - image: odaniait/aws-kubectl:latest
            imagePullPolicy: IfNotPresent
            name: ecr-cred-helper
            command:
            - /bin/sh
            - -c
            - |-
              #!/bin/sh

              mkdir -p ~/.aws
              cat > ~/.aws/credentials <<EOF
              [default]
              aws_access_key_id=AWSACCESSKEYIDXXX
              aws_secret_access_key=AWSSECRETACCESSKEYXXX
              EOF

              cat > ~/.aws/config <<EOF
              [profile 123456789]
              region = ap-southeast-1
              role_arn = arn:aws:iam::123456789:role/terraform-role
              source_profile = default

              [profile 987654321]
              region = ap-southeast-1
              role_arn = arn:aws:iam::987654321:role/terraform-role
              source_profile = default
              EOF

              secrets=""

              buildsecret() {
                AWS_PROFILE=$1
                SECRET_NAME=${AWS_PROFILE}-${AWS_DEFAULT_REGION}-ecr-registry
                TOKEN=$(aws ecr get-login-password)

                echo "ENV variables setup done."
                kubectl delete secret --ignore-not-found "$SECRET_NAME"
                kubectl create secret docker-registry "$SECRET_NAME" \
                --docker-server="https://${AWS_PROFILE}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com" \
                --docker-username=AWS \
                --docker-password="${TOKEN}"

                echo "Secret created by name. $SECRET_NAME"

                secrets="{\"name\":\"$SECRET_NAME\"}${secrets:+,$secrets}"
              }

              for acc in $(echo "${AWS_ACCOUNTS:-}" | tr ',' ' '); do
                buildsecret "$acc"
              done

              kubectl patch serviceaccount default -p '{"imagePullSecrets":['"$secrets"']}'
              echo "All done."
            env:
            - name: AWS_ACCOUNTS
              value: "123456789,987654321"
            - name: AWS_DEFAULT_REGION
              value: ap-southeast-1
            resources: {}
          dnsPolicy: Default
          restartPolicy: Never
          securityContext: {}
          terminationGracePeriodSeconds: 30
  schedule: "* */6 * * *"
  successfulJobsHistoryLimit: 3
  suspend: false
