kubeconfig 解析
为什么一个kubectl能控制多个集群?
因为kubectl的配置文件中定义了多个集群,以及多个帐号及上下文信息,可以通过切换上下文实现切换用户管理集群,或者切换集群
# kubectl config view
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: REDACTED
server: https://172.31.117.180:6443
name: kubernetes
contexts:
- context:
cluster: kubernetes
user: kubernetes-admin
name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
kind: Config
preferences: {}
users:
- name: kubernetes-admin
user:
client-certificate-data: REDACTED
client-key-data: REDACTED
创建k8s集群用户
生成私钥
# (umask 077; openssl genrsa -out lotus.key 2048)
生成证书请求,CN为用户名
# openssl req -new -key lotus.key -out lotus.csr -subj "/CN=lotus"
使用ca证书和私钥签发证书
# openssl x509 -req -in lotus.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out lotus.crt -days 3650
查看签发的证书信息
# openssl x509 -in lotus.crt -text -noout
创建lotus用户
# kubectl config set-credentials lotus --client-certificate=./lotus.crt --client-key=./lotus.key --embed-certs=true
创建lotus上下文
# kubectl config set-context lotus@kubernetes --cluster=kubernetes --user=lotus
切换当前用户为lotus
# kubectl config use-context lotus@kubernetes
尝试获取Pods资源,会发现提示没有权限
# kubectl get pods
No resources found.
Error from server (Forbidden): pods is forbidden: User "lotus" cannot list pods in the namespace "default"