---
title: "Log in to gcx | Grafana documentation"
description: "Create or re-authenticate a gcx context with gcx login, and troubleshoot common login errors."
---

> For a curated documentation index, see [llms.txt](/llms.txt). For the complete documentation index, see [llms-full.txt](/llms-full.txt).

# Log in to `gcx`

`gcx login` creates or re-authenticates a context. The context binds a named stack entry containing the Grafana server and authentication and, optionally, a named Cloud entry containing Grafana Cloud platform authentication. The command auto-detects whether the server is Grafana Cloud or self-managed and adjusts the prompt accordingly.

This page walks through the common login paths, the mental model behind them, and how to recover from the errors you’re most likely to see. If you already know which path applies, jump to [Pick your scenario](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#pick-your-scenario).

## Pick your scenario

Find what you want to do in the table, then follow the link to the matching section.

Expand table

| I want to                                                   | Refer to                                                                                                                                                                                                                                       |
|-------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Sign up for Grafana Cloud                                   | [Sign up for Grafana Cloud](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#sign-up-for-grafana-cloud)                                                                                                                 |
| Log in to Grafana Cloud without a stack URL                 | [Log in without a stack URL](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#log-in-without-a-stack-url)                                                                                                               |
| Set up Grafana Cloud interactively                          | [Grafana Cloud (interactive OAuth)](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#grafana-cloud-interactive-oauth)                                                                                                   |
| Run `gcx` over SSH, with the browser on another computer    | [Remote host or SSH session](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#remote-host-or-ssh-session)                                                                                                               |
| Set up self-managed Grafana                                 | [Service account token](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#service-account-token) or [Basic authentication](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#basic-authentication) |
| Set up CI, an agent, or any non-interactive environment     | [Environment variables for CI and agents](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#environment-variables-for-ci-and-agents)                                                                                     |
| Add Grafana Cloud product API access to an existing context | [Grafana Cloud product APIs](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#grafana-cloud-product-apis)                                                                                                               |
| Re-authenticate or switch between contexts                  | [Re-authenticate and switch contexts](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#re-authenticate-and-switch-contexts)                                                                                             |

## First-time Grafana Cloud login

If you don’t have a Grafana Cloud account yet, use `gcx signup`. If you have an account but no stack URL at hand, use `gcx login`. Both flows finish in the browser.

### Sign up for Grafana Cloud

1. Run `gcx signup`. `gcx` opens the grafana.com sign-up page.
2. Create the account and verify your email. The emailed link may open a new tab.
3. Create your first stack. The browser then signs in to the new stack and goes to its **Connect gcx** page.
4. Approve **Connect gcx**. `gcx` saves the connection and prints a summary with the way back to your stack (in a color terminal, the `gcx` logo comes first):
   
   text ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy
   
   ```text
   ✔ You're connected to Grafana Cloud
   
     Stack     https://mystack.grafana.net
     Context   default
   
   Next steps
     Open Grafana
       https://mystack.grafana.net
     Explore interactive guides
       https://mystack.grafana.net/a/grafana-pathfinder-app
   ```

The guides step appears when the stack has the Interactive Learning plugin (Pathfinder) enabled, which Grafana Cloud stacks have by default. The browser page after **Connect gcx** has the same **Open Grafana** button, which takes that tab back to the stack. With `-o json`, `-o yaml`, or in agent mode, stdout carries the same result as `gcx login`, and the next steps come as hints on stderr.

If the browser is already signed in to Grafana Cloud, it asks you to choose a stack instead of showing the sign-up form. Choose one and approve **Connect gcx**. `gcx` saves a connection to that stack the same way. With one organization and one stack, the browser goes straight to **Connect gcx**. To create a separate account instead, sign out of Grafana Cloud in that browser first.

### Log in without a stack URL

1. Run `gcx login` and leave the server URL empty. `gcx` opens the grafana.com stack launcher.
2. Sign in and pick a stack.
3. Approve **Connect gcx**. `gcx` then offers the optional grafana.com management login, as after any interactive Grafana Cloud login.

### While `gcx` waits for the browser

In both flows, `gcx` waits in the terminal while you work in the browser, and prints a verification code that the consent page repeats. While it waits:

- Press Ctrl+C to stop.
- If the browser loses the page (a refresh, or the tab closed), press Enter. `gcx` opens the stack launcher again with the same login, where you sign in if needed and choose a stack. The Enter shortcut works in a local terminal only. Over SSH, or where `gcx` can’t watch the terminal (for example on Windows), open the printed URL again instead.

### Where `gcx signup` saves the connection

`gcx signup` saves the connection to the first of these that applies:

1. The context name you pass (`gcx signup my-stack`).
2. The current context.
3. `default`, when no context is set.

It only ever saves a new connection. Before it opens the browser, it refuses:

- A context that already has a stack or Grafana Cloud entry.
- A name that an existing stack entry uses.
- `GRAFANA_SERVER`, `GRAFANA_PROXY_ENDPOINT`, or `GRAFANA_TLS_*` in the environment.

It asks no questions and saves no Grafana Cloud management credentials, not even `GRAFANA_CLOUD_TOKEN`. To manage Grafana Cloud products (stacks, Synthetic Monitoring, k6, and more), save a Cloud Access Policy token afterwards with `gcx cloud login --context <context> --cloud-token <token>`. Refer to [Grafana Cloud product APIs](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#grafana-cloud-product-apis).

### If signup fails

If signup fails once the browser step has started, don’t run `gcx signup` again: it could start a second account. The error shows the `gcx login` command that finishes the connection in the same context and config file:

- When the browser step finished: `gcx login <context> --server <stack URL> --oauth`.
- When it didn’t: `gcx login <context> --cloud --oauth`, which signs in and lets you pick the new stack.

The command keeps the way the signup reached the browser:

- After `gcx signup --oauth-manual`, it uses `--oauth-manual` in place of `--oauth`.
- After `--oauth-callback-port <port>`, it adds the same port.

Over SSH, the remote session hint also offers a sign-in (`gcx login <context> --cloud --oauth-manual`), because the unreachable callback shows up only at the end, after the account exists.

### Sign up or log in from a coding agent

Coding agents can run `gcx signup` too. A person still completes the browser steps. In agent mode, `gcx` doesn’t open the browser, and prints the URL for the person to open. For an existing account, `gcx login --cloud --oauth` starts the stack launcher without prompting when no server is known (no `--server`, `GRAFANA_SERVER`, or server in the target context), and saves the connection without the optional grafana.com step.

### Use another Grafana Cloud environment

`GRAFANA_CLOUD_OAUTH_URL` moves the launcher and the sign-up page to another Grafana Cloud environment, for example `https://grafana-dev.com`, together with the Cloud OAuth endpoint. For `gcx login`, `--cloud-api-url` does the same.

## Grafana Cloud (interactive OAuth)

This is the recommended flow for day-to-day use on a Grafana Cloud stack. It opens a browser for OAuth, saves the access token, refresh token, and proxy endpoint to the context’s named stack entry, and makes the context current.

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx login my-stack --server https://my-stack.grafana.net
```

When you run this:

1. `gcx` detects that `my-stack.grafana.net` is a Grafana Cloud host and presents an authentication-method prompt.
2. OAuth is the first option. Pick it (or accept the default) and `gcx` opens your browser.
3. Complete the OAuth flow in the browser. `gcx` receives the tokens on a local callback and writes them to the stack entry bound by `my-stack`.
4. The Cloud platform step can keep an existing Cloud Access Policy (CAP) token or unexpired Cloud OAuth credential, accept a new CAP, run the experimental direct Cloud OAuth flow, or skip Cloud functionality. Refer to [Grafana Cloud product APIs](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#grafana-cloud-product-apis).

### Required role

The OAuth consent step is gated by the `grafana-assistant-app.tokens.gcx:access` permission, granted by the gcx User role that the `grafana-assistant-app` plugin registers (available since plugin version 2.0.26). Grafana assigns the role automatically to users with the basic role Viewer or higher. The permission only allows minting `gcx` tokens for the requesting user. Proxied requests run with the user’s own identity and RBAC permissions. If the consent page shows a `Permission Required` error, refer to [Troubleshooting](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#troubleshooting).

If OAuth doesn’t suit your setup (for example, corporate SSO restrictions or no browser available), pick **Service account token** at the prompt instead.

These rules decide which credential `gcx` sends:

- The persisted `auth-method` is authoritative unless a non-blank `GRAFANA_TOKEN` selects service-account-token authentication for the current invocation. That runtime selector is never written back to the config.
- In all other cases, `gcx` sends only the persisted method’s credential, even if an older field remains in a hand-edited config.
- An explicit non-mTLS method doesn’t present a stale client certificate.
- `GRAFANA_PASSWORD` can rotate a Basic context’s password but doesn’t switch another explicit method to Basic.
- Legacy contexts without `auth-method` retain the inference order of OAuth, service account token, Basic, then mTLS or anonymous. A partial or rejected higher-priority credential fails before any request instead of falling through.

Repair the selected method with `gcx login`, or use `gcx config edit --config <path>` when the file can’t be loaded normally.

## Remote host or SSH session

The OAuth callback server listens on `127.0.0.1` on the computer that runs `gcx`. When you run `gcx` over SSH, the browser on your own computer can’t open that address.

**You don’t need a flag, and you don’t need to restart.** `gcx` detects the SSH session, keeps the callback server listening, and also reads a pasted redirect URL. It accepts whichever arrives first:

text ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```text
Note: gcx runs in an SSH session.
The browser on your computer cannot open the callback address on this host.
Do one of these two steps. gcx accepts the one that completes first.

  1. Add a port forward to this SSH session. Press Enter, then press ~C,
     then type this line:
       -L 43817:127.0.0.1:43817

  2. Approve the login in the browser on your computer. The browser then
     goes to an address that does not load. Copy that address and paste it
     here.

Redirect URL (or wait for the browser):
```

Do these steps quickly. The authorization code expires.

### Option 1: Add a forward to the running session

1. Press Enter. The escape only works after a newline.
2. Press `~C`, the OpenSSH escape that opens a command line for `-L`, `-R`, and `-D`.
3. Type the `-L` line that `gcx` prints.

It needs no reconnect and no hostname, and `gcx` keeps waiting, so the login completes as soon as the browser reaches the forwarded port.

### Option 2: Paste the redirect URL

1. Approve in the browser.
2. Let it fail to load `http://127.0.0.1:<port>/callback?...`.
3. Copy the whole address.
4. Paste it at the prompt.

If the address doesn’t work, `gcx` says why and asks again. The callback server stays up the whole time.

The prompt ignores an empty line, so the Enter that Option 1 needs costs nothing. Ctrl-D ends the paste route; `gcx` says so and keeps waiting for the browser.

### Use `--oauth-manual` for scripts and terminals with no `/dev/tty`

The flag starts no callback server at all and only reads the pasted URL:

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx login my-stack --server https://my-stack.grafana.net --oauth-manual
```

- It implies `--oauth` and is mutually exclusive with `--oauth-callback-port`.
- The same flag works on `gcx cloud login`, and one choice covers both the stack step and the Cloud follow-up step.
- You don’t need it for an ordinary interactive SSH login, because the SSH prompt appears on its own.

### Close other `gcx login` sessions on the browser computer first

A `gcx` login that already listens on the same port there receives the callback, rejects it on the state check, and ends its own flow. Your paste still succeeds, but the other login doesn’t.

### Terminal hygiene

Keep in mind the following:

- The pasted URL holds a single-use authorization code and the state value. It doesn’t hold the Proof Key for Code Exchange (PKCE) code verifier or a token, so the code alone can’t mint a token.
- `gcx` reads it from a prompt, so it never enters your shell history.
- It does stay in the terminal scrollback and in the browser history. `gcx` prints the reminder once a URL reaches the screen, whether the login succeeds or fails.

**Clear the terminal if other people can read it.**

## Service account token

Service account tokens work for both Grafana Cloud and self-managed Grafana and are the recommended path for non-interactive use. Browser OAuth works only with Grafana Cloud. Self-managed stacks can also use [Basic authentication](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#basic-authentication) or configured mTLS client certificates.

### Log in non-interactively

This is the recommended method for automation.

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx login my-grafana \
  --server https://your-instance.grafana.net \
  --token glsa_your_token \
  --yes
```

### Log in interactively

`gcx` prompts for the token.

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx login my-grafana --server https://your-instance.grafana.net
# At the prompt, pick "Service account token" and paste your token.
```

### Choose the token role

Use a [Grafana service account token](https://grafana.com/docs/grafana/latest/administration/service-accounts/) with a role matching what the token needs to do:

- **Querying (metrics, logs, traces, profiles) and reading dashboards or folders:** Viewer
- **Pushing and editing dashboards and folders:** Editor
- **Managing data source configuration:** Admin

On Grafana Cloud and Grafana Enterprise, RBAC custom roles can scope query access tighter (for example, `datasources:read` plus `datasources:query` on specific data sources).

### Set the organization ID

For self-managed instances, `gcx` defaults the organization ID to 1 if you don’t specify one, which is the common case for single-tenant Grafana OSS. If you need a different organization ID, set it with `gcx config set stacks.<name>.grafana.org-id N` after login (on the context’s stack entry).

## Basic authentication

Use a Grafana username and password for self-managed Grafana OSS or Grafana Enterprise with Basic authentication enabled. This is useful for server administration: [Admin API endpoints](https://grafana.com/docs/grafana/latest/developer-resources/api-reference/http-api/api-legacy/admin/) require Basic authentication and Grafana server administrator permissions. Logging in doesn’t grant those permissions. Use HTTPS when connecting to a remote instance.

### Log in interactively with a username and password

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx login my-grafana --server https://grafana.example.com
# Pick "Basic auth (username/password)" and enter your username and password.
```

Interactive login always prompts for the password, even if `GRAFANA_PASSWORD` is exported, and doesn’t echo it. To select Basic authentication directly and supply the username:

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx login my-grafana --server https://grafana.example.com --basic-auth --user admin
```

### Log in non-interactively with a username and password

1. Supply `GRAFANA_PASSWORD` through your environment or CI secret store. There is no password command-line flag.
2. Pass `--yes` to disable prompts.

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
# GRAFANA_PASSWORD is already supplied by your secret store.
export GRAFANA_USER=admin
gcx login my-grafana --server https://grafana.example.com --basic-auth --yes
```

### Flag precedence

- `--user` takes precedence over `GRAFANA_USER`.
- `--basic-auth` selects Basic authentication even if a stored token, OAuth login, or `GRAFANA_TOKEN` exists. You can’t combine it with `--token`, `--oauth`, or `--oauth-manual`.
- Supply the username and password again when re-authenticating. Login doesn’t reuse a stored password.

### Credential validation and storage

Before saving, `gcx` makes a fresh authenticated `GET /api/user` request. Successful health checks or cached API discovery don’t replace this check. If Grafana rejects the credentials, login fails without changing the config or keychain. It doesn’t offer to save them anyway. Check:

- The username and password.
- Whether Basic authentication is enabled.
- Whether a proxy blocks the request.

Successful login:

- Stores `auth-method: basic`, the username, and the password through the existing [credential storage policy](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/keychain/).
- Clears previous token and OAuth credentials for that stack entry.

On subsequent commands, a non-blank `GRAFANA_TOKEN` still selects token authentication for that invocation; unset it to use the saved Basic login.

### Configure Basic authentication manually

The equivalent fields on the context’s stack entry are `grafana.auth-method: basic`, `grafana.user`, and `grafana.password`. Use `gcx config edit` to configure them through the same credential storage policy. `GRAFANA_USER` and `GRAFANA_PASSWORD` can also supply credentials at runtime. A password override alone doesn’t switch an explicit token or OAuth context to Basic authentication.

### Select an organization

For organization-scoped operations, login defaults to organization 1 on self-managed Grafana. Use `--org-id N` to select another organization. This doesn’t grant membership or server administrator permissions. The separate [org-selection issue](https://github.com/grafana/gcx/issues/1340) tracks clients that don’t consistently honor the configured organization.

## Grafana Cloud product APIs

These commands need a Grafana Cloud platform credential in addition to Grafana instance authentication:

- `gcx cloud` commands (stack management)
- `gcx k6` with a service account token
- `gcx sm` when it falls back to the direct Synthetic Monitoring API

A [Cloud Access Policy token](https://grafana.com/docs/grafana-cloud/platform/security-and-account-management/security-and-access/authentication-and-permissions/access-policies/) has the widest compatibility and is recommended for automation. Direct Cloud OAuth is available interactively but remains experimental, and some Cloud product clients don’t yet accept it.

### Where to create the token and which scopes to grant

Create the token in either place:

- **In your stack** (the deep link that the `gcx login` prompt offers): `https://<YOUR_STACK>.grafana.net/a/grafana-auth-app`, then **Access Policies** &gt; **Create access policy**.
- **From grafana.com**: **Administration** &gt; **Cloud Access Policies** &gt; **Create access policy** (`https://grafana.com/orgs/<YOUR_ORG>/access-policies`).

Refer to [Create access policies](https://grafana.com/docs/grafana-cloud/platform/security-and-account-management/security-and-access/authentication-and-permissions/access-policies/create-access-policies/) for the step-by-step flow.

Scope the access policy to what you manage. `stacks:read` is the required baseline: it resolves your stack and gates login and token validation. Then add the scopes for the products you use:

Expand table

| Scope                                         | Enables                                                                                                                                                 |
|-----------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|
| `stacks:read`                                 | **Required.** Stack discovery (resolves the stack slug for all Cloud commands; also covers `gcx k6` reads)                                              |
| `metrics:write`, `logs:write`, `traces:write` | Synthetic Monitoring (`gcx sm`). These write verbs are needed to mint the Synthetic Monitoring token.                                                   |
| `stacks:write`                                | Creating or updating stacks                                                                                                                             |
| `stacks:delete`                               | Deleting stacks (`gcx cloud stacks delete`)                                                                                                             |
| `set:alloy-data-write`, `metrics:read`        | Instrumentation Hub setup (`gcx instrumentation setup`). These are for the token you add to the Helm command it prints, not the `gcx` Cloud credential. |

`gcx fleet` and `gcx instrumentation` need no scope here. Fleet Management reaches its API through the `grafana-collector-app` plugin proxy on your stack, so your Grafana login alone is enough. Refer to the [Fleet via collector-app proxy RFC](https://github.com/grafana/gcx/tree/main/docs/rfcs).

The Cloud Access Policy token is for Grafana Cloud product APIs: stack management through the Grafana Cloud API (abbreviated to GCOM), Synthetic Monitoring, and k6. IRM, SLO, and signal queries (`gcx metrics`, `gcx logs`, `gcx traces`, `gcx profiles`) authenticate with your Grafana token (OAuth or service account), not this token. For the Grafana roles and plugin permissions each product needs, refer to [Roles and permissions](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/permissions/). When in doubt, start narrow and widen the policy as commands report missing-scope errors. You can re-scope the token without rerunning `gcx login`.

The interactive `gcx login` prompt links to this guidance when it offers Cloud authentication choices.

### Provide the token at login

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx login my-stack \
  --server https://my-stack.grafana.net \
  --token glsa_your_sa_token \
  --cloud-token glc_your_cap_token \
  --yes
```

### Add Cloud access to an existing context

Rerun `gcx login`:

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx login --context my-stack
# Follow the prompts to keep or replace the existing credential, run Cloud
# OAuth, paste a Cloud Access Policy token, or skip.
```

### Run direct Cloud OAuth

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx cloud login --context my-stack
```

The OAuth result is stored separately from a CAP, together with its expiry, granted scopes, and exact OAuth and API endpoint pair. Keeping an existing credential preserves its kind and metadata. OAuth has no refresh token; after expiry, run Cloud login again. Use a CAP when you need full command compatibility.

`gcx cloud login` persists a CAP only when `--cloud-token` contains a nonblank value. It doesn’t capture an ambient `GRAFANA_CLOUD_TOKEN`. Without a nonblank flag value it runs the OAuth flow.

### Set the stack slug for custom domains

`gcx` derives the Cloud stack slug from `--server` when the hostname matches a standard `*.grafana.net` pattern. For custom domains (such as `*.cloud.example.grafana.com`), set it explicitly on the stack entry:

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx config set stacks.my-stack.slug your-stack-slug
```

### Set Cloud endpoints for custom environments

You don’t need to set Cloud endpoints for `grafana.com`; `gcx` defaults to `https://grafana.com`. For a custom environment, the OAuth origin and API destination must remain coherent. Supplying only one endpoint to a login flow uses it for both operations; `gcx cloud login` accepts both `--oauth-url` and `--api-url` when a deployment deliberately uses a distinct pair. Editing a named entry’s endpoint invalidates its existing credential, so authenticate again after the change.

## Environment variables for CI and agents

For pipelines, agents, and other non-interactive environments, you can avoid a persistent login and provide credentials through environment variables. `gcx` resolves them on every command invocation and applies them only to the selected context’s runtime view.

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
export GRAFANA_SERVER="https://your-instance.grafana.net"
export GRAFANA_TOKEN="glsa_your_sa_token"
export GRAFANA_CLOUD_TOKEN="glc_your_cap_token"

# Optional: only needed when gcx cannot derive the stack slug from
# GRAFANA_SERVER (custom domains).
export GRAFANA_CLOUD_STACK="your-stack-slug"

gcx resources get dashboards
```

How `gcx` handles these variables:

- Environment variables take precedence over config-file values and aren’t persisted incidentally.
- If you invoke unified `gcx login`, explicit flags still win and the relevant environment inputs are used for the selected login target.
- Direct `gcx cloud login` intentionally ignores an ambient Cloud token. Pass `--cloud-token` to persist one.
- Blank or whitespace-only credential variables are treated as unset. They don’t erase a stored token or password and don’t authorize moving a stored credential to an overridden destination.

You can instead run login once to persist credentials and then remove the environment variables.

## Re-authenticate and switch contexts

Use these commands to refresh credentials, switch the current context, and view your contexts.

### Refresh credentials

**On the current context:**

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx login
```

**On a specific context:**

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx login --context my-stack
```

### How re-authentication writes your config

Re-authentication preserves user-set fields (`org-id`, `stack-id`, TLS settings, provider-specific tokens) and updates only auth-bearing fields. If you manually set `org-id: 42`, it stays at 42 after re-auth.

With multiple config layers, `gcx` writes login results without an extra flag only when the existing entries and context bindings have one provable owner. If owners differ or a higher layer could shadow a rebind, the command stops before authentication and lists exact `--config` choices. Consolidate the bindings or explicitly select the intended file.

For discovery-mode login, `gcx` also snapshots every participating config file before authentication. If any file changes, appears, or disappears while OAuth or connectivity validation is running, persistence stops and the fresh credential isn’t written. An explicit `--config` selection pins only that chosen file.

For a pure mTLS login, `GRAFANA_TLS_*` paths remain runtime-only and `gcx` warns that they weren’t saved. Keep supplying them, or persist the reviewed paths explicitly. An `auth-method: mtls` context without both a client certificate and private key fails before its next network request.

Token and OAuth credentials are destination-bound:

- If a bearer login depends on runtime-only `GRAFANA_TLS_*` or `GRAFANA_PROXY_ENDPOINT` settings, `gcx` stops before presenting or saving the credential and prints exact `gcx config set` commands for the selected config, stack, and context. Those commands can also initialize a deliberately selected, not-yet-created `--config` file. Persist the reviewed settings and retry, or unset overrides that weren’t intended.
- If a context or stack map key contains a dot, the dot-path grammar can’t name it safely. `gcx` instead reports the exact fields and directs you to the selected file with `gcx config edit --config ...`.
- If an OAuth issuer selects a proxy different from `GRAFANA_PROXY_ENDPOINT`, persisting the override can’t repair the conflict, so `gcx` tells you to unset that environment variable and retry.

### Switch the current context

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx config use-context my-stack
```

### View all configured contexts

Bash ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy

```bash
gcx config view
```

Secrets are redacted in the output. Refer to [Configuration reference](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/configuration/#configuration-reference) for the full config file layout.

## How login works

This section defines the terms that the troubleshooting entries use. For the internal design, refer to [Configuration, clients, and transport](https://github.com/grafana/gcx/blob/main/docs/architecture/config-and-clients.md).

### Contexts

A context binds together a named *stack entry* (server URL, Grafana credentials, provider config) and, optionally, a named *cloud entry* (grafana.com credentials, shareable across contexts) in your `gcx` config file. `gcx login` creates a stack named after the context plus the binding; `gcx cloud login` creates or reuses a cloud entry and binds it. Commands run against the *current* context unless you pass `--context` to target another one. The model and on-disk format mirror `kubectl` kubeconfig. Refer to [Configuration, clients, and transport](https://github.com/grafana/gcx/blob/main/docs/architecture/config-and-clients.md) for the full layout.

### Grafana Cloud versus self-managed

`gcx` detects whether `--server` points at Grafana Cloud or a self-managed instance, in this order:

1. The hostname is matched against known Cloud suffixes (no network call).
2. Loopback and RFC1918 addresses are classified as self-managed.
3. Anything else is probed with a short HTTP request.

The classification drives which auth methods appear in the prompt.

### Two authentication tiers

Grafana OAuth, service account tokens, Basic authentication, and mTLS authenticate to an individual Grafana instance: dashboards, folders, data sources, alerts, and the Kubernetes-compatible `/apis` endpoints. A CAP or direct Cloud OAuth credential authenticates separately to GCOM and supported Cloud product APIs. A Cloud context therefore commonly binds one Grafana credential and one Cloud-platform credential; a self-managed context needs only Grafana authentication.

### Interactive, `--yes`, and environment variable modes

- **Interactive:** opens prompts for anything you didn’t pass as a flag.
- **`--yes`:** disables optional prompts and makes `gcx login` fail loudly if a required field is missing. Use this mode in CI.
- **Environment variables:** can avoid persistent login and resolve on each command invocation. When login is invoked, its explicit flags take precedence over those inputs.

### Credential storage

Grafana credentials persist under the context’s named stack entry; CAP and Cloud OAuth credentials occupy distinct fields on the referenced Cloud entry. Refer to [Keychain credential storage](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/keychain/) for storage rules and keychain error procedures. `gcx config view` redacts secret fields. Don’t commit a credential-bearing config file to version control.

## Troubleshooting

Each entry pairs the error you see with what it means and how to fix it.

### `missing stacks.X.grafana.org-id or stacks.X.grafana.stack-id`

- *Means:* `gcx` can’t determine which organization (self-managed) or stack (Grafana Cloud) the context’s stack targets.
- *Fix:* `gcx config set stacks.X.grafana.org-id 1` for self-managed Grafana, or `gcx config set stacks.X.grafana.stack-id N` for Grafana Cloud. Issue [#545](https://github.com/grafana/gcx/issues/545) tracks auto-healing this.

### `cloud stack is not configured`

The full error is `cloud stack is not configured: set the stack's slug (gcx config set stacks.<name>.slug <slug>) or GRAFANA_CLOUD_STACK env var`.

- *Means:* a Cloud product API command ran against a context without a resolvable stack slug.
- *Fix:* `gcx config set stacks.<name>.slug your-stack-slug`, or export `GRAFANA_CLOUD_STACK` in the current shell. Issue [#545](https://github.com/grafana/gcx/issues/545) tracks auto-healing this.

### OAuth: browser didn’t open, or token refresh failed

- *Means:* `gcx` tried to open a browser for OAuth but the system command returned an error, or the OAuth refresh flow failed.
- *Fix:* Rerun `gcx login` to trigger a fresh flow. If the browser runs on a different computer, rerun with `--oauth-manual` and paste the redirect URL. Refer to [Remote host or SSH session](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#remote-host-or-ssh-session). If your environment has no browser at all, use a service account token instead. For corporate proxies, check that the OAuth callback URL is reachable.

### OAuth over SSH never completes; the browser shows `ERR_CONNECTION_REFUSED` on 127.0.0.1

- *Means:* the callback server listens on the loopback address of the remote host. The browser on your own computer can’t reach it.
- *Fix:* This is expected. Copy that address from the browser and paste it at the `Redirect URL` prompt, or add a port forward to the running session with `~C`. Refer to [Remote host or SSH session](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/login/#remote-host-or-ssh-session). If `gcx` printed no prompt, it found no `/dev/tty`. Rerun with `--oauth-manual`.

### `Permission Required` on the OAuth consent page (gcx User role or `grafana-assistant-app.tokens.gcx:access`)

- *Means:* your Grafana user lacks the `grafana-assistant-app.tokens.gcx:access` permission that gates `gcx` token minting. The gcx User role granting it is normally auto-assigned to Viewer and above, but the instance may run a `grafana-assistant-app` version older than 2.0.26 (the role doesn’t exist yet) or have customized basic-role grants.
- *Fix:* ask your Grafana administrator to assign the gcx User role, or a custom role including `grafana-assistant-app.tokens.gcx:access`. If the role is missing entirely, the `grafana-assistant-app` plugin needs updating. As a workaround, authenticate with a service account token instead.

### `grafana version X is not supported; gcx requires Grafana 12.0.0 or later`

- *Means:* `gcx` requires Grafana 12 or later because it uses the Grafana Kubernetes-compatible `/apis` surface introduced in 12.
- *Fix:* Upgrade your Grafana instance, or use a different tool for older versions.

### GCOM 401 or Cloud Access Policy token rejected

- *Means:* the Cloud Access Policy token was rejected by GCOM or a Cloud product API.
- *Fix:* Verify the token at [grafana.com &gt; Access Policies](https://grafana.com/docs/grafana-cloud/platform/security-and-account-management/security-and-access/authentication-and-permissions/access-policies/). Rotate if compromised. Provide the new token with `gcx login --context X --cloud-token glc_...`.

### Health check or `/apis` connectivity failures

- *Means:* `gcx` couldn’t reach the server during the validation pipeline. The cause is typically a wrong URL, a DNS or proxy issue, or a TLS mismatch.
- *Fix:* Verify the server URL is correct and reachable. Check any corporate proxies (`HTTPS_PROXY`) and TLS configuration. For a reviewed development-only config, set `stacks.<name>.grafana.tls.insecure-skip-verify`; there is no login flag that bypasses TLS verification.

### `gcx assistant` commands fail with a service account token

- *Means:* `gcx assistant` commands (prompt, investigations) require OAuth, which is only available when you log in through the browser-based OAuth flow. Service account tokens aren’t supported.
- *Fix:* Rerun `gcx login` and choose the OAuth (browser) option. If your environment can’t open a browser, `gcx assistant` isn’t available. Use the Grafana UI instead.

### Flag versus environment variable precedence confusion

- *Means:* both a CLI flag and an environment variable are set for the same field, and `gcx` behaves unexpectedly.
- *Fix:* Flags take precedence over environment variables, which take precedence over config-file values. For credential fields, blank or whitespace-only inputs are treated as unset rather than as an override. Run `gcx config view` to inspect the resolved config and spot the conflict.

### Login refuses to replace an existing context’s server

- *Means:* the selected context points at a different Grafana server. `--yes` doesn’t authorize changing a credential destination, and `gcx` doesn’t present the stored credential to the new server.
- *Fix:* Verify the new URL, then pass `--allow-server-override` together with a fresh `--token`, a fresh `GRAFANA_TOKEN`, or a new OAuth flow. An interactive login can ask for the same explicit confirmation.

### `Configuration write target is ambiguous`

- *Means:* layered files don’t prove one owner for every entry or context binding the login may update.
- *Fix:* Review the paths listed by the error and rerun with the intended `--config <path>`, or keep the target stack, Cloud entry, and context bindings together in one source.

### A credential was `rejected before network use`

- *Means:* a credential reference was missing or foreign, a destination changed, or an environment credential was paired with an auto-discovered repository destination. `gcx` withheld it instead of sending an empty or misrouted credential.
- *Fix:* For an auto-discovered repository destination, review the file and rerun with its explicit `--config` path. Re-authenticate, or replace or unset the rejected field. Refer to [Keychain credential storage](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/keychain/) if the error identifies a keychain reference.

### `Cloud credential destination is ambiguous`

- *Means:* one credential-bearing Cloud entry has no explicit endpoint pair and is referenced by contexts in different Cloud environments. `gcx` doesn’t guess which API destination may receive it.
- *Fix:* Run the exact raw `gcx config edit ...` command from the error, split the Cloud entry into one entry per environment, and update each `contexts.<name>.cloud` binding. Ordinary config loading remains blocked until the ambiguity is removed.

### `Configuration changed during authentication`

- *Means:* the selected owner or the discovered config source set changed while OAuth or connectivity validation was in progress. The freshly authenticated credential wasn’t written.
- *Fix:* Review every changed file, then retry. If you intend to trust one document as authoritative, rerun with its explicit `--config <path>`.

## Learn more

- [`gcx login` flag reference](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/cli-reference/#gcx-login): exhaustive list of flags and options.
- [Keychain credential storage](https://grafana.com/docs/grafana/latest/ai-tools/grafana-cli/gcx/keychain/): credential storage rules and keychain error procedures.
- [Configuration, clients, and transport](https://github.com/grafana/gcx/blob/main/docs/architecture/config-and-clients.md): how contexts are stored, merged, and turned into authenticated requests.
- [Engineering RFCs](https://github.com/grafana/gcx/tree/main/docs/rfcs): historical design rationale (including login and configuration consolidation).
