Created
          July 25, 2025 22:07 
        
      - 
      
- 
        Save Grigore147/941e3d41f85fda97a5b3986f81bfd26d to your computer and use it in GitHub Desktop. 
    Example script to create a K8s client certificate using OpenSSL for K8s API access.
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | #!/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} | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment