# Kubernetes (Service Account)

{% hint style="info" %}
For an overview of the available Kubernetes features and supported platforms, please see our [Kubernetes guide](/admin/resources/clusters.md).
{% endhint %}

## Overview

This guide describes how to set up a Kubernetes cluster in StrongDM with the credentials of a Kubernetes service account. This process involves setting up a Kubernetes cluster, generating a permanent service account token, and using that token to configure a new Kubernetes (Service Account) cluster in the StrongDM Admin UI. When done with this guide, you will be able to use StrongDM to connect to a Kubernetes cluster with the credentials of a Kubernetes service account.

{% hint style="info" %}
If you would like to learn more about how to enable automatic resource discovery within your Kubernetes cluster, or use privilege levels to allow users to request various levels of access to the Kubernetes cluster, please read the [Kubernetes Discovery and Privilege Levels](/admin/resources/clusters/kubernetes-management.md) section to learn more about those features prior to following this configuration guide.
{% endhint %}

## Prerequisites

Ensure that the API server you intend to add to StrongDM is accessible from your StrongDM nodes (gateways, relays, or proxy clusters). See our guide on [Nodes](/admin/networking/gateways-and-relays.md) for more information.

{% hint style="info" %}
If you are using kubectl 1.30 or higher, it will default to using websockets, which the StrongDM client did not support prior to version 45.35.0. This can be remedied by taking one of the following actions:

* Update your client to version 45.35.0 or greater.
* Set the environment variable `KUBECTL_REMOTE_COMMAND_WEBSOCKETS=false` to restore the previous behavior in your kubectl.
  {% endhint %}

## Configure the Kubernetes Cluster

Before you can add the cluster to your StrongDM environment, you need to set up the cluster itself. Follow these steps to configure your cluster.

1. Create a ServiceAccount:

   ```yaml
   kubectl create serviceaccount <serviceaccount-name>
   ```
2. Create a Role or ClusterRole.

{% hint style="info" %}
The permissions given in this Role are exactly what StrongDM users get when they connect to this resource.
{% endhint %}

The following example ClusterRole gives blanket permissions to the whole cluster:

```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
  name: <clusterrolebinding-name>
rules:
  - apiGroups:
      - '*'
    resources:
      - '*'
    verbs:
      - '*'
  - nonResourceURLs:
      - '*'
    verbs:
      - '*'
```

3. Create a RoleBinding or ClusterRoleBinding to associate the Role or ClusterRole with the ServiceAccount.

   To create a RoleBinding:

   ```yaml
   kubectl create rolebinding <rolebinding-name> --role <role-name> --serviceaccount <serviceaccount-name>
   ```

   To create a ClusterRoleBinding:

   ```yaml
   kubectl create clusterrolebinding <clusterrolebinding-name> --clusterrole <clusterrole-name> --serviceaccount <serviceaccount-name>
   ```
4. Create a Secret to manually generate a permanent token.

{% hint style="info" %}
In this step, you manually create a token secret that the kube-apiserver detects and then populates with a token associated with the ServiceAccount. This secret (and token) does not expire. For reference, please see the Kubernetes documentation, [Configure Service Accounts for Pods](https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#manually-create-a-long-lived-api-token-for-a-serviceaccount).
{% endhint %}

1. First save and complete the following yaml template:

   ```yaml
   apiVersion: v1
   kind: Secret
   metadata:
     name: build-robot-secret
     annotations:
       kubernetes.io/service-account.name: <serviceaccount-name>
   type: kubernetes.io/service-account-token
   ```
2. Run:

   ```yaml
   kubectl apply -f template.yaml
   ```
3. If not done already, obtain the generated token by inspecting the Secret just created.

   ```yaml
   kubectl get secret spirit -o json | jq -r '.data.token'
   ```
4. Save the token in a safe place, as you will need it when adding your resource in the StrongDM Admin UI next.

{% hint style="info" %}
There are alternative ways to generate tokens, other than the manual way described in this guide. However, such ways typically yield temporary tokens, which may adversely affect resource registration. For example, if the following command is used to get a token directly to stdout, the `--duration` flag may not be respected:

`kubectl create token <serviceaccount-name> --duration <duration> | pbcopy`
{% endhint %}

## Resource Configuration in StrongDM

This section provides instructions for adding the resource in either the StrongDM Admin UI, CLI, Terraform provider, or SDKs.

{% tabs %}
{% tab title="Admin UI" %}
**Set up and Manage With the Admin UI**

If using the Admin UI to add the resource to StrongDM, use the following steps.

1. Log in to the StrongDM Admin UI and go to **Resources** > **Managed Resources**.
2. Click **Add Resource**.
3. For **Resource Type**, select **Kubernetes (Service Account)**.
4. For **API Token**, set the token that you generated and saved in the previous section of this guide.
5. Set all other required [resource properties](#resource-properties) to configure how the StrongDM node connects.
6. Click **Create** to save the resource.

The Admin UI updates and shows your new cluster in a healthy or unhealthy state. Healthy indicates a successful connection. If it is unhealthy, click into the cluster's name and view the **Diagnostics** tab to determine where the connection is failing.
{% endtab %}

{% tab title="CLI" %}
**Set up and Manage With the CLI**

This section provides general steps on how to configure and manage the resource using the StrongDM CLI. For more information and examples, please see the [CLI Reference](https://docs.strongdm.com/references/cli) documentation.

1. In your terminal or Command Prompt, log in to StrongDM:

   ```sh
   sdm login
   ```
2. Run `sdm admin clusters add`` ``k8s-service --help` to view the help text for the command, which shows you how to use the command and what options (properties) are available. Note which [properties](#resource-properties) are required and collect the values for them.

   ```sh
   NAME:
      sdm admin clusters add k8s-service - create Kubernetes (Service Account) cluster

   USAGE:
      sdm admin clusters add k8s-service [command options] <name>

   OPTIONS:
      --allow-resource-role-bypass                 (For legacy orgs) allows users to fallback to the existing authentication mode (Leased Credential or Identity Set) when a resource role is not provided.
      --api-token value                            (required, secret)
      --bind-interface value                       IP address on which to listen for connections to this resource on clients. Specify "default", "loopback", or "vnm" to automatically allocate an available address from the corresponding IP range configured in the organization. (default: "default")
      --discovery-enabled                          Enable discovery for the cluster.
      --discovery-username value                   The user to impersonate in the cluster when running discovery. Required if the cluster is configured for identity aliases. (conditional)
      --egress-filter value                        apply filter to select egress nodes e.g. 'field:name tag:key=value ...'
      --healthcheck-namespace default              This path will be used to check the health of your connection.  Defaults to default.
      --hostname value                             (required)
      --identity-alias-healthcheck-username value  (conditional)
      --identity-set-id value                      
      --identity-set-name value                    set the identity set by name
      --port value                                 (required) (default: 443)
      --port-override value                        Port on which to listen for connections to this resource on clients. Specify "-1" to automatically allocate an available port. (default: -1)
      --proxy-cluster-id value                     proxy cluster id
      --secret-store-id value                      secret store id
      --subdomain value, --bind-subdomain value    DNS subdomain through which this resource may be accessed on clients (e.g. "app-prod" allows the resource to be accessed as "app-prod.<your-org-name>.<sdm-proxy-domain>"). Only applicable to HTTP-based resources or resources using virtual networking mode.
      --tags value                                 tags e.g. 'key=value,...'
      --template, -t                               display a JSON template
      --timeout value                              set time limit for command
   ```
3. Then run `sdm admin clusters add`` ``k8s-service <RESOURCE_NAME>` and set all required properties with their values. For example:

   ```sh
   sdm admin clusters add k8s-service "k8s-service-prod"
     --hostname "k8s-prod01.acme.internal"
     --port 443
     --api-token "eyJhbGciOiJSUzI1NiIsImtpZCI6..."
     --identity-set-name "K8s Cluster Admins"
     --identity-alias-healthcheck-username "svc_k8s_health"
     --discovery-enabled
     --discovery-username "sdm-discovery"
     --healthcheck-namespace "default"
     --bind-interface "default"
     --port-override -1
     --egress-filter "field:name tag:env=prod tag:region=us-west"
     --proxy-cluster-id "plc_0123456789abcdef"
     --secret-store-id "ss_abcdef0123456789"
     --subdomain "k8s-service-prod01"
     --tags "env=prod,platform=kubernetes,auth=service-account,team=devops"
     --timeout 30
   ```
4. Check that the resource has been added. The output of the following command should show the resource's name:

   ```sh
   sdm admin clusters list
   ```

{% endtab %}

{% tab title="Terraform" %}
**Set up and Manage With Terraform**

This section provides an example of how to configure and manage the resource using the Terraform provider. For more information and examples, please see the [Terraform provider](https://github.com/strongdm/terraform-provider-sdm) documentation.

```hcl
# Install StrongDM provider
terraform {
  required_providers {
    sdm = {
      source  = "strongdm/sdm"
      version = "16.5.0"
    }
  }
}

# Configure StrongDM provider
provider "sdm" {
  # Add API access key and secret key from the Admin UI
  api_access_key = "njjSn...5hM"
  api_secret_key = "ziG...="
}

# Create Kubernetes (Service Account) cluster
resource "sdm_resource" "k8s_service_cluster_prod" {
  k8s_service {
    # Required
    name      = "k8s-service-cluster-prod"          # <name>
    hostname  = "k8s-prod01.acme.internal"          # --hostname
    port      = 443                                 # --port (default 443)
    api_token = "eyJhbGciOiJSUzI1NiIsImtpZCI6..."   # --api-token (use secret store in production)

    # Identity & discovery
    identity_set_name                   = "K8s Service Account Admins" # --identity-set-name
    identity_alias_healthcheck_username = "svc_k8s_health"             # --identity-alias-healthcheck-username (conditional)
    discovery_enabled                   = true                         # --discovery-enabled
    discovery_username                  = "sdm-discovery"              # --discovery-username
    healthcheck_namespace               = "default"                    # --healthcheck-namespace

    # Common networking options
    bind_interface = "default"                                        # --bind-interface ("default" | "loopback" | "vnm")
    port_override  = -1                                               # --port-override (-1 = auto-allocate)
    egress_filter  = "field:name tag:env=prod tag:region=us-west"     # --egress-filter
    subdomain      = "k8s-service-prod01"                             # --subdomain / --bind-subdomain (for VN access)

    # Optional integrations
    proxy_cluster_id = "plc_0123456789abcdef"                         # --proxy-cluster-id
    secret_store_id  = "ss_abcdef0123456789"                          # --secret-store-id (recommended for tokens)

    # (Legacy orgs) allow fallback auth when no resource role is provided
    allow_resource_role_bypass = false                                # --allow-resource-role-bypass

    # Tags
    tags = {                                                          # --tags
      env      = "prod"
      platform = "kubernetes"
      auth     = "service-account"
      team     = "devops"
    }
  }
}
```

{% endtab %}

{% tab title="SDKs" %}
**Set up and Manage With SDKs**

In addition to the Admin UI, CLI, and Terraform, you may configure and manage your resource with any of the following SDK options: Go, Java, Python, and Ruby. Please see the following references for more information and examples.

| Go            | ​[pkg.go.dev](https://pkg.go.dev/github.com/strongdm/strongdm-sdk-go/v17)​ | ​[strongdm-sdk-go](https://github.com/strongdm/strongdm-sdk-go)​         | ​[Go SDK Examples](https://github.com/strongdm/strongdm-sdk-go-examples)​         |
| ------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------- |
| Java          | ​[javadoc](https://strongdm.github.io/strongdm-sdk-java-docs/)​            | ​[strongdm-sdk-java](https://github.com/strongdm/strongdm-sdk-java)​     | ​[Java SDK Examples](https://github.com/strongdm/strongdm-sdk-java-examples)​     |
| Python        | ​[pdocs](https://strongdm.github.io/strongdm-sdk-python-docs/)​            | ​[strongdm-sdk-python](https://github.com/strongdm/strongdm-sdk-python)​ | ​[Python SDK Examples](https://github.com/strongdm/strongdm-sdk-python-examples)​ |
| Ruby          | ​[RubyDoc](https://www.rubydoc.info/gems/strongdm)​                        | ​[strongdm-sdk-ruby](https://github.com/strongdm/strongdm-sdk-ruby)​     | ​[Ruby SDK Examples](https://github.com/strongdm/strongdm-sdk-ruby-examples)​     |
| {% endtab %}  |                                                                            |                                                                          |                                                                                   |
| {% endtabs %} |                                                                            |                                                                          |                                                                                   |

## Resource Properties

The following table describes the configuration properties available for your Kubernetes (Service Account) cluster.

<table><thead><tr><th width="200.1824951171875">Property</th><th width="129.7401123046875">Requirement</th><th>Description</th></tr></thead><tbody><tr><td><strong>Display Name</strong></td><td>Required</td><td>Meaningful name to display the resource throughout StrongDM; exclude special characters like quotes (") or angle brackets (&#x3C; or >)</td></tr><tr><td><strong>Cluster Type</strong></td><td>Required</td><td><strong>Kubernetes (Service Account)</strong></td></tr><tr><td><strong>Proxy Cluster</strong></td><td>Required</td><td>Defaults to "None (use gateways)"; if using <a href="/pages/UPxilwQwoQwFOlrkBP47">proxy clusters</a>, select the appropriate cluster to proxy traffic to this resource</td></tr><tr><td><strong>Hostname</strong></td><td>Required</td><td>Hostname or IP address of the API server, such as <code>api.aks.example.com</code>; relay server should be able to <a href="#prerequisites">connect to your target server</a> or hostname</td></tr><tr><td><strong>Port</strong></td><td>Required</td><td>Port to connect to the API server; default port value <strong>443</strong></td></tr><tr><td><strong>Connectivity Mode</strong></td><td>Required</td><td>Select either <strong>Virtual Networking Mode</strong>, which lets users connect to the resource with a software-defined, IP-based network; or <strong>Loopback Mode</strong>, which allows users to connect to the resource using the local loopback adapter in their operating system; this field is shown if <a href="/pages/lNQp0yqAK0qXnqCStPcb">Virtual Networking Mode</a> enabled for your organization</td></tr><tr><td><strong>IP Address</strong></td><td>Optional</td><td>If <strong>Virtual Networking Mode</strong> is the selected connectivity mode, an IP address value in the configured Virtual Networking Mode subnet in the organization network settings; if <strong>Loopback Mode</strong> is the selected connectivity mode, an IP address value in the configured Loopback IP range in the organization network settings (by default, <code>127.0.0.1</code>); if not specified, an available IP address in the configured IP address space for the selected connectivity mode will be automatically assigned; this field is shown if <a href="/pages/lNQp0yqAK0qXnqCStPcb">Virtual Networking Mode</a> and/or <a href="/pages/RlpqrMxEZ1S3YOOA4Kpi">multi-loopback mode</a> is enabled for your organization</td></tr><tr><td><strong>Port Override</strong></td><td>Optional</td><td>If <strong>Virtual Networking Mode</strong> is the selected connectivity mode, a port value between 1 and 65535 that is not already in use by another resource with the same IP address; if <strong>Loopback Mode</strong> is the selected connectivity mode, a port value between 1024 to 64999 that is not already in use by another resource with the same IP address; when left empty with Virtual Networking Mode, the system assigns the default port to this resource; when left empty for Loopback Mode, an available port that is not already in use by another resource is assigned; preferred port also can be modified later from the <a href="/pages/ux26VjQ6BPsV3H8wjn1v">Port Overrides settings</a></td></tr><tr><td><strong>DNS</strong></td><td>Optional</td><td>If Virtual Networking Mode is the selected connectivity mode, a unique hostname alias for this resource; when set, causes the desktop app to display this resource's human-readable DNS name (for example, <code>k8s.my-organization-name</code>) instead of the bind address that includes IP address and port (for example, <code>100.64.100.100:5432</code>)</td></tr><tr><td><strong>Secret Store</strong></td><td>Optional</td><td>Credential store location; defaults to none (credentials are stored in StrongDM resource configuration); to learn more, see <a href="#secret-store">Secret Store options</a></td></tr><tr><td><strong>API Token</strong></td><td>Required</td><td>Permanent token associated with the ServiceAccount on the Kubernetes cluster</td></tr><tr><td><strong>Healthcheck Namespace</strong></td><td>Optional</td><td>If enabled for your organization, the namespace used for the resource healthcheck; defaults to <code>default</code> if empty; supplied credentials must have the rights to perform one of the following kubectl commands in the specified namespace: <code>get pods</code>, <code>get deployments</code>, or <code>describe namespace</code></td></tr><tr><td><strong>API Token</strong></td><td>Required</td><td>Permanent token associated with the ServiceAccount on the Kubernetes cluster</td></tr><tr><td><strong>Authentication</strong></td><td>Required</td><td>Authentication method to access the cluster; select either <strong>Leased Credential</strong> (default) or <strong>Identity Aliases</strong> (to use the Identity Aliases of StrongDM users to access the cluster)</td></tr><tr><td><strong>Identity Set</strong></td><td>Required</td><td>Displays if <strong>Authentication</strong> is set to <strong>Identity Aliases</strong>; select an Identity Set name from the list</td></tr><tr><td><strong>Healthcheck Username</strong></td><td>Required</td><td>If <strong>Authentication</strong> is set to <strong>Identity Aliases</strong>, the username that should be used to verify StrongDM's connection to it; username must already exist on the target cluster</td></tr><tr><td><strong>Resource Tags</strong></td><td>Optional</td><td>Resource <a data-mention href="/spaces/4XOJmXFslCMVCzIG2rKp/pages/anUqbOAAmDPD3e0fF6GO">/spaces/4XOJmXFslCMVCzIG2rKp/pages/anUqbOAAmDPD3e0fF6GO</a> consisting of key-value pairs <code>&#x3C;KEY>=&#x3C;VALUE></code> (for example, <code>env=dev</code>)</td></tr></tbody></table>

### **Display name**

Some Kubernetes management interfaces, such as Visual Studio Code, do not properly render cluster names containing spaces. If you run into problems, please choose a **Display Name** without spaces.

### **Secret Store**

By default, server credentials are stored in StrongDM. However, these credentials can also be saved in a secrets management tool.

Non-StrongDM options appear in the **Secret Store** dropdown if they are created under **Settings** > **Secrets Management**. When you select another Secret Store type, its unique properties display. For more details, see [Configure Secret Store Integrations](/admin/access/secret-stores.md).

## Test the Connection

1. After creating the Kubernetes (Service Account) cluster resource in the Admin UI, navigate to **Infrastructure > Clusters** and locate your newly added cluster. The health indicator should turn green once connectivity and token authentication are validated.
2. On a test client using the StrongDM Desktop App or CLI, connect to the cluster and run a basic command such as:\\

   ```bash
   kubectl get pods --namespace default
   ```
3. Confirm the command returns resources and the connection is routed through StrongDM.
4. If discovery is enabled, in the Admin UI verify that namespaces, roles, and service accounts appear under the cluster’s **Discovery** tab. This indicates StrongDM successfully queried the Kubernetes API.
5. If the health status remains red or yellow:
   * Verify the cluster’s hostname and port are correct and that the API endpoint is reachable from your relay or gateway.
   * Check that the service account token is valid and has sufficient permissions to access the API.
   * Confirm the `healthcheck_namespace` exists and the user specified in `identity_alias_healthcheck_username` has the appropriate access.
   * Review the **Diagnostics** tab for authentication or network error logs.

Once connectivity is verified and you can successfully run Kubernetes commands, the cluster resource is ready. You can then assign roles, apply policies, and monitor access through StrongDM.

## Help

If you encounter issues, please consult the [StrongDM Help Center](https://help.strongdm.com/hc/en-us).

Be prepared to provide the following information to StrongDM Support, so that they can inspect logs and confirm node and resource health:

* Resource name or ID
* CLI error output or logs
* Node name and region
* Timestamps of failed attempts


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.strongdm.com/admin/resources/clusters/kubernetes-service-account.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
