k9s

repository·master·Indexed 12 days ago

https://github.com/derailed/k9s

A terminal UI for managing Kubernetes clusters, designed to simplify navigating, observing, and managing applications through continuous monitoring and interactive commands. It features a colon-based command mode for resource navigation, regex and label filtering, and a plugin system to extend functionality via external CLI tools like kubectl, helm, and argo.

Tokens
16K
Snippets
42
Records
55
Agent score
99%

What's inside k9s

  1. Extend K9s with Plugins

    master

    K9s allows you to extend its functionality by defining custom cluster commands as plugins. Plugins are loaded from several locations, primarily $XDG_CONFIG_HOME/k9s/plugins.yaml or directories like $XDG_CONFIG_HOME/k9s/plugins and $XDG_DATA_HOME/k9s/plugins.

    A plugin definition includes:

    • shortCut: The key combination to trigger the plugin (e.g., [a-z], Shift-[A-Z], Ctrl-[A-Z]).
    • description: Text displayed in the K9s menu next to the shortcut.
    • scopes: A list of resource names/short-names (e.g., pods, svc) where the plugin is active. Use all for all views.
    • command: The executable to run.
    • args: Arguments passed to the command.
    • background: Boolean indicating if the command runs in the background.
    • confirm: If enabled, prompts the user to confirm before execution.
    • override: If true, overrides the default action for that shortcut.
    • dangerous: If true, allows the plugin to run even in read-only mode.
    • overwriteOutput: Allows providing custom messages on plugin stdout.
    plugins:
      fred:
        shortCut: Ctrl-L
        description: Pod logs
        scopes:
        - pods
        command: kubectl
        args:
        - logs
        - -f
        - $NAME
        - -n
        - $NAMESPACE
  2. Extend K9s functionality with community plugins

    master

    K9s plugins allow you to extend the tool's capabilities by adding custom actions to specific Kubernetes views. These plugins can trigger external CLI tools (like kubectl plugins, helm, argo, etc.) to help you observe or administer your clusters more efficiently.

    Each plugin is defined by a YAML file that specifies:

    • Available on Views: The specific K9s resource views where the plugin action is accessible.
    • Shortcut: The keyboard shortcut used to trigger the plugin action.
    • External Dependencies: Any required CLI tools or kubectl plugins that must be installed on your system for the plugin to function.
  3. Configure Plugin Inputs

    master

    Plugins can prompt users for dynamic values (up to 5 inputs) before execution. These values are accessed in the args section using the syntax $INPUT_<NAME> (where <NAME> is the uppercase version of the input name).

    Supported Input Types:

    • string: Free-form text field.
    • number: Numeric input with validation.
    • bool: Boolean toggle (checkbox).
    • dropdown: Selection from a predefined list of options.

    Input Properties:

    • name (required): The identifier used for referencing.
    • type (required): string, number, bool, or dropdown.
    • label: The UI label shown to the user.
    • required: Boolean; if true, execution is blocked until a value is provided.
    • default: Pre-filled value (must match the type).
    inputs:
      - name: message
        label: Enter a message
        type: string
        required: true
        default: hello world
      - name: environment
        label: Select environment
        type: dropdown
        required: true
        default: staging
        options:
          - development
          - staging
          - production
  4. Configure Popeye cluster sanitization

    master

    K9s integrates with Popeye. While Popeye uses spinach.yml, you can provide cluster-specific configurations by placing the file at: $XDG_CONFIG_HOME/share/k9s/clusters/clusterX/contextY/spinach.yml

  5. Manage K9s logs and debug mode

    master

    K9s produces logs to a specific location. You can find this location using k9s info. To troubleshoot, you can run K9s in debug mode or redirect logs to a custom destination.

    # Start K9s in debug mode
    k9s -l debug
    
    # Customize logs destination via argument
    k9s --logFile /tmp/k9s.log
    
    # Customize logs destination via environment variable
    K9S_LOGS_DIR=/var/log k9s
  6. Locate and manage K9s configuration files

    master

    K9s stores configurations as YAML files in a k9s directory. The exact location depends on your operating system and follows XDG specifications. You can verify your current configuration paths by running k9s info. To override the configuration directory, set the K9S_CONFIG_DIR environment variable.

    Default Locations:

    • Unix: ~/.config/k9s
    • macOS: ~/Library/Application Support/k9s
    • Windows: %LOCALAPPDATA%\k9s
    k9s info
  7. Define Command Aliases

    master

    You can create custom shortnames for Kubernetes resources by creating an aliases.yaml file in your K9s configuration directory ($XDG_DATA_HOME/k9s/aliases.yaml).

    An alias maps a shortname to a GVR (Group/Version/Resource) or even another command alias.

    Example usage:

    • If you define pp: v1/pods, typing :pp in K9s command mode will switch to the pods view.
    # $XDG_DATA_HOME/k9s/aliases.yaml
    aliases:
      pp: v1/pods
      crb: rbac.authorization.k8s.io/v1/clusterrolebindings
      fred: pod fred app=blee
  8. Customize resource table columns with Custom Views

    master

    You can customize which columns are displayed for specific Kubernetes resources by creating a configuration file at $XDG_CONFIG_HOME/k9s/views.yaml. This file uses GVR (Group/Version/Resource) to map views to resources.

    Column Syntax

    COLUMN_NAME<:json_parse_expression><|column_attributes>

    • :json_parse_expression: An optional expression (similar to kubectl -o custom-columns) to extract data from the resource manifest.
    • |column_attributes: Optional attributes to tailor rendering:
      • T: Time column indicator
      • N: Number column indicator
      • W: Wide column (only visible in wide mode)
      • S: Show (ensures column is visible and not wide, overrides standard wide behavior)
      • H: Hide the column
      • L: Left align (default)
      • R: Right align

    Important: Column definitions containing non-alpha characters must be wrapped in single or double quotes as valid YAML strings. Errors in specification are surfaced in the K9s logs.

    # $XDG_CONFIG_HOME/k9s/views.yaml
    views:
      v1/pods:
        columns:
          - AGE
          - NAMESPACE|WR                                     # Right aligned, wide mode only
          - ZORG:.metadata.labels.fred\.io\.kubernetes\.blee # JSON path extraction
          - BLEE:.metadata.annotations.blee|R                # Extract annotation and right align
          - NAME
          - IP
          - NODE
          - STATUS
          - READY
          - MEM/RL|S                                         # Force show (override wide default)
          - '%MEM/R|'                                        # Quoted for non-alpha chars
    
      v1/pods@fred:                                          # Specific namespace
        columns:
          - AGE
          - NAME|WR
    
      v1/pods@kube*:                                         # Namespace regex
        columns:
          - NAME
          - AGE
          - LABELS
    
      cool-kid:                                              # Reference an alias
        columns:
          - AGE
          - NAMESPACE|WR
  9. Use the Node Shell feature

    master

    If the nodeShell feature gate is enabled on a cluster, you can shell into nodes by selecting the s (shell) menu option in the node view.

    Enabling Node Shell:

    1. Enable the feature gate in your cluster configuration file ($XDG_DATA_HOME/k9s/clusters/cluster-1/context-1) by setting featureGates.nodeShell: true.
    2. Alternatively, override all clusters globally using the environment variable K9S_FEATURE_GATE_NODE_SHELL=true|false.

    Customizing the Shell Pod: You can customize the image, namespace, and resource limits for the shell pod in your global config.yaml under the shellPod key. You can also mount volumes (like the Docker socket) using hostPathVolume.

    # Cluster configuration
    k9s:
      featureGates:
        nodeShell: true
    
    # Global config.yaml customization
    k9s:
      shellPod:
        image: cool_kid_admin:42
        namespace: blee
        limits:
          cpu: 100m
          memory: 100Mi
        hostPathVolume:
        - name: docker-socket
          mountPath: /var/run/docker.sock
          hostPath: /var/run/docker.sock
          readOnly: true
  10. Define custom Resource Jumps

    master

    K9s allows you to define custom jump shortcuts between Custom Resource Definitions (CRDs) and their related resources. This enables you to jump from a parent resource to its dependent resources (e.g., from a custom operator resource to its managed jobs) by pressing Enter on a selected item.

    Create a configuration file at $XDG_CONFIG_HOME/k9s/jumps.yaml.

    Configuration Fields

    • Source GVR (Map Key): The group/version/resource of the source resource.
    • targetGVR: The Group/Version/Resource to jump to.
    • labelSelector (optional): Kubernetes label selector using Go template syntax to filter targets.
    • fieldSelector (optional): Kubernetes field selector using Go template syntax. Note that K9s applies this as a local (client-side) filter, meaning it can match any field path in the target object's manifest, not just API-selectable fields.
    • targetNamespace (optional):
      • Empty (default): Use the source resource's namespace.
      • all: View resources across all namespaces.
      • <namespace-name>: Jump to a specific namespace.
      • {{.spec.field}}: Use a template expression to extract the namespace from the source resource.

    Template Syntax

    Use Go template syntax (e.g., {{.metadata.name}}, {{.spec.fieldName}}) to dynamically reference fields from the source resource within your selectors.

    # $XDG_CONFIG_HOME/k9s/jumps.yaml
    jumps:
      # Jump between custom operator resources
      "myoperator.io/v1/patchplans":
        targetGVR: "myoperator.io/v1/patchjobs"
        fieldSelector: "spec.patchPlanRef={{.metadata.name}}"
    
      # Jump from ArgoCD Application to Deployments
      "argoproj.io/v1alpha1/applications":
        targetGVR: "apps/v1/deployments"
        labelSelector: "app.kubernetes.io/instance={{.metadata.name}}"
    
      # Jump from Karpenter NodePool to Nodes (cluster-scoped)
      "karpenter.sh/v1/nodepools":
        targetGVR: "v1/nodes"
        labelSelector: "karpenter.sh/nodepool={{.metadata.name}}"
        targetNamespace: "all"
  11. Configure RBAC for K9s Namespace Access

    master

    If users are constrained to specific namespaces, K9s requires a Role within those namespaces to enable read access to namespaced resources.

    A suggested Role provides RO access to:

    • Most namespaced resources (via apiGroups: ["", "apps", "autoscaling", "batch", "extensions"] and resources: ["*"])
    • Metric server resources (pods, nodes in metrics.k8s.io)

    You must then create a RoleBinding within that namespace to assign the role to your users.

    # K9s Reader Role (default namespace)
    kind: Role
    apiVersion: rbac.authorization.k8s.io/v1
    metadata:
      name: k9s
      namespace: default
    rules:
      # Grants RO access to most namespaced resources
      - apiGroups: ["", "apps", "autoscaling", "batch", "extensions"]
        resources: ["*"]
        verbs: ["get", "list", "watch"]
      # Grants RO access to metric server
      - apiGroups: ["metrics.k8s.io"]
        resources: ["pods", "nodes"]
        verbs:
          - get
          - list
          - watch
    
    ---
    # Sample K9s user RoleBinding
    apiVersion: rbac.authorization.k8s.io/v1
    kind: RoleBinding
    metadata:
      name: k9s
      namespace: default
    subjects:
      - kind: User
        name: fernand
        apiGroup: rbac.authorization.k8s.io
    roleRef:
      kind: Role
      name: k9s
      apiGroup: rbac.authorization.k8s.io
  12. Navigate and view Kubernetes resources in K9s

    master

    K9s uses a colon (:) command mode to navigate between different Kubernetes resources. You can use singular names, plural names, short-names, or aliases.

    Resource Navigation Patterns

    • Basic View: :resource (e.g., :pod or :pods)
    • Namespace Filtering: :resource ns-name (e.g., :pod ns-x)
    • String Filtering: :resource /filter (e.g., :pod /fred to view pods filtered by 'fred')
    • Label Filtering: :resource label=value (e.g., :pod app=fred,env=dev)
    • Context Switching: :resource @context (e.g., :pod @ctx1 to view pods in context ctx1 and switch the K9s context)

    Context and Namespace Switching

    • Switch Contexts: :ctx (to view/switch contexts) or :ctx context-name (to switch directly).
    • Switch Namespaces: :ns (to view/switch namespaces).
    • Warp to Namespace: Press w when the namespace column is visible to jump to that namespace.
    :pod          # View pods
    :pod ns-x     # View pods in namespace x
    :pod /fred    # View pods filtered by 'fred'
    :pod app=fred # View pods with label app=fred
    :pod @ctx1    # View pods in context ctx1 and switch context