apiVersion: batch/v1
kind: Job
metadata:
  name: redis-create-cluster
spec:
  template:
    spec:
      restartPolicy: Never
      volumes:
      - name: tls
        secret:
          secretName: redis-tls
          optional: true
      containers:
      - name: redis-create-custer
        image: redis:6.0.3
        env:
        - name: STATEFULSET_REPLICAS
          value: "6"
        - name: CLUSTER_REPLICAS
          value: "1"
        envFrom:
        - secretRef:
            name: redis-auth
            optional: true
        command:
        - bash
        - -ce
        - |
          set -o pipefail
          if [ "$REDIS_PASSWORD" != "" ]; then
              auth="--pass ${REDIS_PASSWORD}"
          fi
          if [ -f /tls/tls.key ]; then
              tls="--tls --cacert /tls/tls.crt"
          fi
          nodes=""
          for i in $(seq 0 $((STATEFULSET_REPLICAS-1))); do
              until timeout -s SIGKILL 5s redis-cli $tls $auth -h redis-$i ping >/dev/null 2>&1; do
                  echo redis-$i is not yet ready. waiting...
                  sleep 2
              done
              ip=$(getent hosts redis-$i | awk '{ print $1 }')
              nodes="$nodes $ip:6379"
          done
          echo nodes: $nodes
          echo yes | redis-cli $tls $auth --cluster create $nodes --cluster-replicas $CLUSTER_REPLICAS
        volumeMounts:
        - name: tls
          mountPath: /tls
