- 新用户本地生成私钥和证书请求文件
student@client:~$ kubectl create ns test
student@client:~$ cd ~/.kube/
student@client:~/.kube$ openssl genrsa -out fox-user.key 2048
student@client:~/.kube$ openssl rand -writerand ~/.rand
student@client:~/.kube$ openssl req -new -key fox-user.key -out fox-user.csr -subj "/CN=fox-user/O=kubeusers"
注意上面步骤中的-subj参数,指定了在K8S中要新建的用户名为fox-user,角色类型为kubeusers(一个普通用户)
如果要创建集群管理员用户
,则应写:“/CN=XXXXX/O=system:masters/O=system:authenticated”
- 用户把证书请求文件发送给master节点管理员,私钥自己留存
student@client:~/.kube$ scp fox-user.csr k8s-master:/tmp
- 使用master节点的根CA为用户的证书请求文件签发证书
root@k8s-master:~## mv /tmp/fox-user.csr /etc/kubernetes/pki/ && cd /etc/kubernetes/pki
root@k8s-master:/etc/kubernetes/pki## openssl x509 -req -in fox-user.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out fox-user.crt -days 365
root@k8s-master:/etc/kubernetes/pki## openssl x509 -in fox-user.crt -text -noout
- 把签发完的证书和master根证书发回给用户
root@k8s-master:/etc/kubernetes/pki## scp fox-user.crt ca.crt student@client:~/.kube
- 在客户端设置集群入口
student@client:~/.kube$ kubectl config set-cluster mycluster --embed-certs --certificate-authority=ca.crt --server="https://192.168.126.100:6443"
- 在客户端设置用户credentials
student@client:~/.kube$ kubectl config set-credentials fox-user --embed-certs --client-certificate=fox-user.crt --client-key=fox-user.key
- 在客户端设置context
student@client:~/.kube$ kubectl config set-context fox-user@mycluster --cluster=mycluster --user=fox-user
- 在客户端切换上下文并测试
student@client:~/.kube$ kubectl config use-context fox-user@mycluster
student@client:~/.kube$ kubectl get nodes
Error from server (Forbidden): nodes is forbidden: User "fox-user" cannot list resource "nodes" in API group "" at the cluster scope
可以看到一个普通用户并不能执行get nodes这样的操作
- 创建一个角色仅能在namespace=test中执行list pods操作
注意要先回到管理员context
student@client:~/.kube$ kubectl config use-context kubernetes-admin@kubernetes
student@client:~/.kube$ kubectl create role fox-role --resource="pod" --verb="list" -n test
- 创建一个rolebinding,将上述role绑定到用户fox-user
student@client:~/.kube$ kubectl create rolebinding fox-rolebinding --role=fox-role --user=fox-user -n test
- 至此,用户fox-user已绑定到fox-role这个角色,而这个角色的权限仅限于test中list pod,切换上下文,验证
student@client:~/.kube$ kubectl config use-context fox-user@mycluster
student@client:~/.kube$ kubectl get pods -n test
No resources found in test namespace.
试一下list services
student@client:~/.kube$ kubectl get svc -n test
Error from server (Forbidden): services is forbidden: User "fox-user" cannot list resource "services" in API group "" in the namespace "test"