要让一个 Service Account Token 只能被特定的 Pod 使用,可以使用 Kubernetes 中的 RBAC(Role-Based Access Control)机制。以下是具体步骤:
- 创建一个拥有该 Service Account 权限的 Cluster Role 或 Role。
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "watch", "list"]
- 创建一个绑定了该 Role 的 Cluster Role Binding 或 Role Binding,并指定对应的 Service Account。
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: pod-reader-binding
roleRef:
kind: ClusterRole
name: pod-reader
apiGroup: rbac.authorization.k8s.io
subjects:
- kind: ServiceAccount
name: <service-account-name>
namespace: <namespace>
# 或者
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
name : pod-reader-binding
namespace : default
roleRef:
apiGroup : rbac.authorization.k8s.io
kind : ClusterRole
name : pod-reader
subjects :
- kind : ServiceAccount
name : my-sa
3. 在需要使用该 Service Account 的 Pod 中添加 annotation,以指定使用该 Service Account。
apiVersion: v1 kind: Pod metadata:
name: my-pod-with-sa-token
annotations:
kubernetes.io/service-account.name: <service-account-name>
spec:
containers:
- name: my-container
image: nginx
ports:
- containerPort: 80
”`
注意,在上面的示例中,<service-account-name>
指定了该 Pod 所使用的 Service Account 的名称。此外,在绑定 Role 和 Service Account 的时候,可以根据需要指定命名空间。
通过以上步骤,只有在使用了该 annotation 的 Pod 才能使用该 Service Account Token 进行 API 访问。