尽管有 RoleBinding与 ClusterRoleBinding 相同,为什么这个 pod 在调用 Kubernetes API 时会得到 403 Forbidden?

问题描述

我创建了一个 pod(一个用于运行命令的 Alpine“BusyBox”),然后它会获取与之关联的 default 服务帐户。然后我创建了一个 RoleBinding (后来 ClusterRoleBinding 当第一个不起作用时),但它仍然不允许我调用 K8s API。

我做错了什么?

首先我创建了一个容器来运行命令:

# Create a namespace to install our pod
kubectl create namespace one

# Now create a pod that we can run stuff in
kubectl run runner -n one --image alpine -- sleep 3600

然后我创建了一个角色绑定:

# My understanding of this command is that I'm doing the following:
# 1. Creating a binding for the "default" service account in the "one" namespace
# 2. Tying that to the cluster role for viewing things
# 3. Making this binding work in the "default" namespace,so that it can call
#    the API there FROM its own namespace (one)
kubectl create rolebinding default-view --clusterrole=view --serviceaccount=one:default --namespace=default

然后我连接到 pod 的终端并尝试调用 API 以列出其自己的命名空间中的所有服务:

kubectl exec --stdin --tty use-rest -n one -- /bin/ash

# Now I run all these inside that terminal:

# Point to the internal API server hostname
APISERVER=https://kubernetes.default.svc

# Path to ServiceAccount token
SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount

# Read the ServiceAccount bearer token
TOKEN=$(cat ${SERVICEACCOUNT}/token)

# Reference the internal certificate authority (CA)
CACERT=${SERVICEACCOUNT}/ca.crt

# The wget installed with Alpine cannot do SSL
apk --no-cache add ca-certificates
apk add wget

wget --ca-certificate=${CACERT} --header="Authorization: Bearer ${TOKEN}" ${APISERVER}/api/v1/namespaces/$NAMESPACE/services

上面给出了错误

--2021-04-20 01:04:54-- https://kubernetes.default.svc/api/v1/namespaces/default/services/
解决 kubernetes.default.svc (kubernetes.default.svc)... 10.43.0.1
连接到 kubernetes.default.svc (kubernetes.default.svc)|10.43.0.1|:443...已连接。
HTTP 请求已发送,正在等待响应... 403 Forbidden
2021-04-20 01:04:54 错误 403:禁止

但这应该被允许!我在使用集群角色绑定时遇到同样的错误

使用:

  • k3d 版本 v4.4.1
  • k3s 版本 v1.20.5-k3s1(认)
  • 印花布

解决方法

每个 Pod 只能有一个 ServiceAccount,一旦您为该 Pod 分配了一个帐户,default 帐户就不再适用。我试图将角色绑定到 default 帐户,但传递了我为 pod 创建的另一个帐户的令牌。