Kubernetes Pod Exec API调用返回403 Forbidden问题排查求助
问题排查:K8s API调用Pod exec返回403 Forbidden
问题背景
- Deployment包含带共享卷的init-container,容器内有
/validators/step_1.sh脚本 - 通过以下API请求执行脚本时返回403:
http://127.0.0.1:8001/api/v1/namespaces/default/pods/env-654b4aa0e8ab6dd24f7a33e4-6542b780436645c47c706759-6c8cpvqxk/exec?container=init-container&command=/bin/bash&command=-c&command=bash%20/validators/step_1.sh - 已为ServiceAccount
elyes绑定default命名空间的全权限Role(Role和RoleBinding定义如下),且通过kubectl exec执行脚本正常
Role定义
apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: namespace: default name: full-access-role rules: - apiGroups: [""] resources: ["*"] verbs: ["*"]
RoleBinding定义
apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: full-access-role-binding namespace: default subjects: - kind: ServiceAccount name: elyes namespace: default roleRef: kind: Role name: full-access-role apiGroup: rbac.authorization.k8s.io
排查步骤
查API请求用的是不是
elyes这个ServiceAccount的身份- 要是用ServiceAccount token请求,得确认token属于
elyes:
看输出里的# 假设token存在环境变量TOKEN里 echo $TOKEN | cut -d '.' -f2 | base64 -d | jqsub字段是不是system:serviceaccount:default:elyes。 - 要是通过kubectl proxy发的请求,默认用的是当前kubectl上下文的身份,不是
elyes。得手动带上elyes的token:# 先拿elyes的token TOKEN=$(kubectl get secret $(kubectl get sa elyes -o jsonpath='{.secrets[0].name}') -o jsonpath='{.data.token}' | base64 -d) # 用token发请求 curl -H "Authorization: Bearer $TOKEN" "http://127.0.0.1:8001/api/v1/namespaces/default/pods/[POD_NAME]/exec?container=init-container&command=/bin/bash&command=-c&command=bash%20/validators/step_1.sh"
- 要是用ServiceAccount token请求,得确认token属于
确认Role权限覆盖了exec操作
- Pod的exec对应的资源是
pods/exec,你的Role里写了resources: ["*"]按理应该包含,但可以显式加上试试:
修改Role的rules部分:
执行rules: - apiGroups: [""] resources: ["*", "pods/exec"] verbs: ["*"]kubectl apply -f role.yaml更新后再重试请求。
- Pod的exec对应的资源是
看看init-container是不是已经跑完退出了
- init-container执行完就会退出,状态变成
Completed。这时候K8s不允许对已完成的init-container执行exec,有些K8s版本会返回403。 - 查Pod状态:
看kubectl describe pod env-654b4aa0e8ab6dd24f7a33e4-6542b780436645c47c706759-6c8cpvqxkInit Containers部分的状态,要是Completed就没法执行exec了。
- init-container执行完就会退出,状态变成
检查K8s API Server的授权模式
- 确认API Server开了RBAC授权。看API Server的启动参数,得有
--authorization-mode=RBAC(可以加其他模式,但必须包含RBAC)。 - 要是开了其他授权插件(比如ABAC),可能会影响RBAC权限生效。
- 确认API Server开了RBAC授权。看API Server的启动参数,得有
验证RoleBinding是不是真的生效了
- 用
kubectl auth can-i查elyes有没有pod exec的权限:
要是返回kubectl auth can-i create pods/exec --namespace default --as=system:serviceaccount:default:elyesyes,说明权限配置没问题;要是返回no,那RoleBinding没生效,得检查Role和RoleBinding的定义有没有语法错,或者是不是部署到了正确的命名空间。
- 用
内容的提问来源于stack exchange,提问作者elyes kabous
相关产品推荐
相关产品推荐

