Home Explore Blog Models CI



docker

2nd chunk of `content/manuals/extensions/extensions-sdk/guides/kubernetes.md`
46a1d555eac72e7d0a86d5ccad81c5cbb3998714c928b3500000000100000855
The following code snippets have been put together in the [Kubernetes Sample Extension](https://github.com/docker/extensions-sdk/tree/main/samples/kubernetes-sample-extension). It shows how to interact with a Kubernetes cluster by shipping the `kubectl` command-line tool.

### Check the Kubernetes API server is reachable

Once the `kubectl` command-line tool is added to the extension image in the `Dockerfile`, and defined in the `metadata.json`, the Extensions framework deploys `kubectl` to the users' host when the extension is installed.

You can use the JS API `ddClient.extension.host?.cli.exec` to issue `kubectl` commands to, for instance, check whether the Kubernetes API server is reachable given a specific context:

```typescript
const output = await ddClient.extension.host?.cli.exec("kubectl", [
  "cluster-info",
  "--request-timeout",
  "2s",
  "--context",
  "docker-desktop",
]);
```

### List Kubernetes contexts

```typescript
const output = await ddClient.extension.host?.cli.exec("kubectl", [
  "config",
  "view",
  "-o",
  "jsonpath='{.contexts}'",
]);
```

### List Kubernetes namespaces

```typescript
const output = await ddClient.extension.host?.cli.exec("kubectl", [
  "get",
  "namespaces",
  "--no-headers",
  "-o",
  'custom-columns=":metadata.name"',
  "--context",
  "docker-desktop",
]);
```

## Persisting the kubeconfig file

Below there are different ways to persist and read the `kubeconfig` file from the host filesystem. Users can add, edit, or remove Kubernetes context to the `kubeconfig` file at any time.

> Warning
>
> The `kubeconfig` file is very sensitive and if found can give an attacker administrative access to the Kubernetes Cluster.

### Extension's backend container

If you need your extension to persist the `kubeconfig` file after it's been read, you can have a backend container that exposes an HTTP POST endpoint to store the content of the file either in memory or somewhere within the container filesystem. This way, if the user navigates out of the extension to another part of Docker Desktop and then comes back, you don't need to read the `kubeconfig` file again.

Title: Examples of Interacting with Kubernetes and Persisting kubeconfig
Summary
This section provides code examples of how to interact with a Kubernetes cluster from a Docker Extension using the `kubectl` command-line tool. It demonstrates how to check the Kubernetes API server, list Kubernetes contexts and namespaces. It also discusses methods for persisting the kubeconfig file within the extension, such as using the extension's backend container, while emphasizing the security considerations of storing the sensitive kubeconfig file.