k8s创建只读用户

一、给只读账户test创建私钥及证书文件

1.生成私钥文件
openssl genrsa -out test.key 2048

2.创建证书部署请求,关键点其中-subj选项中的CN的值将被kubeconfig最为用户名使用
openssl req -new -key test.key -out test.csr -subj "/CN=test"

3.用kubernetes集群生成的CA签署证书,设置有限时间3650天。
openssl x509 -req -in test.csr -CA /etc/kubernetes/ssl/ca.pem -CAkey /etc/kubernetes/ssl/ca-key.pem  -CAcreateserial -out test.crt -days 3650


4.验证证书信息。
openssl x509 -in test.crt  -text -noout

二、创建一个新的集群信息

kubectl config set-cluster mycluster --kubeconfig=/root/scribe/zjy/config --certificate-authority=/etc/kubernetes/ssl/ca.pem --embed-certs=true --server="https://10.35.1.167:6443"



###########说明###########
--kubeconfig="":配置文件存放路径
--certificate-authority="": 设置kuebconfig配置文件中集群选项中的certificate-authority路径。
--embed-certs=false: 设置kuebconfig配置文件中集群选项中的embed-certs开关。
--server="": 设置kuebconfig配置文件中集群选项中的server。

三、配置客户端证书及密钥,用户名信息会通过命令从证书Subject的CN值中⾃动提取,例如之前创建csr时使⽤的“CN=test”.

kubectl config set-credentials test   --embed-certs=true --client-certificate=test.crt --client-key=test.key --kubeconfig=/root/scribe/zjy/config

四、配置context,⽤来组合cluster和credentials,即访问的集群的上下文

kubectl config set-context test@mycluster --cluster=mycluster --user=test --kubeconfig=/root/scribe/zjy/config

五、指定上下文切换到jackhe访问集群,我们能看到现在是没有任何权限的

kubectl config use-context test@mycluster --kubeconfig=/root/scribe/zjy/config

kubectl config view --kubeconfig=/root/scribe/zjy/config

kubectl get pod --kubeconfig=/root/scribe/zjy/config

 

 

 六、接下来我们基于RBAC建立只读ClusterRole文件(权限可配置)

kubectl apply -f readonly.yaml

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cluster-readonly
rules:
- apiGroups: [""]
  #resources: ["namespaces","namespaces/status","pods","pods/exec","pods/log","pods/status","configmaps","services"]
  resources: ["namespaces","namespaces/status","pods","pods/log","pods/status","configmaps","services"]
  verbs: ["get", "watch","create", "list","exec"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: cluster-readonly
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-readonly
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: test

七、创建基于用户jackhe的ClusterRoleBinding文件

 kubectl get pod --kubeconfig=/root/scribe/zjy/config

八、大功告成,接下来我们只要把/root/scribe/zjy/config文件放到用户的家目录.kube下就可以使用了

mkdir -p /home/test/.kube
cp /root/scribe/zjy/config /home/test/.kube/
chown -R test.test /home/test/.kube/

九、让他们随便删除各种测试

  

  

 

posted @ 2022-03-09 09:52  随心朝阳  阅读(396)  评论(0编辑  收藏  举报