c# - 从 C# 中的 pod 访问 Kubernetes API

标签 c# .net kubernetes kubernetes-apiserver

我正在寻找一种轻量级的方法来从 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 .curl 的示例和 kubectl proxy - 响应为 json 格式。
curl http://localhost:8080/api/v1/pods
复杂的因素是您可能需要一个私有(private)证书包,出于安全原因正确验证它是一种很好的做法。当accessing来自 Pod 的 API,客户端证书位于 /var/run/secrets/kubernetes.io/serviceaccount/ca.crt此外,您需要使用位于 /var/run/secrets/kubernetes.io/serviceaccount/token 上的 token 进行身份验证。

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


您从客户端库中获得的是:
  • 使用证书和 token 实现身份验证
  • 键入的客户端访问 - 而不是手动代码 url 和请求

  • dotnet-client示例显示了“在默认命名空间中列出 Pod”的“类型化客户端访问”的样子(参见 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);
    }
    

    关于c# - 从 C# 中的 pod 访问 Kubernetes API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66092203/

    相关文章:

    c# - 使用 WCF 和 C# 进行远程登录

    .net - 使用多线程加速 .NET 反射

    kubernetes - Kubernetes在Rancher上-入口路径问题

    kubernetes - 节点在尝试加入具有 `kubeadm` 的集群时未获得证书

    c# - 如何明智地使用 StringBuilder?

    python - isinstance() 意外返回 False

    c# - 无需手动多次循环即可将文本添加到列表所有项目的所有属性

    c# - 如何使用 XAML 将 DatagridComboBoxColumn 绑定(bind)到不在 DataGrid 的 ItemsSource 中的 ViewModel 属性?

    c# - 编写 PowerShell Cmdlet 时如何处理路径?

    .net - Visual Studio 默认按钮属性