#cloud-config
write_files:
  - path: /etc/systemd/system/enable-kube-apiserver.service
    owner: "root:root"
    permissions: "0644"
    content: |
      [Unit]
      Description=Configure Kubernetes API Server

      [Service]
      Type=oneshot
      EnvironmentFile=/etc/sysconfig/heat-params
      ExecStart=/etc/sysconfig/enable-kube-apiserver.sh

      [Install]
      WantedBy=multi-user.target

  - path: /etc/sysconfig/enable-kube-apiserver.sh
    owner: "root:root"
    permissions: "0755"
    content: |
      #!/bin/sh

      KUBE_ADMISSION_CONTROL=""
      if [ -n "${ADMISSION_CONTROL_LIST}" ] && [ "${TLS_DISABLED}" == "False" ]; then
          KUBE_ADMISSION_CONTROL="- --admission-control=${ADMISSION_CONTROL_LIST}"
      fi

      TLS_CERT_FILE=${KUBE_CERTS_PATH}/apiserver.pem
      TLS_PRIVATE_KEY_FILE=${KUBE_CERTS_PATH}/apiserver-key.pem
      CLIENT_CA_FILE=${KUBE_CERTS_PATH}/ca.pem
      INSECURE_PORT=8080
      SECURE_PORT=${KUBE_API_PORT}
      BIND_ADDRESS_CMD="--bind-address=0.0.0.0"
      if [ "${TLS_DISABLED}" == "True" ]; then
        TLS_CERT_FILE=
        TLS_PRIVATE_KEY_FILE=
        CLIENT_CA_FILE=
        INSECURE_PORT=${KUBE_API_PORT}
        SECURE_PORT=0
        BIND_ADDRESS_CMD="--insecure-bind-address=0.0.0.0"
      fi

      TEMPLATE=/etc/kubernetes/manifests/kube-apiserver.yaml
      mkdir -p $(dirname ${TEMPLATE})
      cat > $TEMPLATE <<EOF
      apiVersion: v1
      kind: Pod
      metadata:
        name: kube-apiserver
        namespace: kube-system
      spec:
        hostNetwork: true
        containers:
        - name: kube-apiserver
          image: ${HYPERKUBE_IMAGE_REPO}:${KUBE_VERSION}
          command:
          - /hyperkube
          - apiserver
          - ${BIND_ADDRESS_CMD}
          - --etcd-servers=http://127.0.0.1:2379
          - --allow-privileged=${KUBE_ALLOW_PRIV}
          - --service-cluster-ip-range=${PORTAL_NETWORK_CIDR}
          - --secure-port=${SECURE_PORT}
          - --insecure-port=${INSECURE_PORT}
          - --tls-cert-file=${TLS_CERT_FILE}
          - --tls-private-key-file=${TLS_PRIVATE_KEY_FILE}
          - --client-ca-file=${CLIENT_CA_FILE}
          - --service-account-key-file=${TLS_PRIVATE_KEY_FILE}
          ${KUBE_ADMISSION_CONTROL}
          ports:
          - containerPort: 6443
            hostPort: 6443
            name: https
          - containerPort: 8080
            hostPort: 8080
            name: local
          volumeMounts:
          - mountPath: ${KUBE_CERTS_PATH}
            name: ssl-certs-kubernetes
            readOnly: true
          - mountPath: /etc/ssl/certs
            name: ssl-certs-host
            readOnly: true
        volumes:
        - hostPath:
            path: ${KUBE_CERTS_PATH}
          name: ssl-certs-kubernetes
        - hostPath:
            path: ${HOST_CERTS_PATH}
          name: ssl-certs-host
      EOF
