---
title: "Provision cross-dashboard variables using Terraform | Grafana Cloud documentation"
description: "Learn how to provision global and folder-scoped cross-dashboard variables using the Grafana Terraform provider."
---

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

# Provision cross-dashboard variables using Terraform

Use the [Grafana Terraform provider](https://registry.terraform.io/providers/grafana/grafana/latest/docs) to manage [cross-dashboard variables](https://grafana.com/docs/grafana-cloud/learn-and-build/visualizations/dashboards/variables/cross-dashboard-variables/) as code. Cross-dashboard variables are available to multiple dashboards, either globally across the organization or to the dashboards in a single folder. Managing them as code lets you version-control the variables and keep them consistent across Grafana instances.

This guide outlines the steps to provision cross-dashboard variables with Terraform:

1. Configure the Grafana Terraform provider.
2. Define your global and folder-scoped variables in Terraform.
3. Run `terraform apply` to provision the variables.
4. Opt your dashboards in to the variables, either in the Grafana UI or with Terraform.

> Note
> 
> The Grafana Terraform provider is updated frequently. For the latest provider version and the complete reference for every resource and data source, refer to the [Grafana provider in the Terraform Registry](https://registry.terraform.io/providers/grafana/grafana/latest/docs).

## Before you begin

Before you begin, ensure you have the following:

- **Grafana instance**: A Grafana instance or Grafana Cloud stack.
- **Permissions**: The **Admin** role to create global variables, or the **Editor** role with **Edit** permission on the folder to create folder-scoped variables.
- **Terraform**: Terraform 1.9 or later installed on your machine. For more information, refer to the [Terraform install documentation](https://developer.hashicorp.com/terraform/install).
- **Grafana Terraform provider**: Version 4.30.0 or later of `grafana/grafana`, which adds the `grafana_apps_generic_resource` resource that this guide uses.

> Note
> 
> Save all the Terraform configuration files in the same directory.

## Configure the Grafana provider

Terraform authenticates against Grafana with a username and password or with a service account token. Use a service account token for Grafana Cloud.

### Create a service account token

To create a service account token, follow these steps:

1. Create a service account and assign it the **Admin** role, which is required to create global variables. To create a service account, refer to [Create a service account](https://grafana.com/docs/grafana-cloud/platform/security-and-account-management/security-and-access/authentication-and-permissions/service-accounts#create-a-service-account-in-grafana).
2. Add a token to the service account. To add a token, refer to [Add a token to a service account](https://grafana.com/docs/grafana-cloud/platform/security-and-account-management/security-and-access/authentication-and-permissions/service-accounts#add-a-token-to-a-service-account-in-grafana).
3. Copy the token and store it securely, because you can’t view it again after you leave the page.

### Create the provider configuration

Create a file named `main.tf` and add the following:

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

```terraform
terraform {
  required_version = ">= 1.9.0"

  required_providers {
    grafana = {
      source  = "grafana/grafana"
      version = ">= 4.30.0"
    }
  }
}

variable "grafana_auth" {
  type      = string
  sensitive = true
}

provider "grafana" {
  url  = "<GRAFANA_URL>"
  auth = var.grafana_auth

  # Required for Grafana OSS and Grafana Enterprise. Remove for Grafana Cloud.
  org_id = 1
}
```

Replace *`<GRAFANA_URL>`* with the root URL of your Grafana instance, without a trailing path, for example `http://localhost:3000` or `https://my-stack.grafana.net`.

The `grafana_auth` variable holds the service account token, or `<USERNAME>:<PASSWORD>` for a self-managed instance. To keep credentials out of your configuration files, set the variable through the `TF_VAR_grafana_auth` environment variable when you apply the configuration. You can also set the `GRAFANA_URL` and `GRAFANA_AUTH` environment variables, which override the provider block.

The `org_id` argument maps organization `1` to the `default` API namespace. In Grafana Cloud, omit `org_id`, because the `grafana_apps_generic_resource` resource discovers the stack namespace automatically.

## Define cross-dashboard variables

The provider doesn’t have a typed resource for variables. Instead, use the generic App Platform resource, [`grafana_apps_generic_resource`](https://registry.terraform.io/providers/grafana/grafana/latest/docs/resources/apps_generic_resource), to send the same Kubernetes-style manifest that Grafana stores, with `apiVersion` set to `dashboard.grafana.app/v2beta1` and `kind` set to `Variable`.

The examples in this section create the following variables:

- A global constant variable, `$env`.
- A global custom variable, `$region`.
- A folder-scoped custom variable, `$cluster`.

Create a file named `variables.tf` and add the examples from the following sections.

### Define a global variable

Global variables are available to every opted-in dashboard in the organization or stack. For global variables, `metadata.name` must equal `spec.spec.name`.

The following example creates a constant variable named `env`:

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

```terraform
resource "grafana_apps_generic_resource" "env" {
  manifest = {
    apiVersion = "dashboard.grafana.app/v2beta1"
    kind       = "Variable"
    metadata = {
      name = "env"
    }
    spec = {
      kind = "ConstantVariable"
      spec = {
        name  = "env"
        query = "prod"
      }
    }
  }
}
```

The following example creates a custom variable named `region` with three values:

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

```terraform
resource "grafana_apps_generic_resource" "region" {
  manifest = {
    apiVersion = "dashboard.grafana.app/v2beta1"
    kind       = "Variable"
    metadata = {
      name = "region"
    }
    spec = {
      kind = "CustomVariable"
      spec = {
        name             = "region"
        query            = "us-east-1,us-west-2,eu-west-1"
        current          = { text = "us-east-1", value = "us-east-1" }
        options          = []
        multi            = false
        includeAll       = false
        hide             = "dontHide"
        skipUrlSync      = false
        allowCustomValue = true
      }
    }
  }
}
```

### Define a folder-scoped variable

Folder-scoped variables are available only to the dashboards in the same folder. For folder-scoped variables:

- `metadata.name` must be `<VARIABLE_NAME>--<FOLDER_UID>`.
- The `grafana.app/folder` annotation must be set to the UID of the folder.
- The folder must already exist.

The following example creates a folder with the [`grafana_folder`](https://registry.terraform.io/providers/grafana/grafana/latest/docs/resources/folder) resource and a custom variable named `cluster` in that folder:

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

```terraform
resource "grafana_folder" "shared" {
  title = "Shared variables demo"
  uid   = "tf-cross-dash-vars"
}

resource "grafana_apps_generic_resource" "cluster" {
  manifest = {
    apiVersion = "dashboard.grafana.app/v2beta1"
    kind       = "Variable"
    metadata = {
      name = "cluster--tf-cross-dash-vars"
      annotations = {
        "grafana.app/folder" = grafana_folder.shared.uid
      }
    }
    spec = {
      kind = "CustomVariable"
      spec = {
        name             = "cluster"
        query            = "prod,staging"
        current          = { text = "prod", value = "prod" }
        options          = []
        multi            = false
        includeAll       = false
        hide             = "dontHide"
        skipUrlSync      = false
        allowCustomValue = true
      }
    }
  }

  depends_on = [grafana_folder.shared]
}
```

Don’t set `metadata.namespace` in the manifest. The provider sets the namespace to `default` for organization `1` or `stacks-<STACK_ID>` for Grafana Cloud.

### Load the manifest from a YAML file

Instead of writing the manifest in HCL, you can keep it in a YAML file and load it with the `yamldecode()` function.

The following `env.yaml` file defines the same variable as the `env` resource in [Define a global variable](https://grafana.com/docs/grafana-cloud/learn-and-build/as-code/terraform/grafana-resources/terraform-cross-dashboard-variables/#define-a-global-variable):

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

```yaml
apiVersion: dashboard.grafana.app/v2beta1
kind: Variable
metadata:
  name: env
spec:
  kind: ConstantVariable
  spec:
    name: env
    query: prod
```

Reference the file from the resource:

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

```terraform
resource "grafana_apps_generic_resource" "env" {
  manifest = yamldecode(file("${path.module}/env.yaml"))
}
```

### Allow changes from the Grafana UI

By default, you can’t edit Terraform-managed variables in the Grafana UI. To allow UI edits, set `allow_ui_updates` to `true` on the resource:

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

```terraform
resource "grafana_apps_generic_resource" "env" {
  allow_ui_updates = true
  manifest         = { /* ... */ }
}
```

## Provision the variables

In a terminal, run the following commands from the directory where all of the configuration files are located.

1. Initialize the working directory, which downloads the Grafana provider.
   
   sh ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy
   
   ```sh
   terraform init
   ```
2. Set your credentials, then preview the changes that Terraform makes.
   
   sh ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy
   
   ```sh
   export TF_VAR_grafana_auth='<TOKEN>'
   terraform plan
   ```
   
   Replace *`<TOKEN>`* with the service account token that you created in [Create a service account token](https://grafana.com/docs/grafana-cloud/learn-and-build/as-code/terraform/grafana-resources/terraform-cross-dashboard-variables/#create-a-service-account-token).
3. Apply the configuration files.
   
   sh ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy
   
   ```sh
   terraform apply
   ```
   
   Before applying any changes, Terraform displays the execution plan and requests your approval:
   
   console ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy
   
   ```console
   Plan: 4 to add, 0 to change, 0 to destroy.
   
   Do you want to perform these actions?
     Terraform will perform the actions described above.
     Only 'yes' will be accepted to approve.
   
     Enter a value:
   ```
   
   After you enter `yes`, Terraform creates the folder and the three variables:
   
   console ![Copy code to clipboard](https://grafana.com/media/images/icons/icon-copy-small-2.svg) Copy
   
   ```console
   Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
   ```

To verify the result, go to **Dashboards &gt; Variables** in Grafana. The `env` and `region` variables are listed as global variables, and the `cluster` variable is listed in the **Shared variables demo** folder.

## Opt a dashboard in to the variables

Dashboards don’t use cross-dashboard variables automatically. After you create the variables, opt each dashboard in to them.

Only dynamic dashboards (v2 schema) can use cross-dashboard variables. Folder-scoped variables are available only to dashboards in the same folder.

You can opt a dashboard in from the Grafana UI or with Terraform.

### Opt in from the Grafana UI

To opt in a dashboard from the Grafana UI, refer to [Add cross-dashboard variables to a dashboard](https://grafana.com/docs/grafana-cloud/learn-and-build/visualizations/dashboards/variables/cross-dashboard-variables/#add-cross-dashboard-variables-to-a-dashboard).

### Opt in with Terraform

A dashboard opts in to cross-dashboard variables through the `grafana.app/useCrossDashboardVariables` annotation. The value of the annotation is a JSON object with a selection for each scope:

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

```text
{
  "global": "all" | "none" | ["env", "region"],
  "folder": "all" | "none" | ["cluster"]
}
```

The following table describes the possible values:

Expand table

| Value                                      | Effect                                                                                       |
|--------------------------------------------|----------------------------------------------------------------------------------------------|
| `"all"`                                    | Adds every variable in that scope. New variables in that scope appear automatically.         |
| `"none"`                                   | Adds no variables from that scope.                                                           |
| Array of variable names                    | Adds only the listed variables. New variables in that scope don’t appear until you add them. |
| Empty array `[]`                           | Same as `"none"`.                                                                            |
| Scope omitted                              | Same as `"none"` for that scope.                                                             |
| Annotation missing, empty, or invalid JSON | The dashboard isn’t opted in and uses no cross-dashboard variables.                          |

Setting both scopes to `"none"` is the same as omitting the annotation.

The typed `grafana_apps_dashboard_dashboard_v2` resource exposes annotations as read-only, so it can’t set the annotation. Use the `grafana_apps_generic_resource` resource instead.

The following example creates a dashboard in the **Shared variables demo** folder that uses the `env`, `region`, and `cluster` variables:

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

```terraform
resource "grafana_apps_generic_resource" "demo_dashboard" {
  manifest = {
    apiVersion = "dashboard.grafana.app/v2"
    kind       = "Dashboard"
    metadata = {
      name = "tf-cross-dash-vars-demo"
      annotations = {
        "grafana.app/folder" = grafana_folder.shared.uid
        "grafana.app/useCrossDashboardVariables" = jsonencode({
          global = ["env", "region"]
          folder = ["cluster"]
        })
      }
    }
    spec = {
      title      = "Cross-dashboard variables demo"
      cursorSync = "Off"
      preload    = false
      elements   = {}
      layout     = { kind = "GridLayout", spec = { items = [] } }
      timeSettings = {
        timezone = "browser"
        from     = "now-6h"
        to       = "now"
      }
    }
  }

  depends_on = [
    grafana_apps_generic_resource.env,
    grafana_apps_generic_resource.region,
    grafana_apps_generic_resource.cluster,
  ]
}
```

The `dashboard.grafana.app/v2` API version requires Grafana 13 or later. On Grafana 12, set the dashboard `apiVersion` to `dashboard.grafana.app/v2beta1`. Variables always use `dashboard.grafana.app/v2beta1`.

After you apply the configuration, the `$env`, `$region`, and `$cluster` variables appear on the dashboard. Cross-dashboard variables are added at runtime. You can use them in queries, but Grafana doesn’t write them to the dashboard JSON when you save the dashboard. If the dashboard has a local variable with the same name as a cross-dashboard variable, the local variable takes precedence.

## Update and delete variables

To update a variable, change its configuration and run `terraform apply` again. For example, if you change the `query` of the `env` variable from `prod` to `staging`, Terraform updates the variable in place.

You can’t change the name (`spec.spec.name`) or the folder scope of an existing variable. To rename a variable or move it to another folder, remove the resource from your configuration and run `terraform apply` to delete the variable. Then, add a resource with the new name or scope and run `terraform apply` again.

To delete all the resources that Terraform manages in this directory, run the following command and enter `yes` to confirm:

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

```sh
terraform destroy
```

This command only removes the objects in the Terraform state of this directory, in this example the folder and the three variables.

## Import existing variables

To bring an existing cross-dashboard variable under Terraform management, add a matching resource block to your configuration and import the variable:

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

```sh
terraform import grafana_apps_generic_resource.env \
  dashboard.grafana.app/v2beta1/Variable/env
```

## Troubleshoot

The following table lists common errors and their likely causes:

Expand table

| Symptom                                                          | Likely cause                                                                                                                         |
|------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------|
| `Failed to resolve namespace`                                    | The provider for a self-managed instance is missing `org_id = 1`.                                                                    |
| `403 Forbidden` when you create a global variable                | The user or service account doesn’t have the **Admin** role. Editors can’t create global variables.                                  |
| `400` name mismatch                                              | `metadata.name` doesn’t match `<VARIABLE_NAME>` for global variables or `<VARIABLE_NAME>--<FOLDER_UID>` for folder-scoped variables. |
| `400` folder error                                               | The folder UID is missing or wrong, or the folder doesn’t exist.                                                                     |
| `409` already exists                                             | A variable with the same name already exists in that scope. Import it or choose a new name.                                          |
| `400` when you create a variable with `dashboard.grafana.app/v2` | Variables are only available in `dashboard.grafana.app/v2beta1`.                                                                     |
| The variable exists but doesn’t appear on the dashboard          | The dashboard isn’t opted in, or it isn’t a dynamic dashboard (v2 schema).                                                           |
| Global variables appear, but folder-scoped variables don’t       | The dashboard isn’t in the same folder as the variable.                                                                              |
| A variable shows a different value than expected                 | A local dashboard variable with the same name takes precedence over the cross-dashboard variable.                                    |

## Use Crossplane

If you use [Crossplane](https://github.com/grafana/crossplane-provider-grafana), the Grafana Crossplane provider wraps the same Terraform resource. Use the `Resource` kind (`oss.grafana.m.crossplane.io/v1alpha1`) and set `forProvider.manifest` to the same `dashboard.grafana.app/v2beta1` variable manifest as in the Terraform examples.

## Next steps

- To learn more about cross-dashboard variables, refer to [Cross-dashboard variables](https://grafana.com/docs/grafana-cloud/learn-and-build/visualizations/dashboards/variables/cross-dashboard-variables/).
- To learn more about App Platform resources in Grafana Cloud, refer to [Configure the Grafana provider for App Platform resources in Grafana Cloud](https://grafana.com/docs/grafana-cloud/learn-and-build/as-code/terraform/grafana-resources/terraform-app-platform-resources/).
- For all the options of the generic resource, refer to the [`grafana_apps_generic_resource` resource documentation](https://registry.terraform.io/providers/grafana/grafana/latest/docs/resources/apps_generic_resource).
