Skip to main content
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:
ClusterActionGenerateKubeconfig = "generateKubeconfig"
The output type (defined in /home/daytona/workspace/source/pkg/apis/management.cattle.io/v3/cluster_types.go:321):
type GenerateKubeConfigOutput struct {
    Config string  // Base64-encoded kubeconfig YAML
}

Generating Kubeconfig

Via Rancher UI

2
  • Go to Cluster Management
  • Locate your cluster in the list
  • Click the menu next to the cluster name
  • Select Download KubeConfig
  • 3
    Save the File
    4
  • The kubeconfig file downloads automatically
  • Save to ~/.kube/config or a custom location
  • Verify the file contains valid YAML
  • 5
    Use with kubectl
    6
    # 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
    

    Via Rancher API

    Generate kubeconfig via API:
    curl -X POST \
      'https://{RANCHER_URL}/v3/clusters/{CLUSTER_ID}?action=generateKubeconfig' \
      -H 'Authorization: Bearer {TOKEN}' \
      -H 'Content-Type: application/json'
    
    Response:
    {
      "config": "apiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: LS0t...",
      "type": "generateKubeconfigOutput"
    }
    
    Decode and save:
    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.
    1
    User Authentication
    2
  • Extract user identity from the API request
  • Verify user has access to the cluster
  • Determine authentication strategy based on cluster configuration
  • 3
    Token Generation
    4
    If token-based authentication is enabled (settings.KubeconfigGenerateToken.Get() == "true"):
    5
  • Create token: Generate a new kubeconfig token for the user
  • Token type: Token is marked with kind: "kubeconfig"
  • Token name: Prefixed with kubeconfig-{username}
  • Token TTL: Uses default TTL from settings.KubeconfigDefaultTokenTTLMilliSeconds
  • Token scope: Scoped to the user’s permissions
  • 6
    Token creation is handled differently based on the cluster’s local authentication endpoint configuration:
    7
  • Local auth enabled: Cluster-specific token via ensureClusterToken()
  • Local auth disabled: Global token via ensureToken()
  • 8
    Kubeconfig Assembly
    9
    The kubeconfig structure varies based on cluster type:
    10
    With local cluster auth endpoint (defined at /home/daytona/workspace/source/pkg/apis/management.cattle.io/v3/cluster_types.go:385):
    11
    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}
    
    12
    Without local cluster auth (proxied through Rancher):
    13
    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}
    
    14
    Token Properties
    15
    Tokens generated for kubeconfig files:
    16
  • 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
  • Access Patterns

    Direct Cluster Access

    When clusters have Local Cluster Auth Endpoint enabled:
    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:
    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:
    kubectl delete token {TOKEN_NAME}
    
    Or via Rancher UI:
    1. Navigate to API & Keys
    2. Find the token
    3. Click Delete
    Deleting a token immediately invalidates all kubeconfig files using that token.

    Token Rotation

    Rotate tokens periodically for security:
    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

    Token TTL Configuration

    Configure default token TTL (Time To Live):
    # 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

    # 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

    # 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

    # 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

    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

    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
      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:
    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