我又遇到了这个概念。出于安全考虑,我们不应该将cluster-admin权限与包含它的ClusterRole一起使用。
假设我们想在集群中部署一个pod,只能访问集群中特定命名空间中的查看和创建pod。在这种情况下,ServiceAccount
可能如下所示:
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
name: spinupcontainers
subjects:
- kind: ServiceAccount
name: spinupcontainers
namespace: <YOUR_NAMESPACE>
roleRef:
kind: Role
name: spinupcontainers
apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: Role
metadata:
name: spinupcontainers
namespace: <YOUR_NAMESPACE>
labels:
k8s-app: <YOUR_APP_LABEL>
rules:
- apiGroups: [""]
resources:
- pods
verbs:
- create
- update
- patch
- delete
- get
- watch
- list
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: spinupcontainers
namespace: <MY_NAMESPACE>
labels:
k8s-app: <MY_APP_LABEL>
---
如果您在部署中使用
serviceAccountName: spinupcontainers
来应用服务账户到容器规格,那么您不需要挂载额外的卷密钥或手动附加证书。
kubectl客户端将从
/var/run/secrets/kubernetes.io/serviceaccount
获取所需的令牌。然后,您可以使用类似以下命令测试它是否正常工作:
$ kubectl exec -it <your-container-with-the-attached-privs> -- /kubectl get pods -n <YOUR_NAMESPACE>
NAME. READY STATUS RESTARTS AGE
pod1-0 1/1 Running 0 6d17h
pod2-0 1/1 Running 0 6d16h
pod3-0 1/1 Running 0 6d17h
pod3-2 1/1 Running 0 67s
或者权限被拒绝:
$ kubectl exec -it <your-container-with-the-attached-privs> -- /kubectl get pods -n kube-system
Error from server (Forbidden): pods is forbidden: User "system:serviceaccount:default:spinupcontainers" cannot list resource "pods" in API group "" in the namespace "kube-system"
command terminated with exit code 1
测试环境:
$ kubectl exec -it <your-container-with-the-attached-privs> -- /kubectl versionClient Version: version.Info{Major:"1", Minor:"17", GitVersion:"v1.17.0", GitCommit:"70132b0f130acc0bed193d9ba59dd186f0e634cf", GitTreeState:"clean", BuildDate:"2019-12-07T21:20:10Z", GoVersion:"go1.13.4", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"17", GitVersion:"v1.17.0", GitCommit:"70132b0f130acc0bed193d9ba59dd186f0e634cf", GitTreeState:"clean", BuildDate:"2019-12-07T21:12:17Z", GoVersion:"go1.13.4", Compiler:"gc", Platform:"linux/amd64"}