Skip to content

Instantly share code, notes, and snippets.

@Grigore147
Created July 25, 2025 22:07
Show Gist options
  • Save Grigore147/941e3d41f85fda97a5b3986f81bfd26d to your computer and use it in GitHub Desktop.
Save Grigore147/941e3d41f85fda97a5b3986f81bfd26d to your computer and use it in GitHub Desktop.

Revisions

  1. Grigore147 created this gist Jul 25, 2025.
    50 changes: 50 additions & 0 deletions k8s-client-certificate.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    #!/bin/bash

    USER='grigore'

    openssl genrsa -out ${USER}.key 2048
    openssl req -new -key ${USER}.key -out ${USER}.csr -subj "/CN=${USER}"

    # Get certificate info:
    # openssl x509 -noout -text -in ./grigore.crt

    # $(cat ${USER}.key | base64 | tr -d "\n")

    cat <<EOF > ${USER}.csr.yaml
    apiVersion: certificates.k8s.io/v1
    kind: CertificateSigningRequest
    metadata:
    name: ${USER}
    spec:
    request: $(cat ${USER}.key | base64)
    signerName: kubernetes.io/kube-apiserver-client
    expirationSeconds: 86400 # one day
    usages:
    - client auth
    EOF

    # cat ${USER}.csr.yaml
    # cat ${USER}.csr.yaml | yq -e .spec.request | base64 -D

    # Create CSR:
    # kubectl create -f ${USER}.csr.yaml

    # Get the list of CSRs:
    # kubectl get csr

    # Approve the CSR:
    # kubectl certificate approve ${USER}

    # Export the issued certificate from the CertificateSigningRequest.
    # kubectl get csr ${USER} -o jsonpath='{.status.certificate}'| base64 -d > ${USER}.crt


    # Add to kubeconfig
    # First, you need to add new credentials:
    # kubectl config set-credentials ${USER} --client-key=${USER}.key --client-certificate=${USER}.crt --embed-certs=true

    # Then, you need to add the context:
    # kubectl config set-context ${USER} --cluster=kubernetes --user=${USER}

    # To test it, change the context to ${USER}:
    # kubectl config use-context ${USER}