I want C# code to connect to a K8s cluster and for now just list the namespaces. The following C# code I tried works, and connects to a Kubernetes cluster, but it only works when "SkipTlsVerify = true". When I set SkipTlsVerify to false I get the following error:
Unhandled exception: k8s.Exceptions.KubeConfigException: A CA must be set when SkipTlsVerify === false
I don't want to skip TLS verification. How can I provide the necessary CA information to the C# Kubernetes Client to enable TLS verification?
I don't want to use BuildConfigFromConfigFile(). None of this can reach into a file system to read or write a file. For now all I can use is local variables
I tried this at first, and it works, but it's skipping TLS verification:
var contextName = "mycontext, i copied this from my kubeconfig file"
var server = "https://...*** copied from 'server' in kubeconfig file *** "
var config = new KubernetesClientConfiguration()
{
Host = server,
AccessToken = accessToken,
SkipTlsVerify = true,
};
var client = new Kubernetes(config);
var namespaces = client.CoreV1.ListNamespace();
foreach (var ns in namespaces)
{
Console.WriteLine(ns.Name());
}
I also tried the following code, and got the same error message result. The following code works, unless config.SkipTlsVerify is set to false. The inner SkipTlsVerify has no effect, but the outer SkipTlsVerify does affect the result. I assume that the "ClientCertificateKeyData" C# field matches to the "client-key-data" in my kubeconfig file.
var clientCertificateData = "*** copied and pasted from client-certificate-data in kube-config ****";
var clientKeyData = "*** copied from client-key-data in kube-config ****";
var certificateAuthorityData = "...copied from certificate-authority-data in kube-config"
var config = KubernetesClientConfiguration.BuildConfigFromConfigObject(new K8SConfiguration
{
ApiVersion = "v1",
Clusters = new List<Cluster>
{
new()
{
ClusterEndpoint = new ClusterEndpoint
{
CertificateAuthorityData = certificateAuthorityData,
Server = server,
//SkipTlsVerify = true // This one has no effect. I still get the same
//error even when setting this to true
},
Name = contextName
}
}
}, masterUrl: server); // I think it's a little strange that I need to put in server here
// If I omit masterUrl, i get the error
//"k8s.Exceptions.KubeConfigException:
// Cannot infer server host url either from context or masterUrl"
//config.SkipTlsVerify = true; // uncommenting this makes it work
config.Host = server;
config.AccessToken = accessToken;
config.ClientCertificateData = clientCertificateData;
config.ClientCertificateKeyData = clientKeyData; // I assume this line is supposed to be client-key-data from the kubeconfig?
var client2 = new Kubernetes(config);
var namespaces2 = client2.CoreV1.ListNamespace();
foreach (var ns in namespaces2)
{
Console.WriteLine(ns.Name());
}