K8S创建用户账号User Account并赋予权限
【代码】K8S创建用户账号User Account并赋予权限。
·
拷贝根证书
其中ca.pem和ca-key.pem是创建K8S集群证书的时候生成的,命令为:
cfssl gencert -initca ca-csr.json | cfssljson -bare ca -
上图为ca-csr.json的内容
[root@k8s-master1 useradd_test]# cat ca-config.json
{
"signing": {
"default": {
"expiry": "87600h"
},
"profiles": {
"kubernetes": {
"expiry": "87600h",
"usages": [
"signing",
"key encipherment",
"server auth",
"client auth"
]
}
}
}
}
安装cfssl并生成新增用户的证书
wget https://pkg.cfssl.org/R1.2/cfssl_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssljson_linux-amd64
wget https://pkg.cfssl.org/R1.2/cfssl-certinfo_linux-amd64
chmod +x *
mv * /usr/local/bin
创建普通用户json文件
cat > byhzg.json <<EOF
{
"CN": "byhzg",
"hosts": [],
"key": {
"algo": "rsa",
"size": 2048
},
"names": [
{
"C": "CN",
"ST": "BeiJing",
"L": "BeiJing",
"O": "k8s",
"OU": "System"
}
]
}
EOF
生成证书
cfssl gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=kubernetes byhzg.json | cfssljson -bare devuser
创建配置文件
集群配置
kubectl config set-cluster k8s \
--server=https://192.168.113.21:6443 \
--certificate-authority=ca.pem \
--embed-certs=true \
--kubeconfig=/root/devuser.conf
用户配置
kubectl config set-credentials byhzg \
--client-certificate=byhzg.pem \
--client-key=byhzg-key.pem \
--embed-certs=true \
--kubeconfig=/root/devuser.conf
设置上下文参数
kubectl config set-context byhzg@k8s \
--cluster=k8s \
--user=byhzg \
--kubeconfig=/root/devuser.conf
切换context
kubectl config use-context byhzg@k8s --kubeconfig=/root/devuser.conf
kubectl config view --kubeconfig=/root/devuser.conf
创建系统用户
useradd byhzg
mkdir -p /home/byhzg/.kube
cp /root/devuser.conf /home/byhzg/.kube/config
chown byhzg.byhzg -R /home/byhzg/
su - byhzg
新增角色并帮定用户
[root@k8s-master1 useradd_test]# cat cluster-reader.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: cluster-reader
rules:
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- list
- watch
[root@k8s-master1 useradd_test]# cat byhzg-read-all-pod.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: billy-read-all-pods
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-reader
subjects:
- apiGroup: rbac.authorization.k8s.io
kind: User
name: byhzg
验证功能
[root@k8s-master1 useradd_test]# su - byhzg
上一次登录:一 6月 12 23:15:46 CST 2023pts/0 上
[byhzg@k8s-master1 ~]$ kubectl get po -n kube-system
NAME READY STATUS RESTARTS AGE
calico-kube-controllers-8db96c76-9wzd7 1/1 Running 0 32d
calico-node-bwgkl 1/1 Running 0 32d
calico-node-f7r54 1/1 Running 0 32d
calico-node-v8vws 1/1 Running 0 32d
coredns-77fcb55c6d-2pr2k 1/1 Running 0 32d
coredns-77fcb55c6d-hrczn 1/1 Running 0 32d
如果没有成功,则报错为:
[byhzg@k8s-master1 ~]$ kubectl get po -n kube-system
Error from server (Forbidden): pods is forbidden: User "byhzg" cannot list resource "pods" in API group "" in the namespace "kube-system"
更多推荐
已为社区贡献10条内容
所有评论(0)