Rancher CLI

repository·main·Indexed 18 days ago

https://github.com/rancher/cli

A unified command-line tool for interacting with Rancher Server (version 2.x.x). It enables users to manage Rancher resources, including Kubernetes clusters, project contexts, and member roles, via a terminal interface. Key capabilities include cluster creation, importing existing clusters, node registration, and Kubeconfig retrieval.

Tokens
10.8K
Snippets
62
Records
76
Agent score
63%

What's inside rancher-cli

  1. Run Rancher CLI via Docker

    main

    You can run the CLI using a Docker container. To provide authentication, you must mount your local cli2.json configuration file into the container at /home/cli/.rancher/cli2.json using a volume mount.

    To build the rancher/cli Docker image, run make. To build using a custom repository name, use REPO=custom make to produce a custom/cli image.

    docker run --rm -it -v <PATH_TO_CONFIG>:/home/cli/.rancher/cli2.json rancher/cli2 [ARGS]
  2. Set up Rancher CLI with a Rancher Server

    main

    The CLI requires your Rancher Server URL and authentication credentials (API keys). Authentication information is stored in a JSON file named cli2.json, which is automatically created in ~/.rancher/cli2.json the first time you run the rancher login command.

    When providing the server URL, ensure you include the specific port exposed during your Rancher Server installation.

    rancher login https://<RANCHER_SERVER_URL> -t my-secret-token
  3. Build the Rancher CLI from source

    main

    You can build the Rancher CLI binaries using make. The resulting binaries will be located in the /bin directory.

    • Linux: Use make build.
    • macOS: Use CROSS=1 make build to ensure compatibility.
    # For Linux
    make build
    
    # For Mac
    CROSS=1 make build
  4. Token ID prefixing for extension tokens

    main

    When working with tokens issued via the extension API, the CLI uses the ext/ prefix to distinguish them from standard v3 Management tokens.

    • Standard Token: A normal token ID is used for direct v3 Management API lookups.
    • Extension Token: A token ID prefixed with ext/ (e.g., ext/my-token-name) tells the CLI to bypass the v3 API and look up the token directly via the ext.cattle.io/v1 API. The prefix is automatically stripped by the CLI before performing the actual API call.
  5. How the CLI manages Kubeconfigs for users

    main

    The CLI maintains a mapping of Kubeconfigs associated with specific users and clusters within its configuration file.

    When retrieving a Kubeconfig, the CLI uses a key format of {user}-{cluster} to look up the specific configuration for that user context. This allows the CLI to switch between different Kubernetes contexts seamlessly based on the user and the current cluster being targeted.

  6. Understand the OAuth authentication process

    main

    The Rancher CLI uses OAuth2 to exchange identity provider credentials for a Rancher-specific token. The process follows these steps:

    1. Initiation: The CLI identifies the provider and the requested flow (auth_code or device_code).
    2. Authorization:
      • In auth_code flow: A local server is started, a browser is opened to the provider's auth URL, and the CLI waits for a callback.
      • In device_code flow: The CLI displays a VerificationURI and a UserCode.
    3. Token Exchange: Once the user authenticates, the CLI exchanges the provider's code/token for an id_token.
    4. Rancher Login: The CLI sends the id_token to the Rancher server via a POST request to the login endpoint. The request body includes:
      • type: The authentication provider name.
      • responseType: Usually kubeconfig (or kubeconfig_<clusterID> if a specific cluster is targeted).
      • id_token: The token received from the OAuth provider.
    5. Result: Rancher returns a Rancher token and associated metadata (like a kubeconfig) which the CLI then uses for subsequent commands.
  7. How Rancher CLI handles token types and lookups

    main

    The Rancher CLI manages two distinct types of authentication tokens: v3 Management API tokens and ext.cattle.io/v1 Tokens.

    To ensure compatibility, the CLI uses a fallback mechanism for lookups and validation:

    1. Prefix Detection: If a token ID is prefixed with ext/, the CLI identifies it as an ext.cattle.io/v1 token and skips the v3 Management API lookup entirely to avoid unnecessary 404 errors.
    2. v3 Lookup: For tokens without the ext/ prefix, the CLI first attempts to find the token via the v3 Management API. If the token is not found (a 404 error), it falls back to the ext.cattle.io/v1 API.
    3. ext.cattle.io/v1 Lookup: If the v3 lookup fails or if the token ID is explicitly prefixed with ext/, the CLI attempts to retrieve the token from the ext.cattle.io/v1 API. The ext/ prefix is stripped before the request is made to the extension API.

    This dual-layer approach allows the CLI to seamlessly support both legacy and extended token formats used by different Rancher server configurations.

  8. Configure OAuth authentication flows

    main

    The Rancher CLI supports two primary OAuth authentication flows. You can control which flow is used via the CATTLE_OAUTH_AUTH_FLOW environment variable or by passing the appropriate flag in your command.

    Supported Flows

    • auth_code: The Authorization Code flow. This flow automatically attempts to open your default web browser to complete the authentication. It starts a local callback server to receive the authorization code.
    • device_code (Default): The Device Code flow. This is used when a browser cannot be automatically opened or when working in headless environments. The CLI will provide a verification URI and a user code for you to enter manually in a browser on another device.

    If no flow is specified, the CLI defaults to device_code.

    export CATTLE_OAUTH_AUTH_FLOW=auth_code
    # or use the CLI flag if available in the parent command
  9. Configure CLI output formats

    main

    The Rancher CLI supports different output formats for commands via the --format flag and suppresses headers via the --quiet flag.

    Supported formats:

    • json: Outputs the object as a JSON string.
    • yaml: Outputs the object as a YAML string.
    • default: (When no format is specified) Outputs data in a tabular format using a template.
    • custom: Any other string is treated as a Go template for the object values.

    Behavioral rules:

    • If --quiet is used, headers are suppressed and the output defaults to showing only the {{.ID}} of the object.
    • If a custom --format is provided (other than json or yaml), headers are suppressed and the output uses that format/template.
    • When using custom templates (non-JSON/YAML), a newline is automatically appended to the output.
  10. Configure the Rancher CLI configuration path

    main

    The Rancher CLI uses a configuration file to manage settings. You can specify the path to this file using the --config flag or the RANCHER_CONFIG_DIR environment variable. If neither is provided, the CLI defaults to the directory returned by cmd.ConfigDir().

    Flags:

    • --config (alias: -c): Path to rancher config.

    Environment Variables:

    • RANCHER_CONFIG_DIR: Path to rancher config.
    # Using the flag
    rancher --config /path/to/config.yaml cluster list
    
    # Using the environment variable
    export RANCHER_CONFIG_DIR=/path/to/config.yaml
    rancher cluster list