已创建ServiceAccount、ClusterRole等资源却无法在指定命名空间创建Deployment
问题修复方案
核心错误点
- ClusterRole权限配置缺失:需求包含创建权限,但你配置的verbs列表里没有
create字段,创建操作会被直接拒绝 - 绑定对象匹配错误:你创建的身份是ServiceAccount(SA)类型的
john,但ClusterRoleBinding里配置的subject是User类型的hruser,身份完全不匹配,绑定规则没有生效 - 权限校验命令格式错误:用
--as模拟ServiceAccount身份时,需要使用SA的完整标识格式,不能直接写SA名称
正确操作步骤
1. 清理之前错误创建的资源
kubectl delete sa john -n default kubectl delete sa john -n hr kubectl delete clusterrole hrcrole kubectl delete clusterrolebinding hrcrolebind kubectl delete rolebinding hrcrolebind -n hr
2. 创建ServiceAccount
按需求将SA创建在hr命名空间:
kubectl create sa john -n hr
3. 修正后的ClusterRole配置
保存为hrcrole.yaml:
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: hrcrole rules: - apiGroups: ["apps"] resources: ["deployments", "statefulsets", "daemonsets"] verbs: ["get", "watch", "list", "delete", "create"]
应用配置:
kubectl apply -f hrcrole.yaml
4. 绑定配置
如果要求权限仅在hr命名空间生效(和需求描述一致),使用RoleBinding绑定ClusterRole,保存为hrcrolebind.yaml:
apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: hrcrolebind namespace: hr subjects: - kind: ServiceAccount name: john namespace: hr roleRef: kind: ClusterRole name: hrcrole apiGroup: rbac.authorization.k8s.io
如果要求必须使用ClusterRoleBinding(权限全局生效),使用以下配置:
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: hrcrolebind subjects: - kind: ServiceAccount name: john namespace: hr apiGroup: rbac.authorization.k8s.io roleRef: kind: ClusterRole name: hrcrole apiGroup: rbac.authorization.k8s.io
应用配置:
kubectl apply -f hrcrolebind.yaml
5. 权限校验
使用SA完整标识执行校验:
kubectl auth can-i create deploy --as system:serviceaccount:hr:john -n hr
正常会返回yes。
内容的提问来源于stack exchange,提问作者haridurgempudi
相关产品推荐
相关产品推荐

