首页 新闻 会员 周边 捐助

请问在 ASP.NET Core 中如何直接读取 Kubernetes ConfigMap 中的配置

0
悬赏园豆:30 [待解决问题]

请问在 ASP.NET Core 中如何通过 C# 代码直接读取 Kubernetes ConfigMap 中的配置?

dudu的主页 dudu | 高人七级 | 园豆:30778
提问于:2021-01-22 18:46
< >
分享
所有回答(1)
1

通过 Kubernetes C# Client 可以读取,控制台代码如下:

using System;
using k8s;

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

            var cm = client.ReadNamespacedConfigMap("appsettings.shared.json", "production");
            Console.WriteLine(cm.Data["appsettings.shared.json"]);
        }
    }
}

需要安装 nuget 包 KubernetesClient

dotnet add package KubernetesClient
dudu | 园豆:30778 (高人七级) | 2021-01-22 21:39

ASP.NET Core 中的读取代码如下

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var env = hostingContext.HostingEnvironment;
                    config.AddJsonFile("appsettings.json", optional: true)
                        .AddJsonStream(new MemoryStream(ReadK8sConfigMap()))
                        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

                    config.AddEnvironmentVariables();
                });

                webBuilder.UseStartup<Startup>();
            });

    private static byte[] ReadK8sConfigMap()
    {
        var config = KubernetesClientConfiguration.InClusterConfig();
        IKubernetes client = new Kubernetes(config);

        var cm = client.ReadNamespacedConfigMap("appsettings.shared.json", "production");
        return System.Text.Encoding.UTF8.GetBytes(cm.Data["appsettings.shared.json"]);
    }
}
支持(0) 反对(0) dudu | 园豆:30778 (高人七级) | 2021-01-22 22:59
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册