使用 Kubernetes API 存取叢集

本頁說明如何使用 Kubernetes API 存取叢集。

開始之前

您需要有一個 Kubernetes 叢集,並且必須設定 kubectl 命令列工具以與您的叢集通訊。建議在至少有兩個節點且節點不充當控制平面主機的叢集上執行本教學課程。如果您還沒有叢集,可以使用 minikube 建立一個,或者您可以使用以下 Kubernetes 實驗環境

若要檢查版本,請輸入 kubectl version

存取 Kubernetes API

首次使用 kubectl 存取

首次存取 Kubernetes API 時,請使用 Kubernetes 命令列工具 kubectl

若要存取叢集,您需要知道叢集的位置並具有存取它的憑證。通常,當您完成入門指南時,會自動設定此項,或者其他人設定了叢集並為您提供了憑證和位置。

使用此命令檢查 kubectl 知道的位置和憑證

kubectl config view

許多範例提供了 kubectl 使用入門。完整文件請參閱 kubectl 手冊

直接存取 REST API

kubectl 處理定位和驗證 API 伺服器。如果您想要使用 http 用戶端(例如 curlwget)或瀏覽器直接存取 REST API,則有多種方法可以定位 API 伺服器並對其進行驗證

  1. 在 Proxy 模式下執行 kubectl(建議)。建議使用此方法,因為它使用儲存的 API 伺服器位置,並使用自我簽署憑證驗證 API 伺服器的身分。使用此方法不可能發生中間人 (MITM) 攻擊。
  2. 或者,您可以將位置和憑證直接提供給 http 用戶端。這適用於對 Proxy 感到困惑的用戶端程式碼。為了防止中間人攻擊,您需要將根憑證匯入到您的瀏覽器中。

使用 Go 或 Python 用戶端程式庫提供在 Proxy 模式下存取 kubectl。

使用 kubectl proxy

以下命令在 kubectl 充當反向 Proxy 的模式下執行 kubectl。它處理定位 API 伺服器和身份驗證。

像這樣執行它

kubectl proxy --port=8080 &

如需更多詳細資訊,請參閱 kubectl proxy

然後,您可以使用 curl、wget 或瀏覽器探索 API,如下所示

curl http://localhost:8080/api/

輸出類似於此

{
  "versions": [
    "v1"
  ],
  "serverAddressByClientCIDRs": [
    {
      "clientCIDR": "0.0.0.0/0",
      "serverAddress": "10.0.1.149:443"
    }
  ]
}

不使用 kubectl proxy

可以透過將身份驗證權杖直接傳遞到 API 伺服器來避免使用 kubectl proxy,如下所示

使用 grep/cut 方法

# Check all possible clusters, as your .KUBECONFIG may have multiple contexts:
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:
export CLUSTER_NAME="some_server_name"

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

# Create a secret to hold a token for the default service account
kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
  name: default-token
  annotations:
    kubernetes.io/service-account.name: default
type: kubernetes.io/service-account-token
EOF

# Wait for the token controller to populate the secret with a token:
while ! kubectl describe secret default-token | grep -E '^token' >/dev/null; do
  echo "waiting for token..." >&2
  sleep 1
done

# Get the token value
TOKEN=$(kubectl get secret default-token -o jsonpath='{.data.token}' | base64 --decode)

# Explore the API with TOKEN
curl -X GET $APISERVER/api --header "Authorization: Bearer $TOKEN" --insecure

輸出類似於此

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

上述範例使用了 --insecure 標記。這會使其容易遭受中間人攻擊 (MITM)。當 kubectl 存取叢集時,它會使用儲存的根憑證和用戶端憑證來存取伺服器。(這些憑證安裝在 ~/.kube 目錄中)。由於叢集憑證通常是自簽憑證,因此可能需要特殊配置才能讓您的 http 用戶端使用根憑證。

在某些叢集上,API 伺服器不需要身份驗證;它可能在 localhost 上提供服務,或受到防火牆保護。這方面沒有標準做法。控制 Kubernetes API 的存取權 說明了叢集管理員可以如何配置此項。

程式化存取 API

Kubernetes 官方支援以下用戶端程式庫:GoPythonJavadotnetJavaScriptHaskell。還有其他用戶端程式庫由其作者提供和維護,而非 Kubernetes 團隊。請參閱用戶端程式庫,以了解如何從其他語言存取 API 以及它們如何進行身份驗證。

Go 用戶端

  • 若要取得程式庫,請執行以下命令:go get k8s.io/client-go@kubernetes-<kubernetes-version-number> 請參閱 https://github.com/kubernetes/client-go/releases 以查看支援的版本。
  • 在 client-go 用戶端之上編寫應用程式。

Go 用戶端可以使用與 kubectl CLI 相同的 kubeconfig 檔案,以定位 API 伺服器並對其進行身份驗證。請參閱此範例

package main

import (
  "context"
  "fmt"
  "k8s.io/apimachinery/pkg/apis/meta/v1"
  "k8s.io/client-go/kubernetes"
  "k8s.io/client-go/tools/clientcmd"
)

func main() {
  // uses the current context in kubeconfig
  // path-to-kubeconfig -- for example, /root/.kube/config
  config, _ := clientcmd.BuildConfigFromFlags("", "<path-to-kubeconfig>")
  // creates the clientset
  clientset, _ := kubernetes.NewForConfig(config)
  // access the API to list pods
  pods, _ := clientset.CoreV1().Pods("").List(context.TODO(), v1.ListOptions{})
  fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
}

如果應用程式以 Pod 形式部署在叢集中,請參閱從 Pod 內部存取 API

Python 用戶端

若要使用 Python 用戶端,請執行以下命令:pip install kubernetes。請參閱 Python 用戶端程式庫頁面 以取得更多安裝選項。

Python 用戶端可以使用與 kubectl CLI 相同的 kubeconfig 檔案,以定位 API 伺服器並對其進行身份驗證。請參閱此範例

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))

Java 用戶端

若要安裝 Java 用戶端,請執行

# Clone java library
git clone --recursive https://github.com/kubernetes-client/java

# Installing project artifacts, POM etc:
cd java
mvn install

請參閱 https://github.com/kubernetes-client/java/releases 以查看支援的版本。

Java 用戶端可以使用與 kubectl CLI 相同的 kubeconfig 檔案,以定位 API 伺服器並對其進行身份驗證。請參閱此範例

package io.kubernetes.client.examples;

import io.kubernetes.client.ApiClient;
import io.kubernetes.client.ApiException;
import io.kubernetes.client.Configuration;
import io.kubernetes.client.apis.CoreV1Api;
import io.kubernetes.client.models.V1Pod;
import io.kubernetes.client.models.V1PodList;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import java.io.FileReader;
import java.io.IOException;

/**
 * A simple example of how to use the Java API from an application outside a kubernetes cluster
 *
 * <p>Easiest way to run this: mvn exec:java
 * -Dexec.mainClass="io.kubernetes.client.examples.KubeConfigFileClientExample"
 *
 */
public class KubeConfigFileClientExample {
  public static void main(String[] args) throws IOException, ApiException {

    // file path to your KubeConfig
    String kubeConfigPath = "~/.kube/config";

    // loading the out-of-cluster config, a kubeconfig from file-system
    ApiClient client =
        ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();

    // set the global default api-client to the in-cluster one from above
    Configuration.setDefaultApiClient(client);

    // the CoreV1Api loads default api-client from global configuration.
    CoreV1Api api = new CoreV1Api();

    // invokes the CoreV1Api client
    V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
    System.out.println("Listing all pods: ");
    for (V1Pod item : list.getItems()) {
      System.out.println(item.getMetadata().getName());
    }
  }
}

dotnet 用戶端

若要使用 dotnet 用戶端,請執行以下命令:dotnet add package KubernetesClient --version 1.6.1。請參閱 dotnet 用戶端程式庫頁面 以取得更多安裝選項。請參閱 https://github.com/kubernetes-client/csharp/releases 以查看支援的版本。

dotnet 用戶端可以使用與 kubectl CLI 相同的 kubeconfig 檔案,以定位 API 伺服器並對其進行身份驗證。請參閱此範例

using System;
using k8s;

namespace simple
{
    internal class PodList
    {
        private static void Main(string[] args)
        {
            var config = KubernetesClientConfiguration.BuildDefaultConfig();
            IKubernetes client = new Kubernetes(config);
            Console.WriteLine("Starting Request!");

            var list = client.ListNamespacedPod("default");
            foreach (var item in list.Items)
            {
                Console.WriteLine(item.Metadata.Name);
            }
            if (list.Items.Count == 0)
            {
                Console.WriteLine("Empty!");
            }
        }
    }
}

JavaScript 用戶端

若要安裝 JavaScript 用戶端,請執行以下命令:npm install @kubernetes/client-node。請參閱 https://github.com/kubernetes-client/javascript/releases 以查看支援的版本。

JavaScript 用戶端可以使用與 kubectl CLI 相同的 kubeconfig 檔案,以定位 API 伺服器並對其進行身份驗證。請參閱此範例

const k8s = require('@kubernetes/client-node');

const kc = new k8s.KubeConfig();
kc.loadFromDefault();

const k8sApi = kc.makeApiClient(k8s.CoreV1Api);

k8sApi.listNamespacedPod('default').then((res) => {
    console.log(res.body);
});

Haskell 用戶端

請參閱 https://github.com/kubernetes-client/haskell/releases 以查看支援的版本。

Haskell 用戶端可以使用與 kubectl CLI 相同的 kubeconfig 檔案,以定位 API 伺服器並對其進行身份驗證。請參閱此範例

exampleWithKubeConfig :: IO ()
exampleWithKubeConfig = do
    oidcCache <- atomically $ newTVar $ Map.fromList []
    (mgr, kcfg) <- mkKubeClientConfig oidcCache $ KubeConfigFile "/path/to/kubeconfig"
    dispatchMime
            mgr
            kcfg
            (CoreV1.listPodForAllNamespaces (Accept MimeJSON))
        >>= print

下一步

上次修改時間:2023 年 12 月 06 日,上午 9:05 PST:Clean up change-default-storage-class.md (d1d6eda640)