![Kubernetes API 从 Pod 内部返回 403 Forbidden,而 ClusterRole 似乎已正确绑定到 Pod 服务帐户](https://linux22.com/image/793088/Kubernetes%20API%20%E4%BB%8E%20Pod%20%E5%86%85%E9%83%A8%E8%BF%94%E5%9B%9E%20403%20Forbidden%EF%BC%8C%E8%80%8C%20ClusterRole%20%E4%BC%BC%E4%B9%8E%E5%B7%B2%E6%AD%A3%E7%A1%AE%E7%BB%91%E5%AE%9A%E5%88%B0%20Pod%20%E6%9C%8D%E5%8A%A1%E5%B8%90%E6%88%B7.png)
我有一个在 k8s pod(Google Kubernetes Engine 1.25)中运行的 Python 脚本,它查询 K8S API 来创建 VaultStaticSecret 的资源。
为了简洁起见,我将粘贴 Helm Chart 模板:
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: {{ .Release.Name }}
rules:
- apiGroups: ["secrets.hashicorp.com"]
resources: ["vaultstaticsecrets"]
verbs: ["list", "create", "update", "patch", "watch", "get"]
- apiGroups: ["secrets.hashicorp.com"]
resources: ["vaultstaticsecrets/status"]
verbs: ["get"]
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: {{ .Release.Name }}
namespace: {{ .Release.Namespace }}
subjects:
- kind: ServiceAccount
name: {{ .Release.Name }}
namespace: {{ .Release.Namespace }}
roleRef:
kind: ClusterRole
name: {{ .Release.Name }}
apiGroup: rbac.authorization.k8s.io
看起来 k8s 应该允许此服务帐户列出 VaultStaticSecrets,例如:
kubectl auth can-i get vaultstaticsecret --as system:serviceaccount:vault-secrets-operator-system:vault-secrets-syncer
yes
然而 Python 脚本内部出现错误:
An exception occurred when querying for VaultStaticSecret: (403)
Reason: Forbidden
HTTP response headers: HTTPHeaderDict({'Audit-Id': '26c77f88-2d10-426c-9c23-a830c8f6c50e', 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'X-Content-Type-Options': 'nosniff', 'X-Kubernetes-Pf-Flowschema-Uid': '44e95fb1-2e69-4685-8a4e-26140f6145a9', 'X-Kubernetes-Pf-Prioritylevel-Uid': '5969f717-f4e9-4246-83b2-c6b7c9f20f49', 'Date': 'Tue, 20 Feb 2024 12:16:54 GMT', 'Content-Length': '491'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":".vaultstaticsecrets.secrets.hashicorp.com \"vaultstaticsecrets\" is forbidden: User \"system:serviceaccount:vault-secrets-operator-system:vault-secrets-syncer\" cannot get resource \"/dagster\" in API group \"vaultstaticsecrets.secrets.hashicorp.com\" in the namespace \"data-platform\"","reason":"Forbidden","details":{"name":"vaultstaticsecrets","group":"vaultstaticsecrets.secrets.hashicorp.com"},"code":403}
答案1
经过一些调试后,我发现我将 k8s 命名空间参数传递给“get_namespaced_custom_object”函数时带有尾随斜杠,但错误却没有尾随斜杠。