我有过类似的情况。这是我解决它的方法(我使用的是“默认”以外的命名空间)。
对 API 的访问是通过创建一个ServiceAccount来完成的,将其分配给Pod并将一个角色绑定到它。
1.创建服务账户
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-serviceaccount
namespace: my-namespace
2.创建角色:在本节中,您需要提供资源列表和您想要访问的操作列表。这是您想要列出端点并获取特定端点详细信息的示例。
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: my-role
namespace: my-namespace
rules:
- apiGroups: [""]
resources: ["endpoints"]
verbs: ["get", "list"]
3.将角色绑定到服务账号
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: my-role-binding
namespace: my-namespace
subjects:
- kind: ServiceAccount
name: my-serviceaccount
roleRef:
kind: Role
name: my-role
apiGroup: rbac.authorization.k8s.io
4.将服务帐户分配给部署中的 pod(它应该在 template.spec 下)
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-deployment
namespace: my-namespace
spec:
replicas: 1
selector:
matchLabels:
app: my-pod
template:
metadata:
labels:
app: my-pod
spec:
serviceAccountName: my-serviceaccount
containers:
- name: my-pod
...
设置好所有安全方面后,您将有足够的权限访问 Pod 中的 API。与 API Server 通信所需的所有信息都安装/var/run/secrets/kubernetes.io/serviceaccount
在您的 Pod 中。您可以使用以下 shell 脚本(可能将其添加到您的命令或 Docker 映像的入口点)。
#!/bin/bash
# Point to the internal API server hostname
API_SERVER=https://kubernetes.default.svc
# Path to ServiceAccount token
SERVICE_ACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount
# Read this Pod's namespace
NAMESPACE=$(cat ${SERVICE_ACCOUNT}/namespace)
# Read the ServiceAccount bearer token
TOKEN=$(cat ${SERVICE_ACCOUNT}/token)
# Reference the internal certificate authority (CA)
CA_CERT=${SERVICE_ACCOUNT}/ca.crt
从现在开始,它只是简单的 REST API 调用。您可以使用您选择的任何语言读取这些环境变量并访问 API。
这是为您的用例列出端点的示例
# List all the endpoints in the namespace that Pod is running
curl --cacert ${CA_CERT} --header "Authorization: Bearer ${TOKEN}" -X GET \
"${API_SERVER}/api/v1/namespaces/${NAMESPACE}/endpoints"
# List all the endpoints in the namespace that Pod is running for a deployment
curl --cacert ${CA_CERT} --header "Authorization: Bearer ${TOKEN}" -X GET \
"${API_SERVER}/api/v1/namespaces/${NAMESPACE}/endpoints/my-deployment"
有关可用 API 端点以及如何调用它们的更多信息,请参阅API 参考。