11using System ;
22using System . IO ;
3+ using System . Security . Cryptography . X509Certificates ;
34using k8s ;
5+ using k8s . Authentication ;
46
57namespace Octopus . Tentacle . Kubernetes
68{
79 class LocalMachineKubernetesClientConfigProvider : IKubernetesClientConfigProvider
810 {
11+ const string ServiceAccountTokenKeyFileName = "token" ;
12+ const string ServiceAccountRootCAKeyFileName = "ca.crt" ;
13+
914 public KubernetesClientConfiguration Get ( )
1015 {
1116#if DEBUG
17+ var telepresenceRoot = Environment . GetEnvironmentVariable ( "TELEPRESENCE_ROOT" ) ;
18+ if ( ! string . IsNullOrEmpty ( telepresenceRoot ) )
19+ {
20+ return GetTelepresenceConfig ( telepresenceRoot ) ;
21+ }
1222 var kubeConfigEnvVar = Environment . GetEnvironmentVariable ( "KUBECONFIG" ) ;
1323 if ( kubeConfigEnvVar != null && ! Path . IsPathRooted ( kubeConfigEnvVar ) )
1424 {
@@ -29,5 +39,45 @@ public KubernetesClientConfiguration Get()
2939 throw new NotSupportedException ( "Local machine configuration is only supported when debugging." ) ;
3040#endif
3141 }
42+
43+ KubernetesClientConfiguration GetTelepresenceConfig ( string telepresenceRoot )
44+ {
45+ var serviceAccountPath =
46+ Path . Combine ( new string [ ]
47+ {
48+ $ "{ telepresenceRoot } ", "var" , "run" , "secrets" , "kubernetes.io" , "serviceaccount" ,
49+ } ) ;
50+ var rootCAFile = Path . Combine ( serviceAccountPath , ServiceAccountRootCAKeyFileName ) ;
51+ var host = Environment . GetEnvironmentVariable ( "KUBERNETES_SERVICE_HOST" ) ;
52+ var port = Environment . GetEnvironmentVariable ( "KUBERNETES_SERVICE_PORT" ) ;
53+ if ( string . IsNullOrEmpty ( host ) )
54+ {
55+ host = "kubernetes.default.svc" ;
56+ }
57+
58+ if ( string . IsNullOrEmpty ( port ) )
59+ {
60+ port = "443" ;
61+ }
62+
63+ X509Certificate2Collection certificates = new X509Certificate2Collection ( ) ;
64+ certificates . Import ( rootCAFile ) ;
65+
66+ var result = new KubernetesClientConfiguration
67+ {
68+ Host = new UriBuilder ( "https" , host , Convert . ToInt32 ( port ) ) . ToString ( ) ,
69+ TokenProvider = new TokenFileAuth ( Path . Combine ( serviceAccountPath , ServiceAccountTokenKeyFileName ) ) ,
70+ SslCaCerts = certificates ,
71+ } ;
72+
73+ var namespaceVar = Environment . GetEnvironmentVariable ( "OCTOPUS__K8STENTACLE__NAMESPACE" ) ;
74+
75+ if ( ! string . IsNullOrEmpty ( namespaceVar ) )
76+ {
77+ result . Namespace = namespaceVar ;
78+ }
79+
80+ return result ;
81+ }
3282 }
3383}
0 commit comments