generate-tls-config.sh 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env bash
  2. set -xe
  3. DIR=$1
  4. SERVICE=$2
  5. NAMESPACE=$3
  6. IP=$4
  7. if [ -z "${IP}" ]; then
  8. IP=127.0.0.1
  9. fi
  10. openssl genrsa -out "${DIR}"/"${SERVICE}".key 2048
  11. cat <<EOF >"${DIR}"/csr.conf
  12. [req]
  13. req_extensions = v3_req
  14. distinguished_name = req_distinguished_name
  15. [req_distinguished_name]
  16. [ v3_req ]
  17. basicConstraints = CA:FALSE
  18. keyUsage = nonRepudiation, digitalSignature, keyEncipherment
  19. extendedKeyUsage = serverAuth
  20. subjectAltName = @alt_names
  21. [alt_names]
  22. DNS.1 = ${SERVICE}
  23. DNS.2 = ${SERVICE}.${NAMESPACE}
  24. DNS.3 = ${SERVICE}.${NAMESPACE}.svc
  25. DNS.4 = ${SERVICE}.${NAMESPACE}.svc.cluster.local
  26. IP.1 = ${IP}
  27. EOF
  28. openssl req -new -key "${DIR}"/"${SERVICE}".key -subj "/CN=system:node:${SERVICE};/O=system:nodes" -out "${DIR}"/server.csr -config "${DIR}"/csr.conf
  29. export CSR_NAME=${SERVICE}-csr
  30. # Minimum 1.19.0 kubernetes version is required for certificates.k8s.io/v1 version
  31. SERVER_VERSION=$(kubectl version --short | awk -F "." '/Server Version/ {print $2}')
  32. MINIMUM_VERSION=19
  33. if [ "${SERVER_VERSION}" -lt "${MINIMUM_VERSION}" ]
  34. then
  35. cat <<EOF >"${DIR}"/csr.yaml
  36. apiVersion: certificates.k8s.io/v1beta1
  37. kind: CertificateSigningRequest
  38. metadata:
  39. name: ${CSR_NAME}
  40. spec:
  41. groups:
  42. - system:authenticated
  43. request: $(cat "${DIR}"/server.csr | base64 | tr -d '\n')
  44. usages:
  45. - digital signature
  46. - key encipherment
  47. - server auth
  48. EOF
  49. else
  50. cat <<EOF >"${DIR}"/csr.yaml
  51. apiVersion: certificates.k8s.io/v1
  52. kind: CertificateSigningRequest
  53. metadata:
  54. name: ${CSR_NAME}
  55. spec:
  56. groups:
  57. - system:authenticated
  58. request: $(cat "${DIR}"/server.csr | base64 | tr -d '\n')
  59. signerName: kubernetes.io/kubelet-serving
  60. usages:
  61. - digital signature
  62. - key encipherment
  63. - server auth
  64. EOF
  65. fi
  66. kubectl create -f "${DIR}/"csr.yaml
  67. kubectl certificate approve "${CSR_NAME}"
  68. timeout 10 bash <<-'EOF'
  69. until [ $(kubectl get csr "${CSR_NAME}" -o jsonpath='{.status.certificate}' | wc -c) -gt 1 ]; do
  70. echo "waiting for certificate "${CSR_NAME}" to be filled"
  71. sleep 1
  72. done
  73. EOF
  74. serverCert=$(kubectl get csr "${CSR_NAME}" -o jsonpath='{.status.certificate}')
  75. echo "${serverCert}" | openssl base64 -d -A -out "${DIR}"/"${SERVICE}".crt
  76. kubectl config view --raw --minify --flatten -o jsonpath='{.clusters[].cluster.certificate-authority-data}' | base64 -d > "${DIR}"/"${SERVICE}".ca