Kubernetes自定义权限
1 创建账号
1.1 创建私钥,一定要用 root 用户
(umask 077; openssl genrsa -out test.key 2048)

1.2 基于私钥生成证书,由 k8s 集群的 ca.crt 签署
CN 为账号名称,OU 为组
openssl req -new -key test.key -out test.csr -subj "/CN=test"

ca.crt 与 ca.key 是 k8s 的秘钥
openssl x509 -req -in test.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out test.crt -days 365
1.3 查看证书
openssl x509 -in test.csr -text -noout
1.4 k8s 创建用户,并使用证书认证
kubectl config set-credentials test --client-certificate=test.crt --client-key=test.key --embed-certs=true
1.5 查看集群
kubectl config get-contexts

1.6 设置上下文,用户访问哪个集群
kubectl config set-context test@kubernetes --cluster=kubernetes --user=test
1.7 查看配置
kubectl config view

2 配置权限
2.1 使用系统角色
—clusterrole=view 是系统只读权限
kubectl create clusterrolebinding test-rolebinding --clusterrole=view --user=test
2.2 自定义角色
2.2.1 创建 role
kubectl create clusterrole test-clusterrole --verb=get,list,watch --resource=pods,deploy,svc --dry-run=client -o yaml > test/clusterrole.yaml
编辑 test/clusterrole.yaml
apiVersion: rbac.authorization.k8s.io/v1kind: ClusterRolemetadata: name: rongxin-cluster-rolerules:- apiGroups: - "" resources: - pods - services - pods/log verbs: - get - list - watch- apiGroups: - "" resources: - pods/exec verbs: - create- apiGroups: - apps resources: - deployments verbs: - get - list - watchkubectl apply -f test/clusterrole.yaml
2.2.2 查看 role
kubectl describe clusterrole test-cluster-role

2.2.3 创建 rolebinding
我习惯备份下,也可以参考上面命令直接运行
kubectl create rolebinding test-dev-rolebinding --clusterrole=test-cluster-role --user=test --dry-run=client -o yaml > test/test-dev-rolebinding.yaml
kubectl apply -f test/test-dev-rolebinding.yaml
2.2.4 查看 rolebinding
kubectl get rolebinding -n dev

kubectl describe rolebinding test-dev-rolebinding -n dev

2.3 查看集群
kubectl config get-contexts

3 导出配置
kubectl config set-context test \--cluster=kubernetes \--user=test \--current-context=test \--kubeconfig=test.config
kubectl config set-cluster kubernetes \--certificate-authority=/data/server/certs/ca/k8s/master/ca.pem \ #与上面的ca.crt是同一个文件--embed-certs=true \--server=https://10.1.1.1:7443 \--kubeconfig=test.config
kubectl config set-credentials test \--client-certificate=./test.crt --client-key=test.key --embed-certs=true \--kubeconfig=test.config
vim test.configcontexts:- context: cluster: kubernetes user: test name: test@kubernetescurrent-context: read-ccops # 修改这里,要不然会报 The connection to the server localhost:8080......3.1 测试 kubeconfig
kubectl get pods --kubeconfig=test.config -n kube-systemNAME READY STATUS RESTARTS AGEcsi-rbdplugin-5vfrd 3/3 Running 0 79mkubectl delete pods --kubeconfig=test.config -n kube-system csi-rbdplugin-5vfrdError from server (Forbidden): pods "csi-rbdplugin-5vfrd" is forbidden: User "test" cannot delete resource "pods" in API group "" in the namespace "kube-system"文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!