How to get Kubernetes cluster name from K8s API
Asked Answered
M

18

110

As stated in the title, is it possible to find out a K8s cluster name from the API? I looked around the API and could not find it.

Misgovern answered 7/7, 2016 at 9:33 Comment(0)
C
60

Unfortunately a cluster doesn't know its own name, or anything else that would uniquely identify it (K8s issue #44954). I wanted to know for helm issue #2055.

Update: A common workaround is to create a ConfigMap containing the cluster name and read that when required (#2055 comment 1244537799).

apiVersion: v1
kind: ConfigMap
metadata:
  name: cluster-info
  namespace: kube-system
data:
  cluster-name: foo
Calliecalligraphy answered 27/4, 2017 at 21:1 Comment(1)
This answer should be at the top.. Most answers here are fetching the info from kube-config file which is misleading.Antitoxic
M
80

kubectl config current-context does the trick (it outputs little bit more, like project name, region, etc., but it should give you the answer you need).

Marenmarena answered 22/10, 2018 at 13:45 Comment(5)
The context name can be renamed manually and therefore unreliable.Tansey
@AkihiroHARAI yes you can rename it manually. But: a) why would you do that? b) running gcloud container clusters get-credentials sets the context back.Marenmarena
I wonder why this answer has so many upvotes. config current-context doesn't do any k8s API calls, it just reads locally stored kubectl config (which is not even, strictly speaking, a part of kubernetes, just a client for its apis).Tyrocidine
@Tyrocidine because question has tag "google-kubernetes-engine" and this solves problem of finding which cluster you are connected to on GKEMarenmarena
@usamec, the question was about kubernetes API. Executing kubectl, which will likely won't be even installed in a POD with a running application is very far from kubernetes API. By this logic I could also suggest to the topic starter to open a browser, navigate to google console and check cluster name in GKE UI.Tyrocidine
C
60

Unfortunately a cluster doesn't know its own name, or anything else that would uniquely identify it (K8s issue #44954). I wanted to know for helm issue #2055.

Update: A common workaround is to create a ConfigMap containing the cluster name and read that when required (#2055 comment 1244537799).

apiVersion: v1
kind: ConfigMap
metadata:
  name: cluster-info
  namespace: kube-system
data:
  cluster-name: foo
Calliecalligraphy answered 27/4, 2017 at 21:1 Comment(1)
This answer should be at the top.. Most answers here are fetching the info from kube-config file which is misleading.Antitoxic
K
37

There is no way to get the name via K8s API. But here is a one-liner in case the name you have in your .kube/config file is enough for you (if you download it from your cloud provider the names should match):

kubectl config view --minify -o jsonpath='{.clusters[].name}'

Note 1: The --minify is key here so it will output the name of your current context only. There are other similar answers posted here but without the "minify" you will be listing other contexts in your config that might confuse you.

Note 2: The name in your .kube/config might not reflect the name in your cloud provider, if the file was autogenerated by the cloud provider the names should match, if you configured it manually you could have typed any name just for local config.

Note 3: Do not rely on kubectl config current-context this returns just the name of the context, not the name of the cluster.

Kerek answered 23/6, 2020 at 19:21 Comment(1)
pratical and fast, ty!Salable
R
26

I dont believe there is a k8s cluster name. This command could provide some nice informations

kubectl cluster-info

Repose answered 7/7, 2016 at 22:29 Comment(1)
I'm sorry I downvoted for kubectl cluster-info not returning a name. Here, take the bounty instead. See https://mcmap.net/q/194866/-how-to-get-kubernetes-cluster-name-from-k8s-api for the kubernetes ticket.Calliecalligraphy
G
15

The question is not really well described. However, if this question is related to Google Container Engine then as coreypobrien mentioned the name of cluster is stored in custom metadata of nodes. From inside a node, run the following command and the output will be name of cluster:

curl http://metadata/computeMetadata/v1/instance/attributes/cluster-name -H "Metadata-Flavor: Google"

If you specify your use case, I might be able to extend my answer to cover it.

Glossotomy answered 28/4, 2017 at 2:39 Comment(5)
This is great. Thanks !Cookie
Any way to do this inside an Amazon EKS Cluster?Exudation
How do you make this call using the k8s.io/client-go? Tried to use the RESTClient() unsuccessfullySplashdown
Hi, where can I find the documentation for this? I can find the metadata documentation, but nothing specific about GKE and "cluster-name" for example. Can I also get the project name?Promycelium
@Promycelium looks like you can list the other available commands by shortening it to curl http://metadata/computeMetadata/v1/instance/attributes/ -H "Metadata-Flavor: Google"Clostridium
C
14

The kubernetes API doesn't know much about the GKE cluster name, but you can easily get the cluster name from the Google metatdata server like this

kubectl run curl --rm --restart=Never -it --image=appropriate/curl -- -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/attributes/cluster-name
Clot answered 27/4, 2017 at 12:29 Comment(3)
This is the answer I have been looking for all day; I needed to see the full list of instance attributes available. kubectl run curl --rm --restart=Never -it --image=appropriate/curl -- -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/attributes/Eigenfunction
how can I avoid having kubectl print "pod curl deleted" at the end?Waynant
Add --quiet after run. The entire command would be kubectl run --quiet curl --rm --restart=Never -it --image=appropriate/curl -- -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/attributes/cluster-name > cluster_name. @AlexFlintTansey
L
12

It is the same as getting the current config, but the below command gives clear output:

kubectl config view

Lomond answered 16/7, 2019 at 8:53 Comment(1)
This was useful for me! I ran kubectl config view -o json. I was then able to determine my "current-cluster" by using the current context and mapping that to the contexts to get the current cluster name. Thanks!Udelle
E
5

This command will Check all possible clusters, as you know .KUBECONFIG may have multiple contexts

kubectl config view -o jsonpath='{"Cluster name\tServer\n"}{range .clusters[*]}{.name}{"\t"}{.cluster.server}{"\n"}{end}'

And you will get output like

Cluster name    Server
kubernetes      https://localhost:6443
Exigible answered 18/11, 2019 at 6:5 Comment(0)
F
3

For clusters that were installed using kubeadm, the configuration stored in the kubeadm-config configmap has the cluster name used when installing the cluster.

$ kubectl -n kube-system get configmap kubeadm-config -o yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: kubeadm-config
  namespace: kube-system
data:
  ClusterConfiguration: |
    clusterName: NAME_OF_CLUSTER

For clusters that are using CoreDNS for their DNS, the "cluster name" from kubeadm is also used as the domain suffix.

$ kubectl -n kube-system get configmap coredns -o yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: coredns
  namespace: kube-system
data:
  Corefile: |
    .:53 {
        kubernetes NAME_OF_CLUSTER.local in-addr.arpa ip6.arpa {
Fasciate answered 15/4, 2019 at 8:8 Comment(0)
F
3

at-least for kubespray clusters, the following works for me

kubectl config current-context | cut -d '@' -f2
Finical answered 28/7, 2021 at 21:57 Comment(2)
This is the context name, as defined in your client .kube/config: completely arbitrary. Should be the case from a master node, using /etc/kubernetes/admin.conf, as deployed by Kubespray -- which I hope you're not using on your own client. In general, I would agree with the already-accepted answer: https://mcmap.net/q/194866/-how-to-get-kubernetes-cluster-name-from-k8s-apiMeshach
I agree with the accepted answer, what I have shared is just a mere workaround. The config I had tested was generated by kubespray ansible on my client. It might be root config but the context I was using this command is to set up the cluster/admin work so should be fine either way.Finical
M
1

Well this returns precisely one thing, a cluster name

K8s: kubectl config view -o jsonpath='{.clusters[].name}{"\n"}'

Openshift: oc config view -o jsonpath='{.clusters[].name}{"\n"}'

Marutani answered 2/6, 2020 at 7:6 Comment(1)
This is incorrect! it just return the FIRST cluster name. This may be diffrent than the cluster of the curent context.Mandibular
S
1

The solution I found was to read the current context from kubeConfig object. For example, using NPM @kubernetes/client-node:

const k8s = require('@kubernetes/client-node');
const kubeConfig = new k8s.KubeConfig();
kubeConfig.loadFromFile(process.env.KUBECONFIG_PATH);
clusterName = kubeConfig.getCurrentContext();
Selector answered 4/10, 2023 at 5:35 Comment(0)
D
0

$ kubectl config get-clusters --> get you the list of existing clusters

Desma answered 28/12, 2017 at 17:39 Comment(0)
C
0

Using python k8s client. But this won't work with incluster_kubeconfig.

from kubernetes import config

cluster_context = config.kube_config.list_kube_config_contexts()
print (cluster_context)
([{'context': {'cluster': 'k01.test.use1.aws.platform.gov', 'user': 'k01-test'}, 'name': 'k01.test.use1.aws.platform.gov'}], {'context': {'cluster': 'k01.test.use1.aws.platform.gov', 'user': 'k01-test'}, 'name': 'k01.test.use1.aws.platform.gov'})

cluster_name = cluster_context[1]['context']['cluster']
print (cluster_name)
k01.test.use1.aws.platform.gov
Carousel answered 12/6, 2021 at 18:34 Comment(0)
A
0

Using kubectl command:

$ kubectl config get-clusters
NAME
kubernetes
Antevert answered 23/10, 2021 at 10:44 Comment(0)
M
0
kubectl config get-clusters
    
kubectl config get-contexts
Myriapod answered 2/8, 2022 at 18:54 Comment(0)
C
0

There is a great tool called kubectx https://github.com/ahmetb/kubectx.

kubectx - lists all previously added clusters and highlights the currently used one. This is only one word to type instead of kubectl config current-context.

kubectx <cluster> - switches to a chosen cluster.

Moreover this tool comes also with kubens which does exactly the same for namespaces:

kubens - lists all namespaces and shows the current one,

kubens <namespace> - switches to a chosen namespace.

Conservationist answered 24/11, 2022 at 11:41 Comment(0)
Q
0

For AWS EKS, we can get it via user-data, Run below from pod with ec2 instance metadata access available -

curl -s http://169.254.169.254/latest/user-data | grep /etc/eks/bootstrap.sh | awk '{print $2}'

EKS node's user-data runs a script named /etc/eks/bootstrap.sh with 1st argument as EKS cluster name, which we can use.

Quadrature answered 22/4, 2024 at 7:46 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.