从 C# 中的 pod 访问 Kubernetes API

Access Kubernetes API from a pod in C#

我正在寻找一种从 C# 应用程序中的 Pod 访问 Kubernetes API 的轻量级方法。

Kubernetes 文档提到了两种方式 accessing the API from a Pod:

  1. Run kubectl proxy in a sidecar container in the pod, or as a background process within the container

这通常有效,并且允许仅用一两行代码轻松击中 API 端点 - 示例:

using System;
using System.Net;

namespace GetIngresses
{
    class Program
    {
        static void Main(string[] args)
        {
            var apiBaseUrl = "http://127.0.0.1:8001"; // requires kubectl proxy
            Console.WriteLine((new WebClient()).
             DownloadString($"{apiBaseUrl}/apis/networking.k8s.io/v1/ingresses"));
        }
    }
}

但是,现在有一个 运行 kubectl proxy 流程来监控、维护等 - 这似乎不适合生产。

  1. Use the Go client library, and create a client using the rest.InClusterConfig() and kubernetes.NewForConfig() functions. They handle locating and authenticating to the apiserver.

我的应用程序是用 C# 而不是 Go 编写的。有一个 C# client library 大概可以达到同样的目的。但是,我真的必须为了对单个端点进行简单的 GET 操作而带上整个客户端库吗?

理想情况下,我只想使用 WebClient,如上例所示。文档提到

The recommended way to locate the apiserver within the pod is with the kubernetes.default.svc DNS name, which resolves to a Service IP which in turn will be routed to an apiserver.

所以,在上面的例子中,我可以这样做吗...

var apiBaseUrl = "http://kubernetes.default.svc"

...并获取 WebClient 以传递所需的服务帐户凭据?如果是,如何?

Ideally, I'd like to just use WebClient

Kubernetes 是一个 REST API,所以这可行。如 Directly accessing the REST API using kubectl proxy 所示,使用例如 API 很容易探索curl.

curlkubectl proxy 的示例 - 响应采用 json 格式。

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

复杂的因素是您可能需要一个私有证书包,出于安全原因,最好对其进行正确验证。当 accessing 来自 Pod 的 API 时,客户端证书位于 /var/run/secrets/kubernetes.io/serviceaccount/ca.crt 上,此外,您需要使用位于 /var/run/secrets/kubernetes.io/serviceaccount/token

上的令牌进行身份验证

But do I really have to bring a whole client library on board just for a simple GET to a single endpoint?

您从客户端库中得到的是:

  • 使用证书和令牌实施身份验证
  • 键入客户端访问 - 而不是手动代码 url 和请求

dotnet-client example shows how the "Typed client access" looks like, for "listing Pods in the default namespace" (see authentication alternatives):

var config = KubernetesClientConfiguration.InClusterConfig()  // auth from Pod
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);
}