- 创建证书文件并配置
#创建对应目录
mkdir /data/devops/kube-read -p
cd /data/devops/kube-read
cp /etc/kubernetes/ssl/ca* .
#创建证书文件
root@172-16-160-221:/data/devops/kube-read# cat ca-config.json
{
"signing": {
"default": {
"expiry": "4320h"
},
"profiles": {
"kubernetes": {
"usages": [
"signing",
"key encipherment",
"server auth",
"client auth"
],
"expiry": "4320h"
}
}
}
}
#创建证书签名请求文件
root@172-16-160-221:/data/devops/kube-read# cat read-csr.json
{
"CN": "readuser",
"hosts": [],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"ST": "QingDao",
"L": "QingDao",
"O": "k8s",
"OU": "System"
}
]
}
# 执行签发证书
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes read-csr.json | cfssljson -bare readuser
# 会生成以下文件
readuser.csr # 签名请求
readuser-key.pem # 私钥
readuser.pem #证书
# 校验证书
cfssl-certinfo -cert readuser.pem
- 生成kubeconfig文件
# 172.16.7.132:6443 改成对应的公网apiserver 地址,但是要做ip 限制
kubectl config set-cluster kubernetes \--certificate-authority=ca.pem \--embed-certs=true \--server=https://172.16.7.132:6443 \--kubeconfig=readuser.config
# 设置客户端认证参数
kubectl config set-credentials readuser \--client-certificate=readuser.pem \--client-key=readuser-key.pem \--embed-certs=true \--kubeconfig=readuser.config
# 设置上下文参数
kubectl config set-context kubernetes \--cluster=kubernetes \--user=readuser \--kubeconfig=readuser.config
# 设置默认上下文
kubectl config use-context kubernetes --kubeconfig=readuser.config
# read-crb.yaml
root@172-16-160-221:/data/devops/kube-read# cat read-crb.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: readuser
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: view
subjects:
- apiGroup: rbac.authorization.k8s.io
kind: User
name: readuser
# 验证
kubectl get pods --kubeconfig=readuser.config -n kube-system
- 增加 exec pod 权限
# 创建一个附加的 ClusterRole
root@172-16-160-221:/data/devops/kube-read# cat pod-exec-role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: pod-exec
rules:
- apiGroups: [""] # 核心 API 组
resources: ["pods/exec"] # 子资源 exec
verbs: ["create"] # exec 操作需要 create 权限
# 将权限绑定到用户
# kubectl apply -f pod-exec-role.yaml
root@172-16-160-221:/data/devops/kube-read# cat pod-exec-binding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: pod-exec-binding
subjects:
- kind: User
name: readuser # kubeconfig 中的用户名称
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: pod-exec
apiGroup: rbac.authorization.k8s.io
# kubectl apply -f pod-exec-binding.yaml
#验证权限
root@172-16-160-221:/data/devops/kube-read# kubectl --kubeconfig=readuser.config exec -it -n single-doc key-opinion-llm-data-56f55d8ff6-twqln bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
root@key-opinion-llm-data-56f55d8ff6-twqln:/app/lingo-engine#
标签:exec,--,只读,kubeconfig,read,readuser,k8s,config
From: https://www.cnblogs.com/lixinliang/p/18642767