给user2用户授权aming命名空间Pod读取权限
1.生成ca证书
bash
cd /etc/kubernetes/pki/
openssl genrsa -out user1.key 2048
openssl req -new -key user1.key -out user1.csr -subj "/CN=user1"
openssl x509 -req -in user1.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out user1.crt -days 3650
2.生成kubeconfig授权文件
bash
# 设置集群
kubectl config set-cluster myk8s \
--certificate-authority=/etc/kubernetes/pki/ca.crt \
--embed-certs=true \
--server=https://192.168.222.101:6443 \ #修改成master节点地址
--kubeconfig=/root/user1.kubecfg
# 查看user1配置,users和context都为空
kubectl config view --kubeconfig=/root/user1.kubecfg
# 设置客户端认证
kubectl config set-credentials user1 \
--client-key=user1.key \
--client-certificate=user1.crt \
--embed-certs=true \
--kubeconfig=/root/user1.kubecfg
# 查看user1配置,users有内容了
kubectl config view --kubeconfig=/root/user1.kubecfg
# 设置context
kubectl config set-context user1@myk8s \
--cluster=myk8s \
--user=user1 \
--kubeconfig=/root/user1.kubecfg
# 查看user1配置,context已经有内容了
kubectl config view --kubeconfig=/root/user1.kubecfg
# 切换context
kubectl config use-context user1@myk8s --kubeconfig=/root/user1.kubecfg
3.创建角色
bash
cat > user1-role.yaml <<EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: aming
name: user1-role
rules:
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- list
- watch
EOF
kubectl apply -f user1-role.yaml
4.将用户与角色绑定
bash
cat > user1-rolebinding.yaml <<EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: user1-rolebinding
namespace: aming
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: user1-role
subjects:
- kind: User
name: user1
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f user1-rolebinding.yaml
5.创建系统用户并使用user1的配置
bash
useradd aming
mkdir /home/aming/.kube
cp /root/user1.kubecfg /home/aming/.kube/config
chown -R aming.aming /home/aming/.kube/
6.切换到普通用下并访问k8s
bash
su - aming
$ kubectl get po
$ kubectl get po -n aming
$ kubectl get deploy -n aming