Access Clusters Using the Kubernetes API

This page shows how to access clusters using the Kubernetes API.

Before you begin

You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:

To check the version, enter kubectl version.

Accessing the Kubernetes API

Accessing for the first time with kubectl

When accessing the Kubernetes API for the first time, use the Kubernetes command-line tool, kubectl.

To access a cluster, you need to know the location of the cluster and have credentials to access it. Typically, this is automatically set-up when you work through a Getting started guide, or someone else setup the cluster and provided you with credentials and a location.

Check the location and credentials that kubectl knows about with this command:

  1. kubectl config view

Many of the examples provide an introduction to using kubectl. Complete documentation is found in the kubectl manual.

Directly accessing the REST API

kubectl handles locating and authenticating to the API server. If you want to directly access the REST API with an http client like curl or wget, or a browser, there are multiple ways you can locate and authenticate against the API server:

  1. Run kubectl in proxy mode (recommended). This method is recommended, since it uses the stored apiserver location and verifies the identity of the API server using a self-signed cert. No man-in-the-middle (MITM) attack is possible using this method.
  2. Alternatively, you can provide the location and credentials directly to the http client. This works with client code that is confused by proxies. To protect against man in the middle attacks, you’ll need to import a root cert into your browser.

Using the Go or Python client libraries provides accessing kubectl in proxy mode.

Using kubectl proxy

The following command runs kubectl in a mode where it acts as a reverse proxy. It handles locating the API server and authenticating.

Run it like this:

  1. kubectl proxy --port=8080 &

See kubectl proxy for more details.

Then you can explore the API with curl, wget, or a browser, like so:

  1. curl http://localhost:8080/api/

The output is similar to this:

  1. {
  2. "versions": [
  3. "v1"
  4. ],
  5. "serverAddressByClientCIDRs": [
  6. {
  7. "clientCIDR": "0.0.0.0/0",
  8. "serverAddress": "10.0.1.149:443"
  9. }
  10. ]
  11. }

Without kubectl proxy

It is possible to avoid using kubectl proxy by passing an authentication token directly to the API server, like this:

Using grep/cut approach:

  1. # Check all possible clusters, as your .KUBECONFIG may have multiple contexts:
  2. kubectl config view -o jsonpath='{"Cluster name\tServer\n"}{range .clusters[*]}{.name}{"\t"}{.cluster.server}{"\n"}{end}'
  3. # Select name of cluster you want to interact with from above output:
  4. export CLUSTER_NAME="some_server_name"
  5. # Point to the API server referring the cluster name
  6. APISERVER=$(kubectl config view -o jsonpath="{.clusters[?(@.name==\"$CLUSTER_NAME\")].cluster.server}")
  7. # Gets the token value
  8. TOKEN=$(kubectl get secrets -o jsonpath="{.items[?(@.metadata.annotations['kubernetes\.io/service-account\.name']=='default')].data.token}"|base64 --decode)
  9. # Explore the API with TOKEN
  10. curl -X GET $APISERVER/api --header "Authorization: Bearer $TOKEN" --insecure

The output is similar to this:

  1. {
  2. "kind": "APIVersions",
  3. "versions": [
  4. "v1"
  5. ],
  6. "serverAddressByClientCIDRs": [
  7. {
  8. "clientCIDR": "0.0.0.0/0",
  9. "serverAddress": "10.0.1.149:443"
  10. }
  11. ]
  12. }

Using jsonpath approach:

  1. APISERVER=$(kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}')
  2. TOKEN=$(kubectl get secret $(kubectl get serviceaccount default -o jsonpath='{.secrets[0].name}') -o jsonpath='{.data.token}' | base64 --decode )
  3. curl $APISERVER/api --header "Authorization: Bearer $TOKEN" --insecure
  4. {
  5. "kind": "APIVersions",
  6. "versions": [
  7. "v1"
  8. ],
  9. "serverAddressByClientCIDRs": [
  10. {
  11. "clientCIDR": "0.0.0.0/0",
  12. "serverAddress": "10.0.1.149:443"
  13. }
  14. ]
  15. }

The above example uses the --insecure flag. This leaves it subject to MITM attacks. When kubectl accesses the cluster it uses a stored root certificate and client certificates to access the server. (These are installed in the ~/.kube directory). Since cluster certificates are typically self-signed, it may take special configuration to get your http client to use root certificate.

On some clusters, the API server does not require authentication; it may serve on localhost, or be protected by a firewall. There is not a standard for this. Controlling Access to the Kubernetes API describes how you can configure this as a cluster administrator.

Programmatic access to the API

Kubernetes officially supports client libraries for Go, Python, Java, dotnet, Javascript, and Haskell. There are other client libraries that are provided and maintained by their authors, not the Kubernetes team. See client libraries for accessing the API from other languages and how they authenticate.

Go client

  • To get the library, run the following command: go get k8s.io/client-go@kubernetes-<kubernetes-version-number> See https://github.com/kubernetes/client-go/releases to see which versions are supported.
  • Write an application atop of the client-go clients.

Note: client-go defines its own API objects, so if needed, import API definitions from client-go rather than from the main repository. For example, import "k8s.io/client-go/kubernetes" is correct.

The Go client can use the same kubeconfig file as the kubectl CLI does to locate and authenticate to the API server. See this example:

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "k8s.io/apimachinery/pkg/apis/meta/v1"
  6. "k8s.io/client-go/kubernetes"
  7. "k8s.io/client-go/tools/clientcmd"
  8. )
  9. func main() {
  10. // uses the current context in kubeconfig
  11. // path-to-kubeconfig -- for example, /root/.kube/config
  12. config, _ := clientcmd.BuildConfigFromFlags("", "<path-to-kubeconfig>")
  13. // creates the clientset
  14. clientset, _ := kubernetes.NewForConfig(config)
  15. // access the API to list pods
  16. pods, _ := clientset.CoreV1().Pods("").List(context.TODO(), v1.ListOptions{})
  17. fmt.Printf("There are %d pods in the cluster\n", len(pods.Items))
  18. }

If the application is deployed as a Pod in the cluster, see Accessing the API from within a Pod.

Python client

To use Python client, run the following command: pip install kubernetes See Python Client Library page for more installation options.

The Python client can use the same kubeconfig file as the kubectl CLI does to locate and authenticate to the API server. See this example:

  1. from kubernetes import client, config
  2. config.load_kube_config()
  3. v1=client.CoreV1Api()
  4. print("Listing pods with their IPs:")
  5. ret = v1.list_pod_for_all_namespaces(watch=False)
  6. for i in ret.items:
  7. print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

Java client

  1. # Clone java library
  2. git clone --recursive https://github.com/kubernetes-client/java
  3. # Installing project artifacts, POM etc:
  4. cd java
  5. mvn install

See https://github.com/kubernetes-client/java/releases to see which versions are supported.

The Java client can use the same kubeconfig file as the kubectl CLI does to locate and authenticate to the API server. See this example:

  1. package io.kubernetes.client.examples;
  2. import io.kubernetes.client.ApiClient;
  3. import io.kubernetes.client.ApiException;
  4. import io.kubernetes.client.Configuration;
  5. import io.kubernetes.client.apis.CoreV1Api;
  6. import io.kubernetes.client.models.V1Pod;
  7. import io.kubernetes.client.models.V1PodList;
  8. import io.kubernetes.client.util.ClientBuilder;
  9. import io.kubernetes.client.util.KubeConfig;
  10. import java.io.FileReader;
  11. import java.io.IOException;
  12. /**
  13. * A simple example of how to use the Java API from an application outside a kubernetes cluster
  14. *
  15. * <p>Easiest way to run this: mvn exec:java
  16. * -Dexec.mainClass="io.kubernetes.client.examples.KubeConfigFileClientExample"
  17. *
  18. */
  19. public class KubeConfigFileClientExample {
  20. public static void main(String[] args) throws IOException, ApiException {
  21. // file path to your KubeConfig
  22. String kubeConfigPath = "~/.kube/config";
  23. // loading the out-of-cluster config, a kubeconfig from file-system
  24. ApiClient client =
  25. ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();
  26. // set the global default api-client to the in-cluster one from above
  27. Configuration.setDefaultApiClient(client);
  28. // the CoreV1Api loads default api-client from global configuration.
  29. CoreV1Api api = new CoreV1Api();
  30. // invokes the CoreV1Api client
  31. V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
  32. System.out.println("Listing all pods: ");
  33. for (V1Pod item : list.getItems()) {
  34. System.out.println(item.getMetadata().getName());
  35. }
  36. }
  37. }

dotnet client

To use dotnet client, run the following command: dotnet add package KubernetesClient --version 1.6.1 See dotnet Client Library page for more installation options. See https://github.com/kubernetes-client/csharp/releases to see which versions are supported.

The dotnet client can use the same kubeconfig file as the kubectl CLI does to locate and authenticate to the API server. See this example:

  1. using System;
  2. using k8s;
  3. namespace simple
  4. {
  5. internal class PodList
  6. {
  7. private static void Main(string[] args)
  8. {
  9. var config = KubernetesClientConfiguration.BuildDefaultConfig();
  10. IKubernetes client = new Kubernetes(config);
  11. Console.WriteLine("Starting Request!");
  12. var list = client.ListNamespacedPod("default");
  13. foreach (var item in list.Items)
  14. {
  15. Console.WriteLine(item.Metadata.Name);
  16. }
  17. if (list.Items.Count == 0)
  18. {
  19. Console.WriteLine("Empty!");
  20. }
  21. }
  22. }
  23. }

JavaScript client

To install JavaScript client, run the following command: npm install @kubernetes/client-node. See https://github.com/kubernetes-client/javascript/releases to see which versions are supported.

The JavaScript client can use the same kubeconfig file as the kubectl CLI does to locate and authenticate to the API server. See this example:

  1. const k8s = require('@kubernetes/client-node');
  2. const kc = new k8s.KubeConfig();
  3. kc.loadFromDefault();
  4. const k8sApi = kc.makeApiClient(k8s.CoreV1Api);
  5. k8sApi.listNamespacedPod('default').then((res) => {
  6. console.log(res.body);
  7. });

Haskell client

See https://github.com/kubernetes-client/haskell/releases to see which versions are supported.

The Haskell client can use the same kubeconfig file as the kubectl CLI does to locate and authenticate to the API server. See this example:

  1. exampleWithKubeConfig :: IO ()
  2. exampleWithKubeConfig = do
  3. oidcCache <- atomically $ newTVar $ Map.fromList []
  4. (mgr, kcfg) <- mkKubeClientConfig oidcCache $ KubeConfigFile "/path/to/kubeconfig"
  5. dispatchMime
  6. mgr
  7. kcfg
  8. (CoreV1.listPodForAllNamespaces (Accept MimeJSON))
  9. >>= print

Accessing the API from within a Pod

When accessing the API from within a Pod, locating and authenticating to the API server are slightly different to the external client case described above.

The easiest way to use the Kubernetes API from a Pod is to use one of the official client libraries. These libraries can automatically discover the API server and authenticate.

Using Official Client Libraries

From within a Pod, the recommended ways to connect to the Kubernetes API are:

  • For a Go client, use the official Go client library. The rest.InClusterConfig() function handles API host discovery and authentication automatically. See an example here.

  • For a Python client, use the official Python client library. The config.load_incluster_config() function handles API host discovery and authentication automatically. See an example here.

  • There are a number of other libraries available, please refer to the Client Libraries page.

In each case, the service account credentials of the Pod are used to communicate securely with the API server.

Directly accessing the REST API

While running in a Pod, the Kubernetes apiserver is accessible via a Service named kubernetes in the default namespace. Therefore, Pods can use the kubernetes.default.svc hostname to query the API server. Official client libraries do this automatically.

The recommended way to authenticate to the API server is with a service account credential. By default, a Pod is associated with a service account, and a credential (token) for that service account is placed into the filesystem tree of each container in that Pod, at /var/run/secrets/kubernetes.io/serviceaccount/token.

If available, a certificate bundle is placed into the filesystem tree of each container at /var/run/secrets/kubernetes.io/serviceaccount/ca.crt, and should be used to verify the serving certificate of the API server.

Finally, the default namespace to be used for namespaced API operations is placed in a file at /var/run/secrets/kubernetes.io/serviceaccount/namespace in each container.

Using kubectl proxy

If you would like to query the API without an official client library, you can run kubectl proxy as the command of a new sidecar container in the Pod. This way, kubectl proxy will authenticate to the API and expose it on the localhost interface of the Pod, so that other containers in the Pod can use it directly.

Without using a proxy

It is possible to avoid using the kubectl proxy by passing the authentication token directly to the API server. The internal certificate secures the connection.

  1. # Point to the internal API server hostname
  2. APISERVER=https://kubernetes.default.svc
  3. # Path to ServiceAccount token
  4. SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount
  5. # Read this Pod's namespace
  6. NAMESPACE=$(cat ${SERVICEACCOUNT}/namespace)
  7. # Read the ServiceAccount bearer token
  8. TOKEN=$(cat ${SERVICEACCOUNT}/token)
  9. # Reference the internal certificate authority (CA)
  10. CACERT=${SERVICEACCOUNT}/ca.crt
  11. # Explore the API with TOKEN
  12. curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" -X GET ${APISERVER}/api

The output will be similar to this:

  1. {
  2. "kind": "APIVersions",
  3. "versions": [
  4. "v1"
  5. ],
  6. "serverAddressByClientCIDRs": [
  7. {
  8. "clientCIDR": "0.0.0.0/0",
  9. "serverAddress": "10.0.1.149:443"
  10. }
  11. ]
  12. }