How to Detect EKS, GKE, and AKS in Your Application
In modern cloud-native application development, it’s essential to understand the environment where your application is running, especially when working with container orchestration platforms like Kubernetes. Platforms such as EKS (Amazon Elastic Kubernetes Service), GKE (Google Kubernetes Engine), and AKS (Azure Kubernetes Service) have their own unique markers for detection. This blog will guide you through how to programmatically detect these platforms in your application.
1. Detecting AWS EKS (Elastic Kubernetes Service)
AWS EKS is a managed Kubernetes service provided by Amazon. Here’s how you can detect if your application is running on EKS:
private static boolean isEKS() {
String awsExecutionEnv = System.getenv("AWS_EXECUTION_ENV");
return awsExecutionEnv != null && awsExecutionEnv.contains("EKS");
}
2. Detecting GKE (Google Kubernetes Engine)
Google Kubernetes Engine is Google Cloud’s managed Kubernetes platform. Here’s how you can detect if you are running on GKE:
private static boolean isGKE() {
try {
URL url = new URL("http://metadata.google.internal/computeMetadata/v1/instance/attributes/cluster-name");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Metadata-Flavor", "Google");
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
return connection.getResponseCode() == 200;
} catch (IOException e) {
return false; // Not running on GKE
}
}
3. Detecting AKS (Azure Kubernetes Service)
Azure Kubernetes Service is Microsoft Azure’s managed Kubernetes platform. Here’s how to detect AKS:
private static boolean isAKS() {
try {
URL url = new URL("http://169.254.169.254/metadata/instance");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Metadata", "true");
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
return connection.getResponseCode() == 200;
} catch (IOException e) {
return false; // Not running on AKS
}
}
4. Detecting Generic Kubernetes
If your application runs on Kubernetes but the platform (EKS, GKE, or AKS) isn’t specified, you can still detect Kubernetes itself.
private static boolean isKubernetes() {
return new File("/var/run/secrets/kubernetes.io/serviceaccount/token").exists();
}