问题描述
我在kubernetes中有一个服务帐户:
apiVersion: v1
kind: ServiceAccount
Metadata:
name: testsa
namespace: project-1
我已将其分配给view
角色:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
Metadata:
name: testsa-view
namespace: project-1
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: view
subjects:
- kind: ServiceAccount
name: testsa
namespace: project-1
这应授予服务帐户对所有资源的读取权限。在project-1
命名空间的容器中,我试图运行以下Python代码:
>>> from kubernetes import client,config
>>> config.load_incluster_config()
>>> api = client.CoreV1Api()
>>> api.list_pod_for_all_namespaces()
但这失败,并出现403
错误:
kubernetes.client.rest.ApiException: (403)
Reason: Forbidden
[...]
HTTP response body: {"kind":"Status","apiVersion":"v1","Metadata":{},"status":"Failure","message":"pods is forbidden: User \"system:serviceaccount:project-1:testsa\" cannot list resource \"pods\" in API group \"\" at the cluster scope","reason":"Forbidden","details":{"kind":"pods"},"code":403}
吊舱与服务帐户相关联:
apiVersion: v1
kind: Pod
Metadata:
labels:
run: testsa
name: testsa-2-l929g
namespace: project-1
spec:
serviceAccountName: testsa
automountServiceAccountToken: true
containers:
- image: larsks/testsa
imagePullPolicy: Always
name: testsa
ports:
- containerPort: 8080
protocol: TCP
resources: {}
在容器内,我可以看到安装的机密:
/src $ find /run/secrets/ -type f
/run/secrets/kubernetes.io/serviceaccount/..2020_09_04_16_30_26.292719465/ca.crt
/run/secrets/kubernetes.io/serviceaccount/..2020_09_04_16_30_26.292719465/token
/run/secrets/kubernetes.io/serviceaccount/..2020_09_04_16_30_26.292719465/service-ca.crt
/run/secrets/kubernetes.io/serviceaccount/..2020_09_04_16_30_26.292719465/namespace
/run/secrets/rhsm/ca/redhat-uep.pem
/run/secrets/rhsm/ca/redhat-entitlement-authority.pem
我在这里想念什么?
解决方法
错误提示cannot list resource \"pods\" in API group \"\" at the cluster scope
,因为您试图访问群集中所有名称空间的所有Pod,而不是仅访问project-1
名称空间的所有Pod。
因此将Role
更改为ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: testsa-view
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: view
subjects:
- kind: ServiceAccount
name: testsa
namespace: project-1
从示例here RoleBinding
引用开始,即使在引用其中的ClusterRole
时,也始终授予仅限于该特定名称空间的名称空间范围资源。
您可以使用以下命令检查服务帐户的权限
kubectl auth can-i --list --as=system:serviceaccount:project-1:testsa
kubectl auth can-i --list --as=system:serviceaccount:project-1:testsa -n project-1
kubectl auth list pods --as=system:serviceaccount:project-1:testsa
kubectl auth list pods --as=system:serviceaccount:project-1:testsa -n project-1