Skip to content

Instantly share code, notes, and snippets.

@wenerme
Created July 12, 2020 06:12
Show Gist options
  • Save wenerme/b5f93426bafc801855e6899c85c77c3b to your computer and use it in GitHub Desktop.
Save wenerme/b5f93426bafc801855e6899c85c77c3b to your computer and use it in GitHub Desktop.
K3S Create Client Cert
#!/bin/bash
set -e
fail(){
echo "error: $*"
echo "usage: ./k3s-new-cert <name> [subject=/O=admin]"
exit 1
}
name=$1
[ -z "$name" ] && fail No name
: ${SUBJECT:=$2}
: ${DAYS:=3650}
[ -f "$name.key" ] || {
# openssl ecparam -name prime256v1 -genkey -noout -out $name.key
openssl genrsa -out $name.key 4096
echo genrsa key
}
[ -f "$name.csr" ] || {
openssl req -new -key $name.key -out $name.csr -subj "/CN=$name$SUBJECT"
echo create csr
}
[ -f "$name.crt" ] || {
openssl x509 -req -in $name.csr -CA k3s/client-ca.crt -CAkey k3s/client-ca.key -CAcreateserial -out $name.crt -days $DAYS
echo create cert
}
cluster=$(kubectl config view --minify --output 'jsonpath={.clusters[0].name}')
namespace=$(kubectl config view --minify --output 'jsonpath={..namespace}')
server=$(kubectl config view --minify --output 'jsonpath={.clusters[0].cluster.server}')
: ${CONTEXT:=$cluster-$name}
KUBECTL="kubectl --kubeconfig=$name.yaml"
$KUBECTL config set-cluster $cluster --embed-certs --server=$server --certificate-authority=k3s/server-ca.crt
$KUBECTL config set-credentials $name --embed-certs --client-certificate=$name.crt --client-key=$name.key
$KUBECTL config set-context $CONTEXT --cluster=$cluster --namespace=$namespace --user=$name
$KUBECTL config set current-context $CONTEXT
$KUBECTL version
./k3s-new-cert john
$ tree .
.
├── john.crt
├── john.csr
├── john.key
├── john.yaml
├── k3s
│ ├── client-ca.crt
│ ├── client-ca.key
│ ├── server-ca.crt
│ └── server-ca.key
└── k3s-new-cert.sh
@ruby232
Copy link

ruby232 commented Aug 8, 2020

The files k3s/server-ca.crt where are they?

@wenerme
Copy link
Author

wenerme commented Aug 8, 2020

Pulled from /var/lib/rancher/k3s/server/tls/

@retoo
Copy link

retoo commented Jan 25, 2024

thanks for the script.

two notes

  • to generate admins I had to use this snippet

      openssl req -new -key $name.key -out $name.csr -subj "/CN=$name/O=system:masters"
    
  • OR, manually add users to the clusterrolebinding

    openssl req -new -key $name.key -out $name.csr -subj "/CN=$name"
    

    and then edit kubectl edit clusterrolebinding cluster-admin

    [...]
    subjects:
    - apiGroup: rbac.authorization.k8s.io
      kind: Group
      name: system:masters
    - apiGroup: rbac.authorization.k8s.io
      kind: User
      name: john.doe
    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment