通过 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
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"]);
}
}