淘先锋技术网

首页 1 2 3 4 5 6 7

需求是给开发 测试分配不同namespace的账号 并作权限区分

创建test用户

 kubectl create sa test -n test

新建一个namespace

kubectl create ns test

创建ServiceAccount test-service-account.yaml

apiVersion: v1
kind: ServiceAccount
metadata:
  name: test-service-account
  namespace: test     #指定上面创建的 Namespace

然后创建自定义角色分配 Namespace 权限 test-role-binding-custom.yaml

#role
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: test-role
  namespace: test                 #指定 Namespace
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"]
---
#role binding
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: test-role-binding
  namespace: test                 #指定 Namespace
subjects:
  - kind: ServiceAccount
    name: test-service-account              #指定 ServiceAccount
    namespace: test               #指定 Namespace
roleRef:
  kind: Role
  name: test-role
  apiGroup: rbac.authorization.k8s.io

创建 test-cluster-role-binding.yaml 用于解决登录 Dashboard 不能选择 Namespace 问题

kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: role-bind-test
  namespace: test
subjects:
- kind: ServiceAccount
  name: test
  namespace: test
roleRef:
  kind: Role
  name: role-test
  apiGroup: rbac.authorization.k8s.io

创建role

kubectl apply -f test-service-account.yaml
kubectl apply -f test-role-binding-custom.yaml
kubectl apply -f test-cluster-role-binding.yaml

查看token

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

创建test的conf文件

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


用conf文件登陆 这里不小心单词写错了

登陆成功

如果namespace 不能选择 可以参考下面文章

https://www.ziji.work/kubernetes/kubernetes-dashboard-create-rbac.html