Skip to content

Instantly share code, notes, and snippets.

@mjpitz
Created January 17, 2020 14:14
Show Gist options
  • Save mjpitz/a432acc451e63b331ebeecb1794f31f3 to your computer and use it in GitHub Desktop.
Save mjpitz/a432acc451e63b331ebeecb1794f31f3 to your computer and use it in GitHub Desktop.
Simple little script for demonstrating certificate auth in kubernetes
#!/usr/bin/env bash
## Simple script demonstrating how to use certificate auth in Kubernetes. In this script
## we leverage the built in csr approval process. In practice, the approval process can
## be delegated to an external authority so long as the external authority and the
## Kubernetes API server share a common CA.
readonly name=${1:-$(whoami)}
trap "rm ${name}-key.pem ${name}.csr ${name}.crt" EXIT
cat <<EOF | cfssl genkey - | cfssljson -bare ${name}
{
"CN": "${name}",
"names": [
{ "O": "system:authenticated" },
{ "O": "system:masters" }
],
"key": {
"algo": "ecdsa",
"size": 256
}
}
EOF
kubectl delete csr ${name}
cat <<EOF | kubectl apply -f -
apiVersion: certificates.k8s.io/v1beta1
kind: CertificateSigningRequest
metadata:
name: ${name}
spec:
request: $(cat ${name}.csr | base64 | tr -d '\n')
usages:
- digital signature
- key encipherment
EOF
kubectl certificate approve ${name}
kubectl get csr ${name} -o jsonpath='{.status.certificate}' | base64 --decode > ${name}.crt
kubectl config set users.${name}.client-certificate-data $(cat ${name}.crt | base64 | tr -d '\n')
kubectl config set users.${name}.client-key-data $(cat ${name}-key.pem | base64 | tr -d '\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment