> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/rancher/rancher/llms.txt
> Use this file to discover all available pages before exploring further.

# Kubeconfig Access

> Generate kubeconfig files for kubectl access to clusters managed by Rancher

Rancher provides the ability to generate kubeconfig files for accessing Kubernetes clusters with kubectl. These kubeconfig files can be configured for direct cluster access or proxied access through Rancher.

## Overview

Kubeconfig files contain:

* Cluster API server endpoints
* Authentication credentials (tokens or certificates)
* Cluster CA certificates for TLS verification
* Context configuration for kubectl

Rancher-generated kubeconfig files enable:

* kubectl CLI access to managed clusters
* Programmatic API access via client libraries
* Integration with CI/CD pipelines
* Development tooling and IDE integrations

## Cluster Action

The kubeconfig generation action is defined in `/home/daytona/workspace/source/pkg/apis/management.cattle.io/v3/cluster_types.go:30`:

```go theme={null}
ClusterActionGenerateKubeconfig = "generateKubeconfig"
```

The output type (defined in `/home/daytona/workspace/source/pkg/apis/management.cattle.io/v3/cluster_types.go:321`):

```go theme={null}
type GenerateKubeConfigOutput struct {
    Config string  // Base64-encoded kubeconfig YAML
}
```

## Generating Kubeconfig

### Via Rancher UI

<Steps>
  ### Navigate to Cluster

  1. Go to **Cluster Management**
  2. Locate your cluster in the list
  3. Click the **⋮** menu next to the cluster name
  4. Select **Download KubeConfig**

  ### Save the File

  1. The kubeconfig file downloads automatically
  2. Save to `~/.kube/config` or a custom location
  3. Verify the file contains valid YAML

  ### Use with kubectl

  ```bash theme={null}
  # Use default location
  mv ~/Downloads/kubeconfig ~/.kube/config

  # Or specify custom location
  export KUBECONFIG=~/Downloads/{cluster-name}.yaml

  # Verify connectivity
  kubectl cluster-info
  kubectl get nodes
  ```
</Steps>

### Via Rancher API

Generate kubeconfig via API:

```bash theme={null}
curl -X POST \
  'https://{RANCHER_URL}/v3/clusters/{CLUSTER_ID}?action=generateKubeconfig' \
  -H 'Authorization: Bearer {TOKEN}' \
  -H 'Content-Type: application/json'
```

Response:

```json theme={null}
{
  "config": "apiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: LS0t...",
  "type": "generateKubeconfigOutput"
}
```

Decode and save:

```bash theme={null}
curl -X POST ... | jq -r '.config' > kubeconfig.yaml
```

## Kubeconfig Generation Process

The generation is implemented in `/home/daytona/workspace/source/pkg/api/norman/customization/cluster/actions_kubeconfig.go:17`.

<Steps>
  ### User Authentication

  1. Extract user identity from the API request
  2. Verify user has access to the cluster
  3. Determine authentication strategy based on cluster configuration

  ### Token Generation

  If token-based authentication is enabled (`settings.KubeconfigGenerateToken.Get() == "true"`):

  1. **Create token**: Generate a new kubeconfig token for the user
  2. **Token type**: Token is marked with `kind: "kubeconfig"`
  3. **Token name**: Prefixed with `kubeconfig-{username}`
  4. **Token TTL**: Uses default TTL from `settings.KubeconfigDefaultTokenTTLMilliSeconds`
  5. **Token scope**: Scoped to the user's permissions

  Token creation is handled differently based on the cluster's local authentication endpoint configuration:

  * **Local auth enabled**: Cluster-specific token via `ensureClusterToken()`
  * **Local auth disabled**: Global token via `ensureToken()`

  ### Kubeconfig Assembly

  The kubeconfig structure varies based on cluster type:

  **With local cluster auth endpoint** (defined at `/home/daytona/workspace/source/pkg/apis/management.cattle.io/v3/cluster_types.go:385`):

  ```yaml theme={null}
  apiVersion: v1
  kind: Config
  clusters:
  - cluster:
      certificate-authority-data: {CLUSTER_CA}
      server: https://{NODE_IP}:6443
    name: {CLUSTER_NAME}
  contexts:
  - context:
      cluster: {CLUSTER_NAME}
      user: {CLUSTER_NAME}
    name: {CLUSTER_NAME}
  current-context: {CLUSTER_NAME}
  users:
  - name: {CLUSTER_NAME}
    user:
      token: {TOKEN}
  ```

  **Without local cluster auth** (proxied through Rancher):

  ```yaml theme={null}
  apiVersion: v1
  kind: Config
  clusters:
  - cluster:
      certificate-authority-data: {RANCHER_CA}
      server: https://{RANCHER_URL}/k8s/clusters/{CLUSTER_ID}
    name: {CLUSTER_NAME}
  contexts:
  - context:
      cluster: {CLUSTER_NAME}
      user: {CLUSTER_NAME}
    name: {CLUSTER_NAME}
  current-context: {CLUSTER_NAME}
  users:
  - name: {CLUSTER_NAME}
    user:
      token: {TOKEN}
  ```

  ### Token Properties

  Tokens generated for kubeconfig files:

  * **Non-expiring** (by default) or with configured TTL
  * **User-scoped**: Inherit the user's RBAC permissions
  * **Revocable**: Can be deleted from Rancher UI or API
  * **Labeled**: Identifiable as kubeconfig tokens
</Steps>

## Access Patterns

### Direct Cluster Access

When clusters have **Local Cluster Auth Endpoint** enabled:

```go theme={null}
type LocalClusterAuthEndpoint struct {
    Enabled bool    // Enable direct cluster access
    FQDN    string  // Custom FQDN for cluster endpoint
    CACerts string  // Custom CA certificates
}
```

The kubeconfig:

* Points directly to cluster API server (typically `https://{NODE_IP}:6443`)
* Uses cluster's native CA certificates
* Bypasses Rancher for API requests
* Provides lower latency
* Requires network connectivity to cluster nodes

Use cases:

* Accessing clusters from within the same network
* High-performance kubectl operations
* Reducing load on Rancher server

### Proxied Access (Default)

When local auth endpoint is disabled:

The kubeconfig:

* Points to Rancher server endpoint (`https://{RANCHER_URL}/k8s/clusters/{CLUSTER_ID}`)
* Rancher proxies all requests to the cluster
* Uses Rancher's CA certificates
* Works from any location that can reach Rancher
* Requires Rancher to be available

Use cases:

* Accessing clusters across networks/firewalls
* Clusters without publicly accessible API servers
* Centralized audit logging through Rancher
* Consistent access regardless of cluster location

## Token Management

### Listing Tokens

View your kubeconfig tokens:

```bash theme={null}
kubectl get tokens --field-selector=metadata.name=kubeconfig-*
```

Or via Rancher UI:

1. Click your **User Avatar**
2. Select **API & Keys**
3. Filter by **Description**: "Kubeconfig token"

### Revoking Tokens

Remove a kubeconfig token:

```bash theme={null}
kubectl delete token {TOKEN_NAME}
```

Or via Rancher UI:

1. Navigate to **API & Keys**
2. Find the token
3. Click **Delete**

<Warning>
  Deleting a token immediately invalidates all kubeconfig files using that token.
</Warning>

### Token Rotation

Rotate tokens periodically for security:

<Steps>
  1. Generate a new kubeconfig from Rancher
  2. Update your `~/.kube/config` with the new configuration
  3. Verify connectivity: `kubectl cluster-info`
  4. Delete the old token
</Steps>

## Token TTL Configuration

Configure default token TTL (Time To Live):

```bash theme={null}
# Set TTL to 30 days (in milliseconds)
kubectl patch setting kubeconfig-default-token-ttl-minutes \
  --type=merge -p '{"value":"43200"}'

# Disable token expiration (not recommended for production)
kubectl patch setting kubeconfig-generate-token \
  --type=merge -p '{"value":"false"}'
```

Token TTL settings:

* `kubeconfig-generate-token`: Enable/disable token generation (default: `true`)
* `kubeconfig-default-token-ttl-minutes`: Default TTL in minutes

Tokens created before changing TTL settings retain their original expiration.

## Multi-Cluster Access

Manage multiple clusters in a single kubeconfig:

### Merge Kubeconfig Files

```bash theme={null}
# Download multiple cluster kubeconfigs
curl -X POST ... > cluster1.yaml
curl -X POST ... > cluster2.yaml

# Merge into one file
KUBECONFIG=cluster1.yaml:cluster2.yaml kubectl config view \
  --flatten > ~/.kube/config
```

### Switch Contexts

```bash theme={null}
# List available contexts
kubectl config get-contexts

# Switch to a cluster
kubectl config use-context {CLUSTER_NAME}

# Use specific context for one command
kubectl --context={CLUSTER_NAME} get nodes
```

### Set Context Defaults

```bash theme={null}
# Set default namespace
kubectl config set-context --current --namespace={NAMESPACE}

# Rename context for convenience
kubectl config rename-context {OLD_NAME} {NEW_NAME}
```

## Programmatic Access

Use generated kubeconfig with Kubernetes client libraries:

### Go Client

```go theme={null}
import (
    "k8s.io/client-go/tools/clientcmd"
    "k8s.io/client-go/kubernetes"
)

config, err := clientcmd.BuildConfigFromFlags("", "/path/to/kubeconfig")
if err != nil {
    panic(err)
}

clientset, err := kubernetes.NewForConfig(config)
if err != nil {
    panic(err)
}

pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
```

### Python Client

```python theme={null}
from kubernetes import client, config

config.load_kube_config(config_file="/path/to/kubeconfig")
v1 = client.CoreV1Api()

pods = v1.list_namespaced_pod(namespace="default")
for pod in pods.items:
    print(pod.metadata.name)
```

## Security Best Practices

* **Protect kubeconfig files**: Treat as sensitive credentials
* **File permissions**: `chmod 600 ~/.kube/config`
* **No version control**: Never commit kubeconfig to git repositories
* **Token rotation**: Rotate tokens every 30-90 days
* **Minimal scope**: Request tokens with minimum required permissions
* **Audit access**: Monitor token usage in Rancher audit logs
* **Revoke unused tokens**: Clean up old tokens regularly

## Troubleshooting

### "Unable to connect to the server"

* **Network connectivity**: Verify you can reach the cluster endpoint
  ```bash theme={null}
  curl -k https://{CLUSTER_ENDPOINT}
  ```
* **Token expiration**: Generate a new kubeconfig if token expired
* **Rancher availability**: Ensure Rancher server is accessible (for proxied access)

### "Unauthorized" or "Forbidden" errors

* **Token validity**: Verify token hasn't been revoked
* **RBAC permissions**: Check your user's cluster role bindings
* **Cluster access**: Confirm you have permission to access the cluster

Test token:

```bash theme={null}
kubectl auth can-i get pods --all-namespaces
```

### Certificate verification failures

* **CA certificate mismatch**: Regenerate kubeconfig after certificate rotation
* **Custom CA certificates**: Ensure custom CAs are correctly configured
* **Certificate expiration**: Check cluster certificate validity

### Context not found

* **Merged configs**: Verify context exists: `kubectl config get-contexts`
* **File corruption**: Validate YAML syntax: `yamllint ~/.kube/config`
* **Regenerate**: Download a fresh kubeconfig from Rancher

## Related Resources

* [Certificate Rotation](/clusters/operations/certificate-rotation)
* [Importing Clusters](/clusters/importing/import-existing)
* [Cluster API Reference](/api/resources/clusters)
