-
Notifications
You must be signed in to change notification settings - Fork 297
/
KubernetesClientConfiguration.InCluster.cs
79 lines (67 loc) · 3 KB
/
KubernetesClientConfiguration.InCluster.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System.IO;
using k8s.Authentication;
using k8s.Exceptions;
namespace k8s
{
public partial class KubernetesClientConfiguration
{
#pragma warning disable SA1401
// internal for testing
internal static string ServiceAccountPath =
Path.Combine(new string[]
{
$"{Path.DirectorySeparatorChar}var", "run", "secrets", "kubernetes.io", "serviceaccount",
});
#pragma warning restore SA1401
internal const string ServiceAccountTokenKeyFileName = "token";
internal const string ServiceAccountRootCAKeyFileName = "ca.crt";
internal const string ServiceAccountNamespaceFileName = "namespace";
public static bool IsInCluster()
{
var host = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_HOST");
var port = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_PORT");
if (string.IsNullOrEmpty(host) || string.IsNullOrEmpty(port))
{
return false;
}
var tokenPath = Path.Combine(ServiceAccountPath, ServiceAccountTokenKeyFileName);
if (!FileUtils.FileSystem().File.Exists(tokenPath))
{
return false;
}
var certPath = Path.Combine(ServiceAccountPath, ServiceAccountRootCAKeyFileName);
return FileUtils.FileSystem().File.Exists(certPath);
}
public static KubernetesClientConfiguration InClusterConfig()
{
if (!IsInCluster())
{
throw new KubeConfigException(
"Unable to load in-cluster configuration. Missing environment variables KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT or service account token. Hint: consider using option \"automountServiceAccountToken: true\" in deployment declaration.");
}
var rootCAFile = Path.Combine(ServiceAccountPath, ServiceAccountRootCAKeyFileName);
var host = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_HOST");
var port = Environment.GetEnvironmentVariable("KUBERNETES_SERVICE_PORT");
if (string.IsNullOrEmpty(host))
{
host = "kubernetes.default.svc";
}
if (string.IsNullOrEmpty(port))
{
port = "443";
}
var result = new KubernetesClientConfiguration
{
Host = new UriBuilder("https", host, Convert.ToInt32(port)).ToString(),
TokenProvider = new TokenFileAuth(Path.Combine(ServiceAccountPath, ServiceAccountTokenKeyFileName)),
SslCaCerts = CertUtils.LoadPemFileCert(rootCAFile),
};
var namespaceFile = Path.Combine(ServiceAccountPath, ServiceAccountNamespaceFileName);
if (FileUtils.FileSystem().File.Exists(namespaceFile))
{
result.Namespace = FileUtils.FileSystem().File.ReadAllText(namespaceFile);
}
return result;
}
}
}