[kubernetes]-kubernetes创建多namespace权限的kubeconfig

#1. 创建集群级别的角色 ClusterRole

# clusterrole.yaml 提供基本权限
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cr-hz
rules:
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
  - apiGroups: ["extensions", "apps"]
    resources: ["deployments"]
    verbs: ["get", "watch", "list"]
  - apiGroups: [""]
    resources: ["pods/exec"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
  - apiGroups: [""]
    resources: ["pods/log"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

创建clusterrole.cr-namespace.yaml

提供kubectl get namespace能力

# clusterrole.cr-namespace.yaml 提供namespace的查看权限
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cr-namespace-hz
rules:
- apiGroups:
  - ""
  resources:
  - namespaces/status
  - namespaces
  verbs:
  - get
  - list
  - watch
kubectl apply -f clusterrole.yaml
kubectl apply -f clusterrole.cr-namespace.yaml

#2. 在default命名空间创建 ServiceAccount

注意,创建sa后,会自动创建一个绑定的 secret

后面在kubeconfig文件中,会用到该secret中的token

kubectl create serviceaccount hz

#3. 对sa和集群角色建立绑定关系

#这里对dev和test两个namespace授权
kubectl create rolebinding rbd-hz --clusterrole=cr-hz --serviceaccount=default:hz --namespace=dev
kubectl create rolebinding rbd-hz --clusterrole=cr-hz --serviceaccount=default:hz --namespace=test
kubectl create rolebinding rbd-hz --clusterrole=cr-hz --serviceaccount=default:hz --namespace=peg
#这里namespace会将集群级别的权限限定在某个namespace下,cr-devlog中定认的集群权限仅作用于dev和test名称空间
kubectl create clusterrolebinding crbd-hz --clusterrole=cr-namespace-hz --serviceaccount=default:hz

#4.获取token先测试一下

kubectl get secret  |grep hz-token
token_name=`kubectl get secret  |grep hz-token |awk '{print $1}'`
secret=`kubectl  describe secret $token_name|grep "token:" |awk -F":" '{print $NF}'`
echo $secret 

#5.生成config文件

kubectl config set-cluster kubernetes --server=192.168.1.202:6443 --kubeconfig=/kubernetes/dashboard/dashboard-h z.conf
# 这里的scret参数需要替换成上面获取到的登陆的token值
kubectl config set-credentials dashboard-hz --token="$secret" --kubeconfig=/kubernetes/dashboard/dashboard-hz.conf
kubectl config set-context dashboard-hz@kubernetes --cluster=kubernetes --user=dashboard-hz --kubeconfig=/kubernetes/dashboard/dashboard-hz.conf
kubectl config use-context dashboard-hz@kubernetes  --kubeconfig=/kubernetes/dashboard/dashboard-hz.conf

#6.导出config文件 测试

[kubernetes]-kubernetes创建多namespace权限的kubeconfig_第1张图片

[kubernetes]-kubernetes创建多namespace权限的kubeconfig_第2张图片

[kubernetes]-kubernetes创建多namespace权限的kubeconfig_第3张图片

参考

https://pdf.us/2019/09/20/3650.html

你可能感兴趣的:(kubernetes)