我刚刚再次面对这个概念。这是绝对可能的,但出于安全原因,我们不要在 ClusterRole 容器中授予“cluster-admin 权限。
假设我们想在集群中部署一个 pod,它只能在集群中的特定命名空间中访问 view 和 create 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" omitted if was ClusterRoles because are not namespaced
namespace: <YOUR_NAMESPACE>
labels:
k8s-app: <YOUR_APP_LABEL>
rules:
#
# Give here only the privileges you need
#
- 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"}