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

# Create API keys with the CostGraph CLI

> Create one API key with the scopes a script, CI job, or Terraform configuration needs, and fix permission errors

Create one API key with the permissions your workflow needs. Choose its tenant and scopes, then approve the request in your browser.

## API key approval

An API key belongs to you and one tenant. It acts with your current role, limited to the scopes you approve.

Cost data and virtual tags stay limited to that tenant. The `organization:manage` scope permits supported organization management operations across the organization. It does not expand access to tenant data.

If your role changes, the key's access changes with it. See [Roles and permissions](https://docs.costgraph.ai/costgraph/security/roles.md#api-keys) for how roles and scopes combine.

### Browser approval and key storage

The browser approval names the tenant and every requested scope. After approval, the CLI prints the key once and revokes the temporary approval.

Creating a key does not sign you in or change your saved session. The CLI does not save the new key. Store it in your secret manager.

## Requirements

You need the following:

* The CostGraph CLI 0.11.0 or later. Refer to [Install and sign in](https://docs.costgraph.ai/costgraph/cli/install.md#install).
* A browser on the same machine as the CLI, for the approval page.
* Access to the tenant that holds the key.
* The **Owner** role, if the key includes `organization:manage`. Keys with `pricing:write` or `deployment:register` need the **Admin** role or higher.

You don't need to run `costgraph auth login` first. The approval page asks you to sign in if your browser has no CostGraph session.

## Choose a tenant

Every key belongs to one tenant. Its access to cost data, virtual tags, and other tenant data stays within that tenant. Choose the tenant that holds the data your workflow uses.

List your tenants with their names and IDs.

```shell theme={null}
costgraph tenant list
```

Pass the tenant to `costgraph api-keys create` with `--tenant`. The flag accepts a tenant name or ID, and names match without regard to case. Without `--tenant`, you choose the tenant on the approval page.

If you pass `--tenant` and then select a different tenant on the approval page, the CLI stops with `browser approval selected a different tenant; no key was created`.

The key creation output reports the tenant ID. In Terraform, select the tenant by name with the `costgraph_tenant` data source and use its returned `.id`. Refer to [Use a tenant in Terraform](https://docs.costgraph.ai/costgraph/cli/install.md#use-a-tenant-in-terraform).

## Manage scopes

A scope is one permission that you attach to a key. Give a key only the scopes its workflow needs.

### List supported scopes

The following command lists the scopes that your CostGraph deployment supports.

```shell theme={null}
costgraph api-keys scopes
```

The output is a one-column table of scope names. This abbreviated example shows a few of them.

```text theme={null}
 Scope
 ────────────────────
 focus:read
 focus:write
 organization:manage
 usage:read
 virtual-tags:read
 virtual-tags:write
```

This command reads published metadata without signing in. It lists supported scopes, not the scopes attached to a key you already own.

The list can include permissions your role cannot grant. It also varies by deployment and version. Set `COSTGRAPH_API_URL` first for a self-hosted deployment.

Add `-o json` to return a JSON array.

### Choose scopes for a task

The following table lists the scopes for some common workflows.

| Workflow | Scope |
| - | - |
| Query costs with `costgraph cost get` | `focus:read` |
| Price a Terraform plan with `costgraph cost breakdown` or `costgraph cost diff` | `pricing:read` |
| Push your own cost data | `focus:write` |
| Create and update virtual tags through the API, such as with Terraform | `virtual-tags:write` |
| Read virtual tags through the API | `virtual-tags:read` |
| Manage the organization and its tenants | `organization:manage` |

`virtual-tags:write` includes read access. These scopes apply to the virtual tag management API used by Terraform.

The CLI's `costgraph tags` commands require a browser session. See [Credentials](https://docs.costgraph.ai/costgraph/cli/overview.md#credentials).

`organization:manage` permits owner-level organization setup, such as creating tenants, across the key's organization. It doesn't grant access to virtual tags or other data in a tenant. A key that manages the organization and also writes virtual tags needs both scopes. Only an organization owner can grant `organization:manage`.

Refer to [Roles and permissions](https://docs.costgraph.ai/costgraph/security/roles.md#api-keys) for what other scopes allow.

### Attach several scopes to one key

Repeat `--scope` once for each permission. Every scope you pass goes on the same key. The CLI doesn't create one key per scope.

```shell theme={null}
costgraph api-keys create \
  --name cost-reports \
  --tenant Production \
  --scope focus:read \
  --scope virtual-tags:write
```

`--scope` also accepts a comma-separated list, such as `--scope focus:read,virtual-tags:write`. Both forms produce one key with the same scopes. The CLI removes duplicates and rejects a value that contains spaces.

### API key scopes and virtual tag rule scopes

The two `--scope` flags have different meanings.

| Command | Meaning of `--scope` |
| - | - |
| `api-keys create` | Grants permissions such as `focus:read`. |
| `tags create` | Selects `billing` or `k8s` cost data for a rule. Grants no permission. |

## Create an API key

This procedure creates a key named `team-tags` with `virtual-tags:write` in the `Production` tenant. Replace the name, tenant, and scopes with the ones your workflow needs.

**1. Request the key**

```shell theme={null}
costgraph api-keys create \
  --name team-tags \
  --tenant Production \
  --scope virtual-tags:write
```

`--name` is required, and you must pass at least one `--scope`. The CLI opens the approval page in your browser and prints the same address. If the browser doesn't open, copy the address into a browser on the same machine.

**2. Approve the tenant and scopes**

Check that the approval page shows the tenant and every scope you requested, then approve it. To cancel before you approve, close the page and press Ctrl+C in the terminal. The CLI creates no key.

**3. Copy the key**

The terminal reports the new key.

```text theme={null}
API key created
  Name:               team-tags
  Tenant:             2c1f0f7e-5d0a-4a8e-9a43-7b1f3d0c9e21
  Scopes:             virtual-tags:write
  API key:            <your new API key>
Copy this key now. CostGraph does not return it again.
```

Store the key in your secret manager or CI secrets now. CostGraph shows it only in this output.

The browser callback uses local port 9093 by default. Pass `--callback-port` to use another port.

### Capture the key in a script

With `-o json`, the CLI prints the new key as JSON on standard output. Approval instructions still go to standard error, so they stay visible in your terminal. The JSON has the fields `id`, `name`, `tenant_id`, `permission_scopes`, and `raw_api_key`.

The following commands store the key in an environment variable without printing it. They export the variable only when the CLI returns a key.

```shell theme={null}
if key=$(costgraph api-keys create \
  --name team-tags \
  --tenant Production \
  --scope virtual-tags:write \
  -o json | jq -er '.raw_api_key'); then
  export COSTGRAPH_API_KEY="$key"
else
  echo "API key creation failed" >&2
fi
```

`jq -e` rejects a missing or null `raw_api_key`. If capture fails, the `else` branch leaves `COSTGRAPH_API_KEY` unchanged.

The variable lasts only for the current shell. Save the key in a secret store if you need it later.

## Use the key in a script or CI

The CLI reads an API key from the `COSTGRAPH_API_KEY` environment variable. Store the key as a secret in your CI system and expose it to the job under that name.

The following job step prints month-to-date cost by provider. It needs a key with `focus:read`.

```shell theme={null}
export COSTGRAPH_API_KEY="$COSTGRAPH_KEY_SECRET"
costgraph cost get --group-by provider --no-interactive
```

For a self-hosted deployment, also set `COSTGRAPH_API_URL` to your API address.

Create the key on a workstation before the job runs. Key creation always needs an approval in a browser, and `-o json` doesn't change that. A CI job can only use a key that already exists.

The CLI prefers a saved session over an API key. A CI runner normally has no saved session. On a workstation where you signed in, run `costgraph auth logout` before you test commands with the key. Refer to [Credentials](https://docs.costgraph.ai/costgraph/cli/overview.md#credentials).

## Create a key for Terraform

A configuration that manages tenants and virtual tags needs two permissions on one key. Only an organization owner can grant the management permission.

```shell theme={null}
costgraph api-keys create \
  --name terraform-resources \
  --tenant tf-eval \
  --scope organization:manage \
  --scope virtual-tags:write
```

The permissions cover separate parts of the configuration.

| Scope | Used for |
| - | - |
| `organization:manage` | Tenant, cloud integration, and Kubernetes registration management. |
| `virtual-tags:write` | Creating, updating, and reading virtual tags in the key's tenant. |

Remove permissions your configuration does not need. Look up `tf-eval` by name with the `costgraph_tenant` data source. Pass its returned `.id` to virtual tag resources so they use the key's tenant.

The provider reads the key from `COSTGRAPH_API_KEY`. Follow [Capture the key in a script](#capture-the-key-in-a-script) to set it without printing the secret.

### Retry after a partial Terraform apply

If Terraform creates some resources before a virtual tag fails, correct the key's tenant, scopes, or owner role. The virtual tag key needs `virtual-tags:write` for that tenant. `organization:manage` does not grant this access.

Keep the successfully created resources in Terraform state. Run `terraform plan` again after correcting access, review the result, and apply the new plan.

## Manage existing keys

The CLI creates keys and lists supported scopes. It doesn't list, update, rotate, or revoke existing keys. Manage your keys in the CostGraph dashboard under **Settings > Account Settings > API Keys**.

## Resolve permission errors

CostGraph refuses a request with HTTP `401` or `403` for several reasons. A missing scope is only one of them. The CLI prints the reason after `Error:`, followed by the status code. Check each of the following in order.

> [accordion] The command doesn't accept API keys
>
> `Valid Bearer token required (401)` means the command accepts only a saved session. Refer to [Credentials](https://docs.costgraph.ai/costgraph/cli/overview.md#credentials) for the commands that reject API keys. Run the command after `costgraph auth login` instead.

> [accordion] The CLI used your saved session
>
> When you signed in on the machine, the CLI uses your saved session and ignores `COSTGRAPH_API_KEY`. Run `costgraph auth status`. If it reports `browser`, the command ran as your session. Run `costgraph auth logout`, then run the command again with the key.
>
> `costgraph auth status` reports `api_key` when it finds a key and no saved session. It doesn't check the key's scopes or whether the key still works.

> [accordion] The key belongs to another tenant
>
> A key can access cost data and virtual tags only in its own tenant. `organization:manage` covers supported organization management operations across tenants.
>
> Compare the tenant ID in the key creation output with your command or configuration. Create a key in the correct tenant if they differ.

> [accordion] The key lacks a scope
>
> An `Insufficient permissions` message names the missing scope. Check [Choose scopes for a task](#choose-scopes-for-a-task). `organization:manage` does not grant virtual tag access.
>
> To add permissions, create a replacement key with the full set of scopes the workflow needs.

> [accordion] Your role doesn't allow the action
>
> A key never has more access than your current role. If your role changed after you created the key, the key's access changed too. Refer to [Roles and permissions](https://docs.costgraph.ai/costgraph/security/roles.md).

> [accordion] The CLI is pointed at another deployment
>
> A key works only on the deployment that created it. Run `costgraph config list` and check the API address and where it came from. Set `COSTGRAPH_API_URL` to the deployment that issued the key. A saved session also belongs to the deployment where you signed in, so sign in again after you change the address.

> [accordion] The key was revoked or another credential was used
>
> A revoked, deleted, or deactivated key no longer works. CostGraph reports a deactivated key as `API key is inactive`. Check the key under **Settings > Account Settings > API Keys**. Installation tokens, such as the token an operator or agent uses, can't create API keys.

## Key creation errors

Choose the error category reported by the CLI.

> [accordion] Missing name or scopes
>
> `--name is required` means you must name the key.
>
> `at least one --scope is required` means you must request a permission. Run `costgraph api-keys scopes` for supported names.
>
> `each --scope must name one permission` means a value contains spaces. Repeat `--scope` or separate values with commas.

> [accordion] Tenant or scope approval mismatch
>
> If browser approval selects a different tenant, the CLI creates no key. Run the command again and approve the tenant passed with `--tenant`.
>
> If the CLI asks you to approve the scopes for the tenant, run it again and approve every requested scope.

> [accordion] Deployment does not support key creation
>
> If the deployment does not support CLI API key creation, check `COSTGRAPH_API_URL`. Use the dashboard to create the key on that deployment.

> [accordion] Your role cannot grant a permission
>
> Only organization owners can grant `organization:manage`. Remove that scope or ask an owner to create the key.
>
> Only admins can create keys that set prices or register deployments. Remove `pricing:write` and `deployment:register`, or ask an admin.

> [accordion] A key with this name already exists
>
> Choose a different value for `--name`.

> [accordion] The temporary approval was not revoked
>
> `Could not revoke the temporary approval session` means CostGraph created the key but left the approval session active.
>
> Remove it under **Settings > Account Settings > Connected apps**.

## Command reference

Commands are shown without the `costgraph` prefix. Add `--help` for the complete flag list.

### API key commands

Run each command with the `costgraph` prefix.

**api-keys scopes** `command`

Lists permissions supported by the deployment. Does not inspect an existing key. No sign-in required.

**api-keys create** `command`

Creates one key after browser approval. Returns `raw_api_key` once. Does not change the saved CLI login.

### Key creation flags

Pass these flags to `costgraph api-keys create`.

**--name** `string` *required*

Names the key. The name must not already exist.

**--tenant** `string`

Selects the tenant by name or UUID. Omitting it leaves the choice to browser approval.

**--scope** `string[]` *required*

Adds a permission to this key. Repeat the flag or use commas for multiple permissions. Requires at least one scope.

**--callback-port** `integer` (default: 9093)

Sets the local port used for browser approval.

**-o, --output** `string`

Use `json` to capture `raw_api_key`. Browser approval is still required.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.