简体   繁体   English

从本地机器访问 Kubernetes API

[英]Accessing Kubernetes APIs from local machine

I wish to access Kubernetes APIs from my local machine.我希望从我的本地机器访问 Kubernetes API。 I'm trying to get list of pods using kubernetes Rest APIs.我正在尝试使用 kubernetes Rest API 获取 pod 列表。

I've created a kubernetes cluster and some pods on Google Cloud .我在Google Cloud上创建了一个 kubernetes 集群和一些 pod。

On my local Windows machine, I've installed gcloud sdk and kubectl component with it.在我本地的 Windows 机器上,我已经安装了 gcloud sdk 和 kubectl 组件。 I connected to my cluster using:我使用以下方式连接到我的集群:

gcloud container clusters get-credentials my-cluster --region us-central1 --project my-project

I can get the list of pods using kubectl get pods我可以使用kubectl get pods列表

Although, I want to get pods list using kubernetes Rest APIs.虽然,我想使用 kubernetes Rest API 获取 pod 列表。

GET https://kubernetes.default/api/v1/namespaces/default/pods
Authorization: Bearer my_access_token

But I think the request is not going through.但我认为请求没有通过。

In Postman, I get the error:在 Postman 中,我收到错误:

Error: tunneling socket could not be established, cause=socket hang up

Or in Python using requests library (from my local machine), I get the error或者在 Python 中使用 requests 库(来自我的本地机器),我得到了错误

HTTPSConnectionPool(host='kubernetes.default', port=443): Max retries exceeded with url: /api/v1/namespaces/default/pods (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000277DCD04D90>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))

What am I missing here?我在这里想念什么?

The endpoint https://kubernetes.default only works if you want to access Kubernetes REST API from inside the cluster ie from another pod. The endpoint https://kubernetes.default only works if you want to access Kubernetes REST API from inside the cluster ie from another pod. For accessing Kubernetes REST API from outside the kubernetes cluster ie from your local machine you need to use the API server IP or host which is externally accessible ie the one which is there in kubeconfig file. For accessing Kubernetes REST API from outside the kubernetes cluster ie from your local machine you need to use the API server IP or host which is externally accessible ie the one which is there in kubeconfig file.

For accessing it from outside the kubernetes cruster ie from your local machine there are three ways referring from the docs here要从 kubernetes 外壳(即从您的本地计算机)外部访问它, 这里的文档中有三种方法可供参考

  1. Run kubectl in proxy mode (recommended).以代理模式运行 kubectl(推荐)。 This method is recommended, since it uses the stored apiserver location and verifies the identity of the API server using a self-signed cert.建议使用此方法,因为它使用存储的 apiserver 位置并使用自签名证书验证 API 服务器的身份。 No man-in-the-middle (MITM) attack is possible using this method.使用此方法不可能进行中间人 (MITM) 攻击。

    kubectl proxy --port=8080 &

    curl http://localhost:8080/api/v1/namespaces/default/pods

  2. It is possible to avoid using kubectl proxy by passing an authentication token directly to the API server, like this:可以通过将身份验证令牌直接传递给 API 服务器来避免使用 kubectl 代理,如下所示:

Check all possible clusters, as your.KUBECONFIG may have multiple contexts:检查所有可能的集群,因为您的.KUBECONFIG 可能有多个上下文:

kubectl config view -o jsonpath='{"Cluster name\tServer\n"}{range .clusters[*]}{.name}{"\t"}{.cluster.server}{"\n"}{end}'

Select name of cluster you want to interact with from above output: Select 您想要从上面 output 交互的集群名称:

export CLUSTER_NAME="some_server_name"

Point to the API server referring the cluster name指向引用集群名称的 API 服务器

APISERVER=$(kubectl config view -o jsonpath="{.clusters[?(@.name==\"$CLUSTER_NAME\")].cluster.server}")

Gets the token value获取令牌值

TOKEN=$(kubectl get secrets -o jsonpath="{.items[?(@.metadata.annotations['kubernetes\.io/service-account\.name']=='default')].data.token}"|base64 --decode)

Explore the API with TOKEN使用 TOKEN 探索 API

curl -X GET $APISERVER/api/v1/namespaces/default/pods --header "Authorization: Bearer $TOKEN" --insecure
  1. Using client library使用客户端库

To use Python client, run the following command: pip install kubernetes See Python Client Library page for more installation options.要使用 Python 客户端,请运行以下命令: pip install kubernetes有关更多安装选项,请参见ZA7F5F35426B5274173Z 客户端库页面 1B68安装选项2274173Z 客户端库页面。

The Python client can use the same kubeconfig file as the kubectl CLI does to locate and authenticate to the API server. Python 客户端可以使用与kubectl CLI 相同的kubeconfig文件来定位和验证 API 服务器。 See this example:看这个例子:

from kubernetes import client, config

config.load_kube_config()

v1=client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
    print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

You can also do it the way you are doing without using kubeconfig file but it's more work and you need to use the kubernetes API Server IP or hostname from the kubeconfig file.您也可以在不使用 kubeconfig 文件的情况下按照您的方式进行操作,但它需要更多的工作,您需要使用 kubernetes API 服务器 IP 或 kubeconfig.

using below kubectl command start a proxy to the Kubernetes API server:使用以下 kubectl 命令启动 Kubernetes API 服务器的代理:

kubectl proxy --port=8080

Get the API versions:

curl http://localhost:8080/api/
The output should look similar to this:

{
  "kind": "APIVersions",
  "versions": [
    "v1"
  ],
  "serverAddressByClientCIDRs": [
    {
      "clientCIDR": "0.0.0.0/0",
      "serverAddress": "10.0.2.15:8443"
    }
  ]
}

Your api server address is not correct for external REST access.您的 api 服务器地址对于外部 REST 访问不正确。

Get the address like this.获取这样的地址。

kubectl config view

Find your cluster name in the list and get the APi.在列表中找到您的集群名称并获取 APi。

Here is the cURL (without the real IP or the token) which worked in my local pc.这是在我的本地电脑上工作的 cURL(没有真正的 IP 或令牌)。

curl --location --request GET 'https://nnn.nnn.nnnn.nnn/api/v1/namespaces/develop/pods' \
--header 'Authorization: bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

If you run in POSTMAN, you might have to disable certificate verification.如果您在 POSTMAN 中运行,您可能必须禁用证书验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM