genrate certifact for k8s
Jump to turn (13)
- User
genrate certifact for k8s
- Assistant
genrate certifact for k8s
Creating a certificate for Kubernetes typically involves generating TLS certificates for securing the cluster components (API server, etcd, kubelet, etc.) or client certificates for authentication.
Here’s a basic example of how to generate a certificate and key pair using OpenSSL, which you can then use in Kubernetes:
k8s.cnf)This helps specify certificate details like Common Name (CN) and Subject Alternative Names (SANs).
[ req ]
default_bits = 2048
prompt = no
default_md = sha256
req_extensions = req_ext
distinguished_name = dn
[ dn ]
CN = kube-apiserver
[ req_ext ]
subjectAltName = @alt_names
[ alt_names ]
DNS.1 = kubernetes
DNS.2 = kubernetes.default
DNS.3 = kubernetes.default.svc
DNS.4 = kubernetes.default.svc.cluster.local
IP.1 = 10.96.0.1 # Cluster IP for kubernetes service
Adjust values to fit your cluster setup (especially the IP addresses and DNS names).
openssl genrsa -out kube-apiserver.key 2048
openssl req -new -key kube-apiserver.key -out kube-apiserver.csr -config k8s.cnf
Assuming you have a CA key (ca.key) and CA cert (ca.crt):
openssl x509 -req -in kube-apiserver.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
-out kube-apiserver.crt -days 365 -extensions req_ext -extfile k8s.cnf
cfssl tool (Recommended by Kubernetes)Kubernetes' docs often recommend using cfssl for generating certs.
Example CSR JSON (kube-apiserver-csr.json):
{
"CN": "kube-apiserver",
"hosts": [
"127.0.0.1",
"10.96.0.1",
"kubernetes",
"kubernetes.default",
"kubernetes.default.svc",
"kubernetes.default.svc.cluster.local"
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "US",
"L": "San Francisco",
"O": "Kubernetes",
"OU": "Kubernetes The Hard Way",
"ST": "California"
}
]
}
Generate cert:
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes kube-apiserver-csr.json | cfssljson -bare kube-apiserver
If you want me to generate a specific certificate for a particular Kubernetes component or user with exact details, please provide more info (component name, IPs/DNS, CN, usages).
anther whey
Certainly! Another way to generate Kubernetes certificates is by using kubeadm itself, which simplifies the process of creating certificates required for Kubernetes components.
kubeadmIf you have kubeadm installed, it can generate all the required certificates for you.
You can generate the certificates without fully initializing the cluster by running:
kubeadm init phase certs all
This command generates a full set of Kubernetes certificates in /etc/kubernetes/pki/.
You can list the certificates like this:
ls /etc/kubernetes/pki
Typical certs generated:
ca.crt, ca.key (Certificate Authority)apiserver.crt, apiserver.keyapiserver-kubelet-client.crt, apiserver-kubelet-client.keyfront-proxy-ca.crt, front-proxy-ca.keyfront-proxy-client.crt, front-proxy-client.keyetcd/ca.crt, etcd/ca.key, etcd/server.crt, etcd/server.key (if running etcd)If you want to generate an individual certificate, for example for the API Server, you can run:
kubeadm init phase certs apiserver
Or for the kubelet client cert:
kubeadm init phase certs apiserver-kubelet-client
kubeadm automatically handles generating certificates with proper SANs and correct usages./etc/kubernetes/pki/ directory.openssl to create a Self-Signed Certificate Quickly (for development or testing)You can create a self-signed certificate quickly using just one command:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout tls.key -out tls.crt \
-subj "/CN=kubernetes/O=kubernetes"
This generates:
tls.key — Private keytls.crt — Public self-signed certificateNote: This is insecure for production but handy for demo/testing scenarios.
If you want me to provide scripts or commands tailored to your exact use case, just let me know!
anther whey
Sure! Another way to generate Kubernetes certificates is by using cfssl or mkcert, or by leveraging easy bash scripts provided by some Kubernetes tutorials. Here's one more approach using cfssl that’s quick and customizable:
cfsslcfssl is a powerful toolkit from Cloudflare to manage TLS certificates.
cfssl tools if not installed# For Linux
curl -s -L -o /usr/local/bin/cfssl https://pkg.cfssl.org/R1.2/cfssl_linux-amd64
curl -s -L -o /usr/local/bin/cfssljson https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64
chmod +x /usr/local/bin/cfssl /usr/local/bin/cfssljson
ca-config.json){
"signing": {
"default": {
"expiry": "8760h"
},
"profiles": {
"kubernetes": {
"expiry": "8760h",
"usages": [
"signing",
"key encipherment",
"server auth",
"client auth"
]
}
}
}
}
ca-csr.json){
"CN": "Kubernetes",
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "US",
"L": "San Francisco",
"O": "Kubernetes",
"OU": "CA",
"ST": "California"
}
]
}
cfssl gencert -initca ca-csr.json | cfssljson -bare ca
This produces: ca.pem (cert) and ca-key.pem (private key)
anther whey
Certainly! Here's another way to generate Kubernetes certificates using openssl with a simple one-liner for a self-signed certificate, or by using easy-rsa, a toolset originally designed for managing a Public Key Infrastructure (PKI) and widely used in the VPN community but also perfectly valid for Kubernetes TLS certs.
easy-rsaeasy-rsa is a CLI utility to build and manage a CA and generate certs easily.
easy-rsaOn a Debian/Ubuntu system:
sudo apt-get update
sudo apt-get install easy-rsa
Alternatively, download it from its GitHub repo:
git clone https://github.com/OpenVPN/easy-rsa.git
cd easy-rsa/easyrsa3
./easyrsa init-pki
./easyrsa build-ca nopass
You will be prompted for the CA details (Common Name etc). You can use defaults or customize.
./easyrsa gen-req kube-apiserver nopass
This creates:
pki/private/kube-apiserver.key (private key)pki/reqs/kube-apiserver.req (CSR)./easyrsa sign-req server kube-apiserver
You will be prompted to confirm signing; this command outputs signed cert:
pki/issued/kube-apiserver.crtopenssl x509 -in pki/issued/kube-apiserver.crt -text -noout
"server" to "client" in signing step.pki/ inside the easy-rsa directory.For simple testing or dev use (NOT recommended for production), you can create a self-signed cert with SAN using:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout kube-apiserver.key -out kube-apiserver.crt \
-subj "/CN=kube-apiserver" \
-addext "subjectAltName = DNS:kubernetes,DNS:kubernetes.default,DNS:kubernetes.default.svc,DNS:kubernetes.default.svc.cluster.local,IP:10.96.0.1"
If you want me to help generate scripts or set up other cert types, please specify!
anther whey
Certainly! Here's yet another way to generate certificates for Kubernetes, this time using step CLI tool (Smallstep Certificate Manager).
stepstep is a user-friendly CLI for managing a private CA and certificates. It's simple to use and can be a great alternative.
stepbrew install step
curl -sfL https://raw.githubusercontent.com/smallstep/cli/master/install.sh | sh
step ca init --name "Kubernetes Root CA" --dns "kubernetes" --address ":443"
This creates a CA with keys and certs saved locally.
step ca certificate "kube-apiserver" kube-apiserver.crt kube-apiserver.key \
--san kubernetes \
--san kubernetes.default \
--san kubernetes.default.svc \
--san kubernetes.default.svc.cluster.local \
--san 10.96.0.1 \
--san 127.0.0.1
This command generates a signed cert and key with all the required subject alternative names (SANs) for the API server.
You can inspect certificates with:
step certificate inspect kube-apiserver.crt
step?step ca initstep ca certificate command.crt and .key files in your Kubernetes manifests or configIf you want a step-by-step example for your exact Kubernetes setup or other components, just ask!
in production
For production-grade Kubernetes certificates, the strategy must ensure strong security, proper identity, and automated certificate lifecycle management. Here are recommended approaches for generating and managing Kubernetes certificates in production:
kubeadm for Certificate Generation and RenewalWhy? It’s Kubernetes’ officially supported tool for bootstrapping clusters, including generating all component certs properly with correct SANs and usages.
How? When bootstrapping:
kubeadm init
This securely generates CA certs, API server certs, etc. kubeadm also includes commands to renew certs before expiration:
kubeadm certs renew all
Tips:
/etc/kubernetes/pki directory.Why? cert-manager is a Kubernetes-native certificate management controller that automates obtaining, renewing, and using TLS certificates from various issuers (including internal CAs, Let’s Encrypt, HashiCorp Vault).
How?
cert-manager to your cluster.Certificate and Issuer or ClusterIssuer resources.cert-manager handles cert issuance & renewal transparently.Use Cases:
Learn more: https://cert-manager.io/
Why? Enterprises often offload cert lifecycle management to a central PKI system like HashiCorp Vault, Venafi, or cloud KMS.
crate new user
Creating a new user in Kubernetes usually involves creating a new client certificate for that user and then configuring a kubeconfig file so the user can authenticate to the cluster.
Since Kubernetes does not have a built-in user management system, users are typically represented by X.509 client certificates or tokens (e.g., service accounts).
/etc/kubernetes/pki/ca.crt and /etc/kubernetes/pki/ca.keyopenssl installed on your machine.Replace username with your desired username.
openssl genrsa -out username.key 2048
Create a CSR config file username-csr.conf with SAN and subject info:
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
prompt = no
[req_distinguished_name]
CN = username
O = groupname
[v3_req]
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth
username with the user name.groupname with the Kubernetes group this user belongs to (e.g., developers, admins).Generate CSR:
openssl req -new -key username.key -out username.csr -config username-csr.conf
openssl x509 -req -in username.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial \
-out username.crt -days 365 -extensions v3_req -extfile username-csr.conf
anther whey
Certainly! Another way to create and manage users in Kubernetes, especially for production or more automated environments, is to use ServiceAccounts or OpenID Connect (OIDC) authentication instead of manually creating client certificates. Here are some alternative methods:
kubectl create serviceaccount myuser --namespace mynamespace
kubectl create rolebinding myuser-view-binding \
--clusterrole=view \
--serviceaccount=mynamespace:myuser \
--namespace=mynamespace
SECRET_NAME=$(kubectl get serviceaccount myuser -n mynamespace -o jsonpath='{.secrets[0].name}')
kubectl get secret $SECRET_NAME -n mynamespace -o jsonpath='{.data.token}' | base64 --decode
--oidc-issuer-url=https://accounts.google.com
--oidc-client-id=<client-id>
--oidc-username-claim=email
--oidc-groups-claim=groups
Users authenticate with your identity provider (IdP).
anther whey
Certainly! Here's another way to create a new Kubernetes user using certificate signing request (CSR) resources within Kubernetes itself, leveraging the Kubernetes CA to approve and issue client certificates. This method uses the Kubernetes CertificateSigningRequest API, allowing the cluster to manage CSR approvals and certificate issuance instead of signing certs outside the cluster manually.
openssl genrsa -out username.key 2048
openssl req -new -key username.key -out username.csr -subj "/CN=username/O=groupname" \
-config <(cat <<EOF
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
CN = username
O = groupname
EOF
)
CSR_BASE64=$(cat username.csr | base64 | tr -d '\n')
username-csr.yaml)apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
name: username
spec:
request: ${CSR_BASE64}
signerName: kubernetes.io/kube-apiserver-client
usages:
- client auth
Replace ${CSR_BASE64} with the base64 content from above.
kubectl apply -f username-csr.yaml
kubectl certificate approve username
RBAC
Certainly! Here’s a detailed explanation and example of how to use RBAC (Role-Based Access Control) in Kubernetes to control permissions of users, including how to create Roles, ClusterRoles, RoleBindings, and ClusterRoleBindings.
RBAC is a method to regulate access by defining who can do what within the Kubernetes cluster.
| Resource | Scope | Purpose |
|---|---|---|
| Role | Namespace | Defines permissions within one namespace |
| ClusterRole | Cluster | Defines permissions cluster-wide |
| RoleBinding | Namespace | Grants Role permissions to users/groups in a namespace |
| ClusterRoleBinding | Cluster | Grants ClusterRole permissions cluster-wide |
default namespaceapiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
This Role lets you get, list, and watch pods in the default namespace.
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: read-pods
namespace: default
subjects:
- kind: User
name: alice # Name of the user to bind
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role # Refers to the Role created above
name: pod-reader
apiGroup: rbac.authorization.k8s.io
ssl+rbac
Certainly! Combining TLS client certificate authentication (SSL certs) with RBAC is a common and secure way to manage user access in Kubernetes.
(Authenticate users via TLS client certs signed by your Kubernetes CA)
Example for user alice:
aliceopenssl genrsa -out alice.key 2048
Create CSR config alice-csr.conf:
[ req ]
req_extensions = v3_req
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
CN = alice
O = dev-team
[v3_req]
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth
Generate CSR:
openssl req -new -key alice.key -out alice.csr -config alice-csr.conf
openssl x509 -req -in alice.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial \
-out alice.crt -days 365 -extensions v3_req -extfile alice-csr.conf
alicekubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/pki/ca.crt \
--server=https://<API_SERVER_ADDRESS>:6443 \
--kubeconfig=alice.kubeconfig
kubectl config set-credentials alice \
--client-certificate=alice.crt \
--client-key=alice.key \
--kubeconfig=alice.kubeconfig
kubectl config set-context alice-context \
--cluster=kubernetes \
--user=alice \
--kubeconfig=alice.kubeconfig
kubectl config use-context alice-context --kubeconfig=alice.kubeconfig
Generate User Client Certificate
with cert manger
Certainly! To generate and manage client certificates for Kubernetes users with cert-manager, you can leverage cert-manager's Certificate and Issuer resources to automate certificate issuance, including for user/client certificates. Here's how you can do it step-by-step.
kubectl configured to access your clusterkubectl apply -f https://github.com/cert-manager/cert-manager/releases/latest/download/cert-manager.yaml
Wait till cert-manager pods are running:
kubectl get pods -n cert-manager
If you already have a CA signed cert and key, create a secret containing your CA:
kubectl create secret tls ca-key-pair --cert=ca.crt --key=ca.key -n cert-manager
Create a ClusterIssuer referencing that CA:
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: my-ca-issuer
spec:
ca:
secretName: ca-key-pair
Apply:
kubectl apply -f cluster-issuer.yaml
Create a YAML file for your user certificate, e.g., alice-cert.yaml:
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: alice-client-cert
namespace: default
spec:
secretName: alice-client-tls
duration: 8760h # 1 year
renewBefore: 720h # 30 days before expiry
privateKey:
algorithm: RSA
size: 2048
isCA: false
commonName: alice
usages:
- client auth
issuerRef:
name: my-ca-issuer
kind: ClusterIssuer
the same with open ssl
Certainly! Here's how to generate a Kubernetes user client certificate with OpenSSL, then create the kubeconfig and bind RBAC permissions.
/etc/kubernetes/pki/ca.crt and /etc/kubernetes/pki/ca.key)openssl installed on your machineReplace username with your user’s name, e.g., alice.
openssl genrsa -out username.key 2048
Create CSR config file username-csr.conf:
[ req ]
default_bits = 2048
prompt = no
default_md = sha256
distinguished_name = dn
req_extensions = usr_cert
[ dn ]
CN = username
O = groupname
[ usr_cert ]
extendedKeyUsage = clientAuth
CN = the usernameO = the group the user belongs to, e.g., devs, admins (optional)extendedKeyUsage = clientAuth for user certsGenerate the CSR:
openssl req -new -key username.key -out username.csr -config username-csr.conf
openssl x509 -req -in username.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key \
-CAcreateserial -out username.crt -days 365 -extensions usr_cert -extfile username-csr.conf
Example kubeconfig creation commands (<API_SERVER> is your Kubernetes API server URL, e.g., https://10.0.0.1:6443):
Not yet included in a published release.
apiserver-csr.json){
"CN": "kube-apiserver",
"hosts": [
"127.0.0.1",
"10.96.0.1", # Kubernetes default service IP
"kubernetes",
"kubernetes.default",
"kubernetes.default.svc",
"kubernetes.default.svc.cluster.local"
],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "US",
"L": "San Francisco",
"O": "Kubernetes",
"OU": "System",
"ST": "California"
}
]
}
Customize the hosts and names as per your environment.
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes apiserver-csr.json | cfssljson -bare apiserver
This generates:
apiserver.pem — The signed certificateapiserver-key.pem — The private keyThese certs can be referenced in Kubernetes manifests or kubeconfig files for secure communication.
cfssl is flexible and scriptableIf you need, I can generate sample files or scripts for other Kubernetes components (kubelet, etcd, client certs) too!
Let me know if you want a specific example.
How? Vault’s PKI secrets engine issues intermediate certs with fine-grained policies for Kubernetes components.
Benefits:
Example workflow:
cfssl or step but Integrate with Automation & Secure CAcfssl or Smallstep step as part of scripted or CI/CD pipelines.| Area | Recommendations |
|---|---|
| CA Security | Use offline or hardware-backed CA for root private keys |
| Certificate Usage | Use proper Extended Key Usages (EKUs) and SANs matching Kubernetes's expectations |
| Validity Period | Use short-lived certificates (e.g., 1 year or less) and automate renewal |
| Key Algorithm | Use RSA 2048+ or ECDSA P-256 or better |
| Automation | Automate certificate rollout using kubeadm, cert-manager or Vault |
| Backup & Audit | Backup keys/certs securely and audit certificate issuance & usage |
| Method | Pros | Cons | Use Case |
|---|---|---|---|
kubeadm | Native tool, built-in automation | Limited flexibility | Bootstrapping Kubernetes clusters |
cert-manager | Kubernetes-native, automatic renewals | Adds dependency & complexity | Managing app or ingress TLS certs |
| Vault PKI | Enterprise-grade, secure, dynamic | Operational overhead | Large/complex environments |
cfssl or step | Scriptable, customizable | Needs integration & automation | Custom CA setups, pipelines |
If you want, I can help you create a production-ready certificate pipeline or a best-practice configuration for your cluster!
kubeadm in Production# Initialize control plane with kubeadm, generating all certs properly
kubeadm init --config kubeadm-config.yaml
# Example kubeadm config snippet specifying SANs for API server cert:
apiVersion: kubeadm.k8s.io/v1beta3
kind: ClusterConfiguration
apiServer:
certSANs:
- "10.96.0.1"
- "kubernetes"
- "kubernetes.default"
- "kubernetes.default.svc"
- "kubernetes.default.svc.cluster.local"
Let me know if you'd like a walkthrough for any of these production-grade methods!
Use the following template to create a kubeconfig for username. Replace variables accordingly.
kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/pki/ca.crt \
--server=https://<API_SERVER_ADDRESS>:6443 \
--kubeconfig=username.kubeconfig
kubectl config set-credentials username \
--client-certificate=username.crt \
--client-key=username.key \
--kubeconfig=username.kubeconfig
kubectl config set-context username-context \
--cluster=kubernetes \
--user=username \
--kubeconfig=username.kubeconfig
kubectl config use-context username-context --kubeconfig=username.kubeconfig
Now the file username.kubeconfig can be provided to the user to access the cluster.
For example, to bind cluster-admin role to the new user (use carefully, only for trusted users):
kubectl create clusterrolebinding username-cluster-admin-binding \
--clusterrole=cluster-admin \
--user=username
Or for namespace-specific access:
kubectl create rolebinding username-read-binding \
--clusterrole=view \
--user=username \
--namespace=default
If you want, I can generate example commands or files with specific user names or groups — just ask!
Use RBAC with OIDC user/group claims to authorize users inside the cluster.
kubectl with Token Authentication (ServiceAccount Tokens or External Tokens)You can distribute bearer tokens issued by your auth system or service accounts to users and set kubeconfig contexts using tokens instead of certificates.
Example setting kubeconfig user with a token:
kubectl config set-credentials username --token=<token> --kubeconfig=username.kubeconfig
kube-aws-iam-authenticator or External Authentication Shim| Approach | Use Case | Pros | Cons |
|---|---|---|---|
| Client Certificates (Your original way) | Highly secure user auth | Strong TLS auth, native Kubernetes | Cert management overhead |
| ServiceAccounts | Applications/pods access | Easy, automated, no certs | Limited to in-cluster usage |
| OIDC / External IdP | Human user auth | Centralized identity, scalable | Requires IdP setup and config |
| Token-based auth | Short-lived tokens | Simple, quick | Token lifecycle management |
| IAM Authenticator / Cloud IAM | Cloud infrastructure users | Integrates with cloud user management | Cloud specific, requires setup |
If you'd like, I can generate example configurations for any of these alternative ways! Just let me know what you prefer.
kubectl get csr username -o jsonpath='{.status.certificate}' | base64 -d > username.crt
Use the following kubectl commands or create the kubeconfig manually:
kubectl config set-cluster kubernetes \
--server=https://<API_SERVER> \
--certificate-authority=/etc/kubernetes/pki/ca.crt \
--kubeconfig=username.kubeconfig
kubectl config set-credentials username \
--client-certificate=username.crt \
--client-key=username.key \
--kubeconfig=username.kubeconfig
kubectl config set-context username-context \
--cluster=kubernetes \
--user=username \
--kubeconfig=username.kubeconfig
kubectl config use-context username-context --kubeconfig=username.kubeconfig
Create RoleBindings or ClusterRoleBindings for user username to grant access rights.
If you'd like, I can provide a ready-to-use script or YAML templates for this flow!
This binding assigns the pod-reader Role to user alice in the default namespace.
kubectl create clusterrolebinding alice-cluster-admin --clusterrole=cluster-admin --user=alice
Or as YAML:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: alice-cluster-admin
subjects:
- kind: User
name: alice
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: cluster-admin
apiGroup: rbac.authorization.k8s.io
| apiGroups | resources | verbs |
|---|---|---|
"" (core) | pods, services, endpoints, configmaps, secrets, nodes, namespaces, etc. | get, list, watch, create, update, patch, delete, deletecollection |
rbac.authorization.k8s.io | roles, rolebindings, clusterroles, clusterrolebindings | same verbs as above |
apps | deployments, daemonsets, replicasets, statefulsets | same verbs |
Use:
kubectl auth can-i <verb> <resource> --as=<user> --namespace=<namespace>
Example:
kubectl auth can-i create pods --as=alice --namespace=default
If you want, I can generate a complete example including user creation, RBAC binding, and kubeconfig setup! Just let me know.
alicealice to list and get pods in namespace devRole:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: dev
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list"]
RoleBinding:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
namespace: dev
name: alice-pod-reader-binding
subjects:
- kind: User
name: alice # This must match CN in the cert
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
aliceUse alice.kubeconfig with kubectl:
kubectl --kubeconfig=alice.kubeconfig get pods -n dev
alice).--client-ca-file=/etc/kubernetes/pki/ca.crt set to trust your CA.| Step | Description |
|---|---|
| Generate client cert | User’s X.509 certificate and key |
| Configure kubeconfig | Client cert/key + cluster info |
| Setup RBAC (Role,Binding) | Map user CN to allowed actions |
| kube-apiserver config | Trust user CA with --client-ca-file |
If you'd like, I can prepare a full step-by-step script or template you can run to create users secured with SSL certs and RBAC permissions! Just ask!
commonName: alice sets the user name recognized by Kubernetes API serverusages: client auth indicates this cert is for client authenticationkubectl apply -f alice-cert.yaml
cert-manager stores cert and key into the secret alice-client-tls in the same namespace.
Get the key and cert files:
kubectl get secret alice-client-tls -o jsonpath='{.data.tls\.key}' | base64 -d > alice.key
kubectl get secret alice-client-tls -o jsonpath='{.data.tls\.crt}' | base64 -d > alice.crt
alice with issued certificateYou can create a kubeconfig referencing these client cert files and the cluster CA cert.
Example command (replace <API_SERVER> and path to CA cert):
kubectl config set-cluster kubernetes \
--server=https://<API_SERVER>:6443 \
--certificate-authority=/path/to/ca.crt \
--kubeconfig=alice.kubeconfig
kubectl config set-credentials alice \
--client-certificate=alice.crt \
--client-key=alice.key \
--kubeconfig=alice.kubeconfig
kubectl config set-context alice-context \
--cluster=kubernetes \
--user=alice \
--kubeconfig=alice.kubeconfig
kubectl config use-context alice-context --kubeconfig=alice.kubeconfig
Example rolebinding granting view access in the default namespace to user alice:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: alice-view
namespace: default
subjects:
- kind: User
name: alice # must match cert CN
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: view
apiGroup: rbac.authorization.k8s.io
Apply with:
kubectl apply -f alice-rolebinding.yaml
| Step | Description |
|---|---|
| Install cert-manager | Cluster cert manager to automate certs |
| Setup CA issuer | Use your own CA or create new one |
| Create Certificate resource | Defines new user cert with CN and usage |
| Retrieve cert/key from secret | Extract client TLS certificate & key |
| Generate user kubeconfig | Use certs for client auth |
| Configure RBAC | Grant user permissions via RoleBinding |
If you want, I can generate all YAML manifests and helper scripts for this workflow customized for your environment!
kubectl config set-cluster kubernetes \
--certificate-authority=/etc/kubernetes/pki/ca.crt \
--server=<API_SERVER> \
--kubeconfig=username.kubeconfig
kubectl config set-credentials username \
--client-certificate=username.crt \
--client-key=username.key \
--kubeconfig=username.kubeconfig
kubectl config set-context username-context \
--cluster=kubernetes \
--user=username \
--kubeconfig=username.kubeconfig
kubectl config use-context username-context --kubeconfig=username.kubeconfig
For example, allow username view access in namespace default:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: username-view-binding
namespace: default
subjects:
- kind: User
name: username # Must match CN in cert
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: view
apiGroup: rbac.authorization.k8s.io
Apply:
kubectl apply -f rolebinding.yaml
Now use username.kubeconfig to authenticate:
kubectl --kubeconfig=username.kubeconfig get pods -n default
| Step | Command/Action |
|---|---|
| Generate private key | openssl genrsa -out username.key 2048 |
| Create CSR | openssl req -new -key username.key -out username.csr -config username-csr.conf |
| Sign certificate | openssl x509 -req -in username.csr -CA ca.crt -CAkey ca.key ... |
| Create kubeconfig | Use kubectl config set-... commands |
| Bind RBAC role | Create RoleBinding with username as subject |
If you want, I can prepare a shell script that automates all these OpenSSL + kubeconfig + RBAC steps for you!