This is documentation for the next version of Grafana documentation. For the latest stable release, go to the latest version.
Manage saved queries using Terraform
This guide shows you how to manage saved queries, also known as the query library, using the Grafana Terraform provider. Managing saved queries as code lets you version-control your query library and keep it consistent across Grafana instances.
Note
Saved queries are only available on Grafana Enterprise and Grafana Cloud.
Before you begin
Before you begin, ensure you have the following:
- A Grafana Enterprise or Grafana Cloud instance. For more information on setting up a Grafana Cloud account, refer to Get started.
- Terraform installed on your machine. For more information on how to install Terraform, refer to the Terraform install documentation.
- A service account token with the Writer role for saved queries. For more information, refer to Roles, permissions, and RBAC and Service account tokens.
Configure the Grafana provider
Create a file named main.tf and add the following to set up the Grafana provider with the authentication required to manage saved queries:
terraform {
required_providers {
grafana = {
source = "grafana/grafana"
version = ">= 4.6.0"
}
}
}
provider "grafana" {
url = "<Grafana-URL>"
auth = "<Service-account-token>"
}Replace the following field values:
Grafana-URLwith the URL of your Grafana instance, for examplehttps://my-stack.grafana.net/Service-account-tokenwith the service account token that you created
Create a saved query resource
Create a file named saved-queries.tf and add the following:
resource "grafana_apps_queries_query_v1" "example" {
metadata {
uid = "example-saved-query"
}
spec {
title = "Requests per second"
description = "Prometheus rate of HTTP requests"
is_visible = true
tags = ["http", "prometheus"]
targets {
properties_json = jsonencode({
refId = "A"
expr = "rate(http_requests_total[$__rate_interval])"
datasource = {
type = "prometheus"
uid = "my-prometheus-uid"
}
})
}
}
}Because the shape of a data source query depends on the data source, the query stored in each target (properties_json), a target’s variable replacements (variables_json), and a variable’s value list (value_list_definition_json) are passed as raw JSON strings. Use jsonencode() to construct them.
The spec block supports the following fields:
For the complete schema, refer to the grafana_apps_queries_query_v1 resource documentation.
Import an existing saved query
To bring an existing saved query under Terraform management, import it using its UID:
terraform import grafana_apps_queries_query_v1.example example-saved-querySummary
In this guide, you learned how to create and import saved queries using Terraform.
To learn more about saved queries, refer to Saved queries.


