需求
现有两个命名空间dev和test,现需要使用一个serviceaccount同时对这两个命名空间有固定操作权限
步骤
在dev命名空间创建serviceaccount、role以及rolebinding
apiVersion: v1
kind: ServiceAccount
metadata:
name: username
namespace: dev
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: common-user
namespace: dev
rules:
- apiGroups:
- apps
- ''
resources:
- deployments
- replicasets
- statefulsets
- daemonsets
- pods
- pods/log
- pods/exec
- namespaces
verbs:
- list
- get
- create
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: common-user
namespace: dev
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: common-user
subjects:
- kind: ServiceAccount
name: username
namespace: dev
创建资源 kubectl apply -f username.yaml
此时username这个用户对dev这个命名空间是有固定操作权限的
创建一个相同权限的cluserrole
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: common-user
rules:
- apiGroups:
- apps
- ''
resources:
- deployments
- replicasets
- statefulsets
- daemonsets
- pods
- pods/log
- pods/exec
- namespaces
verbs:
- list
- get
- create
创建资源 kubectl apply -f clusterrole.yaml
在test命名空间创建一个rolebinding关联dev命名空间下的serviceaccount
kind: RoleBinding
metadata:
name: common-user
namespace: test
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: common-user
subjects:
- kind: ServiceAccount
name: username
namespace: dev
创建资源 kubectl apply -f username_test.yaml
此时,dev命名空间下的username这个serviceaccount就对dev和test这两个命名空间有相同的操作权限了
查看serviceaccount的token
echo $(kubectl -n dev get secret $(kubectl -n dev get secret | grep username | awk '{print $1}') -o go-template='{{.data.token}}' | base64 -d)