apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig

metadata:
  name: rl-gs-autopilot
  region: us-west-2

nodeGroups:
  - name: mixed-instances-1
    minSize: 2
    maxSize: 50
    ssh:
      allow: true
      publicKeyPath: ~/.ssh/id_rsa.pub
    instancesDistribution:
      instanceTypes: ["c4.large","c4.xlarge","c3.large","c3.xlarge","c5.large","c5.xlarge","c5.2xlarge","c5.4xlarge","c5d.large","c5d.xlarge","c5d.2xlarge","c5d.4xlarge"]
      onDemandPercentageAboveBaseCapacity: 0
      onDemandBaseCapacity: 0
    overrideBootstrapCommand: |
        #!/bin/bash
        set -o errexit
        set -o pipefail
        set -o nounset
        function get_max_pods() {
          while read instance_type pods; do
            if  [[ "${instance_type}" == "${1}" ]] && [[ "${pods}" =~ ^[0-9]+$ ]] ; then
             echo ${pods}
             return
            fi
          done < /etc/eksctl/max_pods.map
        }
        EC2_AVAIL_ZONE=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
        export AWS_DEFAULT_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed 's/[a-z]$//'`"
        NODE_IP="$(curl --silent http://169.254.169.254/latest/meta-data/local-ipv4)"
        INSTANCE_ID="$(curl --silent http://169.254.169.254/latest/meta-data/instance-id)"
        INSTANCE_TYPE="$(curl --silent http://169.254.169.254/latest/meta-data/instance-type)"
        source /etc/eksctl/kubelet.env # this can override MAX_PODS
        INSTANCE_LIFECYCLE=$(aws ec2 describe-instances --instance-ids  ${INSTANCE_ID}  --query 'Reservations[0].Instances[0].InstanceLifecycle' --output text)
        if [ "$INSTANCE_LIFECYCLE" == "spot" ]; then
          NODE_LABELS="${NODE_LABELS},lifecycle=Ec2Spot"
        else
          NODE_LABELS="${NODE_LABELS},lifecycle=OnDemand"
        fi
        if [ "$INSTANCE_LIFECYCLE" == "spot" ]; then
          if [ "$NODE_TAINTS" == "" ]; then
            NODE_TAINTS="spotInstance=true:PreferNoSchedule"
          else
            NODE_TAINTS="${NODE_TAINTS},spotInstance=true:PreferNoSchedule"
          fi
        else
          NODE_TAINTS="${NODE_TAINTS}"
        fi
        cat > /etc/eksctl/kubelet.local.env <<EOF
        NODE_IP=${NODE_IP}
        INSTANCE_ID=${INSTANCE_ID}
        INSTANCE_TYPE=${INSTANCE_TYPE}
        MAX_PODS=${MAX_PODS:-$(get_max_pods "${INSTANCE_TYPE}")}
        NODE_LABELS=${NODE_LABELS}
        NODE_TAINTS=${NODE_TAINTS}
        EOF
        systemctl daemon-reload
        systemctl enable kubelet
        systemctl start kubelet