Kubernetes apiserver 认证 —— X509证书

版本:kube-apiserver:v1.22.9
背景:为用户 myuser 签发认证证书

生成证书

1. 生成RSA私钥

openssl genrsa -out myuser.key 2048

2. 创建证书请求文件(CSR)

openssl req -new -key myuser.key -out myuser.csr

参数说明:

-new 创建新的证书请求文件。
-key file 指定创建证书请求的私钥文件。
-out file 指定输出文件。
CSR,全称为:Certificate Signing Request,证书请求文件的缩写。

3. Base64 CSR

cat myuser.csr | base64 | tr -d "\n"

4. 创建 Kubernetes csr

  1. 配置文件 myuser-csr.yaml
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
 name: myuser
spec:
 request: Base64 csr
 signerName: kubernetes.io/kube-apiserver-client
 expirationSeconds: 86400  # one day
 usages:
 - client auth

  1. 将这个csr交给Kubernetes
kubectl apply -f myuser-csr.yaml
certificatesigningrequest.certificates.k8s.io/myuser created

查看下csr对象, 目前是Pending状态

kubectl get csr
NAME     AGE   SIGNERNAME                            REQUESTOR          REQUESTEDDURATION   CONDITION
myuser   11s   kubernetes.io/kube-apiserver-client   kubernetes-admin   24h                 Pending
  1. Approve Kubernetes csr
kubectl certificate approve myuser
certificatesigningrequest.certificates.k8s.io/myuser approved

approve 后再次查看csr状态为Approved,Issued

NAME     AGE    SIGNERNAME                            REQUESTOR          REQUESTEDDURATION   CONDITION
myuser   100s   kubernetes.io/kube-apiserver-client   kubernetes-admin   24h                 Approved,Issued

5. 提取生成好的证书到 myuser.crt

kubectl get csr myuser -o jsonpath='{.status.certificate}'| base64 -d > myuser.crt

配置证书

kubectl config set-credentials myuser --client-key=myuser.key --client-certificate=myuser.crt --embed-certs=true
User "myuser" set.

配置完成后配置文件会多出一个user。

cat /etc/kubernetes/admin.conf
或者
cat ~/.kube/config
users
- name: myuser
  user:
    client-certificate-data: myuser.crt
    client-key-data: myuser.mey

结果验证

kubectl get pod -A --user=myuser
Error from server (Forbidden): pods is forbidden: User "myuser" cannot list resource "pods" in API group "" at the cluster scope

kubectl get pod -A --user=myuser2
error: auth info "myuser2" does not exist

myuser 认证通过,myuser2认证失败,验证通过。

你可能感兴趣的:(云原生,Kubernetes,kubernetes,云原生,容器)