Grafana: Data Sources

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Checked on 2026-11-09 against Grafana 13.3.x. Tested with Grafana Enterprise 13.3.0 in the hands-on lab: the Prometheus, Loki and Tempo data sources of the lab’s provisioning file load and report healthy, and the PromQL and LogQL examples of this page ran against the lab’s Prometheus and Loki.

To do this by hand, follow Add a Data Source.

Grafana stores no telemetry of its own. Every panel, Explore tab and alert rule reads from a data source: a connection to a system that holds the data, together with the plugin that knows how to query it. The data source decides which query language the editor speaks, which features (alerting, annotations, trace links) are available and, with a typo in a URL or a too-powerful database user, how a monitoring tool turns into an incident of its own. This page covers what is worth knowing before the first query: the catalogue, the three special data sources, how to configure the ones the Bookshelf lab uses both in the UI and as files, who may use them, and TestData for experiments.

Where the data source sits in the whole stack is described in Architecture and Ecosystem; queries are covered in Queries, Explore and Drilldown. The Prometheus side is covered in Prometheus, and the telemetry that reaches each backend in Telemetry Collection Pipelines.

Concepts

A data source has a type (the plugin: prometheus, loki, tempo, elasticsearch, postgres), a human name shown in pickers, and a UID, the stable identifier that dashboards, alert rules, correlations and exemplar links store. Names can be renamed; UIDs should not change. Choosing a UID yourself in provisioning (uid: prometheus) is what makes dashboards portable between environments, because the JSON of a dashboard refers to the UID, not to the name. If you leave the UID out, Grafana generates one, and a dashboard exported from one instance then points at a data source that does not exist on the next.

The same data source can be reached in two ways. access: proxy (shown as Server in the UI) sends the query from the browser to the Grafana server and from there to the backend; the credentials never reach the browser and the backend only needs to be visible from Grafana. access: direct (Browser) calls the backend from the browser, which needs CORS and exposes the URL; some data sources support only proxy. Use proxy.

Exactly one data source can be marked Default: it is preselected in new panels, in Explore and in new alert rules. Choose it deliberately, since alert rules created in a hurry end up on whatever was the default.

The core data sources by signal

The built-in data sources are grouped by what they hold. The groups below are the ones the Grafana documentation uses.

Signal Data sources In the Bookshelf lab

Metrics and time series

Prometheus (also used for Mimir, Thanos and Cortex through its type setting), Graphite, InfluxDB, OpenTSDB, AWS CloudWatch, Azure Monitor, Google Cloud Monitoring

Prometheus data source pointing at the Prometheus or Mimir that Alloy writes to

Logs

Loki, Elasticsearch

Loki for the grafana profile; Elasticsearch is the Kibana profile’s store, and can also be queried from Grafana

Traces

Tempo, Jaeger, Zipkin

Tempo

Profiles

Pyroscope

Not part of the lab

SQL databases

PostgreSQL, MySQL, Microsoft SQL Server

PostgreSQL, the Bookshelf database (business queries such as "books created today")

Alerting

Alertmanager

Not needed: the lab uses Grafana’s built-in Alertmanager

Testing

TestData

Used for experiments, see below

Plugins widen the list: the plugin catalogue contains many more data sources, and Enterprise plugins are marked in it. The catalogue is browsed under Connections in the left-hand menu, which is also where a data source is added.

Source: Grafana: Data sources (built-in core data sources) and Grafana plugin catalogue: data sources.

The special data sources

Three entries in the picker are not connections to a system.

Grafana generates random walk data, streams Live measurements and lists public files; in an annotation query it also returns Grafana’s own annotations, alerts and time regions. Snapshots use it automatically. It is mostly relevant for annotations, see Annotations and Links.

Mixed lets one panel run queries against several data sources in parallel. The first query uses the data source that was selected before Mixed was chosen, and existing queries cannot be switched to Mixed. Typical use in monitoring: a latency line from Prometheus next to a deployment-count line from PostgreSQL. Two caveats follow. Each query is still sent separately, so the panel is as slow as its slowest query. Combine the results of different sources with transformations (see Transformations and Expressions).

Dashboard reuses the complete result of another panel of the same dashboard, so the same query is not sent twice. It is available only while editing a dashboard panel, not in Explore, and it can pass all data or only annotations. Transformations narrow what the second panel shows. This is the right tool when a Stat, a Time series and a Table all show the same Prometheus result: one query, three views, one set of data source calls. The Dashboard data source cannot be used with server-side expressions.

Adding a data source in the UI

  1. In the left-hand menu open Connections, search for the type and select it.

  2. Fill the settings of that type (URL, authentication, type-specific options).

  3. Select Save & test. Grafana calls the backend’s health check and reports success or the error.

Only organization administrators can add data sources. By default every user of the organization can query every data source of the organization.

Verify in the lab: after Save & test succeeds, open Explore, select the data source and run a trivial query (up for Prometheus, {service_name="bookshelf"} for Loki). A green test only proves the health endpoint answers; an empty Explore result with a green test means the data is not arriving (see Telemetry Collection Pipelines).

The health check is also available over HTTP, which is useful in scripts after provisioning:

curl -s -u admin:admin http://localhost:3000/api/datasources/uid/prometheus/health

The lab uses the default administrator account; replace the credentials if the lab sets others. The /api routes are being deprecated in favour of /apis since Grafana 13, but they are not disabled and remain operative.

Provisioning data sources as files

Clicking works for one instance. A lab, a second environment or a rebuilt container needs the same data sources every time, so they are defined as YAML files read at startup from the provisioning/datasources directory (in the official image /etc/grafana/provisioning/datasources). A provisioned data source is read-only in the UI whatever the user’s permissions, and on a change you edit the file and restart Grafana or reload provisioning.

The structure of every file:

  • apiVersion: 1 at the top.

  • datasources: a list; if one already exists (same name and organization) Grafana updates it to match the file.

  • deleteDatasources: names (with orgId) to delete, processed before the list above is applied.

  • prune: true at the root deletes provisioned data sources that disappear from the file.

  • Per data source: name and type (required), uid, access, url, orgId (default 1), isDefault, basicAuth, basicAuthUser, user, database, withCredentials, editable, version, jsonData (type-specific settings stored as JSON) and secureJsonData (encrypted settings such as passwords and TLS certificates).

  • When several Grafana instances share files, set version and increase it on changes: Grafana updates a data source only when the file’s version is the same or higher, so a stale file cannot overwrite a newer configuration.

Values may use environment variables as $NAME or ${NAME} (values only, not keys or structure). Grafana expands ${NAME} first and then $NAME, so a password that itself contains a dollar sign can be expanded twice; write a literal dollar sign as $$. That is the reason the examples below escape the dollar sign of Grafana’s own ${__value.raw} macro as $${__value.raw}: without the escape Grafana treats it as an environment variable and replaces it with nothing.

Prometheus (and Mimir)

apiVersion: 1

datasources:
  - name: Prometheus
    type: prometheus
    uid: prometheus
    access: proxy
    url: http://prometheus:9090
    isDefault: true
    editable: false
    jsonData:
      httpMethod: POST
      prometheusType: Prometheus
      timeInterval: 15s
      manageAlerts: true
      allowAsRecordingRulesTarget: true
      exemplarTraceIdDestinations:
        - datasourceUid: tempo
          name: trace_id

What the keys do:

  • httpMethod: POST is recommended because it allows large queries; GET is for networks that block POST.

  • prometheusType tells Grafana which backend it talks to (Prometheus, Mimir, Thanos or Cortex). A wrong value can cause unexpected behaviour when querying metrics and labels, so set Mimir if the lab’s metrics store is Mimir.

  • timeInterval is the UI’s Scrape interval (default 15s) and should match the real scrape interval: Grafana derives the minimum query step and $__rate_interval from it, so a smaller value than reality produces rate() windows containing a single sample and gaps in the graph. The query timeout is a separate UI setting (default 60s).

  • manageAlerts (the Manage alerts via Alerting UI toggle, on by default) lets the Alerting UI list and manage the rules of this data source; allowAsRecordingRulesTarget (on by default) lets Grafana-managed recording rules write to it, see Recording Rules.

  • exemplarTraceIdDestinations links exemplars to a tracing data source: datasourceUid is the Tempo data source and name is the exemplar label that carries the trace ID. Exemplars exist only if Prometheus stores them (the exemplar storage feature flag) and the application exposes them.

  • The data source can also be set up for incremental querying (incrementalQueryOverlapWindow, beta) and for caching in the browser (cacheLevel); leave them at their defaults until a dashboard is demonstrably slow.

Loki

apiVersion: 1

datasources:
  - name: Loki
    type: loki
    uid: loki
    access: proxy
    url: http://loki:3100
    editable: false
    jsonData:
      maxLines: 1000
      timeout: 60
      derivedFields:
        - datasourceUid: tempo
          matcherRegex: '"trace_id":"(\\w+)"'
          name: TraceID
          url: '$${__value.raw}'
          urlDisplayLabel: 'View trace'
  • maxLines is the maximum number of log lines returned per query (default 1000); raising it makes a dashboard slower and a browser heavier, not the incident faster.

  • timeout is the HTTP timeout in seconds; the page states no default.

  • Derived fields turn a value extracted from each log line into a link. matcherRegex must contain a capture group (the first group is the value), name is shown as a label in the log details, url for an internal link is the query for the target data source with ${__value.raw} standing for the extracted value, and datasourceUid names the target. This is how a Bookshelf JSON log line with a trace ID gets a View trace button that opens the Tempo data source. An internal link only builds the query: if the trace is not in Tempo (sampled out, wrong tenant) the link opens an empty trace. One derived field produces one value per line, so several labels cannot be combined in one link, and a complicated regex slows the browser when many lines are rendered.

  • For a multi-tenant Loki add a custom header X-Scope-OrgID with the tenant ID.

Tempo

apiVersion: 1

datasources:
  - name: Tempo
    type: tempo
    uid: tempo
    access: proxy
    url: http://tempo:3200
    editable: false
    jsonData:
      tracesToLogsV2:
        datasourceUid: loki
        spanStartTimeShift: '-1m'
        spanEndTimeShift: '1m'
        tags: [{ key: 'service.name', value: 'service_name' }]
        filterByTraceID: true
        filterBySpanID: false
      tracesToMetrics:
        datasourceUid: prometheus
        spanStartTimeShift: '-1m'
        spanEndTimeShift: '1m'
        tags: [{ key: 'service.name', value: 'service' }]
        queries:
          - name: 'Request rate'
            query: 'sum(rate(traces_spanmetrics_calls_total{$$__tags}[5m]))'
      serviceMap:
        datasourceUid: prometheus
      nodeGraph:
        enabled: true
      streamingEnabled:
        search: true
        metrics: true
  • tracesToLogsV2 adds a button on each span that opens the logs of the same service around the span in the Loki data source. tags maps span attributes (service.name) to log labels (service_name), the time shifts widen the search window around the span, and filterByTraceID narrows the logs to that trace, which is the usual choice when the logs carry the trace ID.

  • tracesToMetrics does the same towards Prometheus with named queries in which $__tags expands to the mapped tags. The metric traces_spanmetrics_calls_total exists only if span metrics are generated (by the Tempo metrics generator or by the collector); with no span metrics the button opens an empty graph.

  • serviceMap names the Prometheus data source that holds the span metrics the service graph is drawn from, and nodeGraph enables the node graph view of that graph.

  • Streaming (streamingEnabled) shows search and metrics results as they arrive; self-managed Tempo needs stream_over_http_enabled: true in its own configuration (Tempo 2.2 or later).

  • The data source also supports tracesToProfiles for Pyroscope, not used in the lab.

Reference: Grafana: Provision the Tempo data source and Grafana: Configure the Tempo data source. The reverse direction (logs to traces, metrics to traces) is the Loki derived field and the Prometheus exemplar above; rule-based links between arbitrary data sources are correlations, covered in Queries, Explore and Drilldown.

Elasticsearch

Grafana can query the Elasticsearch of the Kibana profile too: useful when one team already has Grafana dashboards and the logs live in Elastic. Supported are Elasticsearch 7.17 or later, 8.x, 9.x and Elastic Cloud Serverless.

apiVersion: 1

datasources:
  - name: Elasticsearch logs
    type: elasticsearch
    uid: elasticsearch-logs
    access: proxy
    url: http://elasticsearch:9200
    editable: false
    jsonData:
      index: 'logs-*'
      timeField: '@timestamp'
      logMessageField: message
      logLevelField: log.level
  • index accepts a wildcard (logs-*), a name, a bracketed time pattern ([logstash-]YYYY.MM.DD, which needs interval set to Daily, Hourly and so on) or a cross-cluster pattern (cluster:logs-*). Put the name in jsonData.index, not in the deprecated database field. Data streams are matched with a wildcard, so no time pattern is needed.

  • timeField defaults to @timestamp.

  • logMessageField and logLevelField tell the Logs view which fields are the message and the level; if the level field is unset or missing, Grafana tries to infer it from the text and otherwise shows the level as unknown. The field name depends on the mapping: ECS uses log.level, so check it in the index before provisioning.

Reference: Grafana: Configure the Elasticsearch data source. Elasticsearch itself is covered in Elasticsearch.

PostgreSQL

The Bookshelf database holds business facts that no metric has: how many books were created today, how many reservations are overdue. Querying it from Grafana is legitimate, but a monitoring tool should never be able to change the data, so create a dedicated user that can only read.

CREATE USER grafanareader WITH PASSWORD 'change-me';
GRANT USAGE ON SCHEMA public TO grafanareader;
GRANT SELECT ON public.book, public.loan TO grafanareader;
apiVersion: 1

datasources:
  - name: Bookshelf database
    type: postgres
    uid: bookshelf-db
    url: postgres:5432
    user: grafanareader
    editable: false
    secureJsonData:
      password: ${BOOKSHELF_DB_PASSWORD}
    jsonData:
      database: bookshelf
      sslmode: disable
      maxOpenConns: 10
      maxIdleConns: 10
      connMaxLifetime: 14400
      timescaledb: false
  • The password goes in secureJsonData (encrypted in the Grafana database) and, as here, is read from an environment variable so that it is not committed. The table names above are the lab’s example and must match the Bookshelf schema.

  • sslmode is one of disable, require, verify-ca, verify-full; a database outside the lab’s private network should use at least require.

  • maxOpenConns and maxIdleConns default to 100; lower them for a database with a small max_connections or behind PgBouncer. connMaxLifetime is in seconds (default 14400, four hours).

  • postgresVersion (not set above) is a version code, 900 for 9.0 up to 1500 for 15 in the reference, that the query builder uses; Grafana detects it when the data source is saved in the UI if it can connect. timescaledb changes the $__timeGroup macro for TimescaleDB.

  • The plugin ID is grafana-postgresql-datasource; type: postgres remains a supported alias.

Permissions, caching and the provisioned lock

Who can do what with a data source is set on its Permissions tab, in three levels: Query (run queries), Edit (query, change the configuration, delete) and Admin (everything, including changing the permissions). They can be granted to users, service accounts, teams or the basic roles. This tab is a Grafana Enterprise and Grafana Cloud feature; in the OSS edition every user of the organization can query every data source, which is a reason to keep a database data source read-only and to separate organizations when teams must not see each other’s data. Label-based access control (LBAC) for Loki and Prometheus, which restricts which streams or series a team sees, is likewise an Enterprise and Cloud feature.

Query and resource caching (also Enterprise and Cloud) stores results in memory, Redis or Memcached for a time-to-live, so repeated dashboard loads do not hit the backend. It is switched on per data source on its Cache tab. When a graph is "stuck", remember it can be a cached answer; sending the header X-Cache-Skip: true bypasses the cache when debugging with curl.

Provisioned data sources are read-only in the UI. On Grafana Cloud you create an editable copy that points to the same backend, which does not follow later changes of the original.

TestData for experiments

TestData ships with Grafana and needs no installation: it generates simulated time series, logs, traces and annotations, with 33 documented scenarios, without any backend. Use it to learn the query editor, to build a transformation pipeline when the real data is not there yet, to prototype an alert rule, and to demonstrate a dashboard in a place without Prometheus. The alerting guide of the data source shows how to prototype alert rules with simulated data. A rule tested only with TestData proves the rule mechanics, not the query: the final test is always against the real data source, with a forced breach (see Alerting Fundamentals).

Reference: Grafana: TestData, with the query editor scenario list.

Lab: all data sources in one file

The lab provisions the data sources in a single file (the full provisioned setup is in Hands-on Lab). Verification after docker compose --profile grafana up:

  1. Connections > Data sources lists them with a lock icon (provisioned).

  2. Run the health check of each UID (prometheus, loki, tempo) with the curl above; each must answer with status OK.

  3. In Explore run up, a Loki query for the bookshelf service, and a Tempo search; open a trace and use the span’s logs button to confirm tracesToLogsV2, and a log line’s View trace button to confirm the derived field.

  4. Break one thing on purpose (for example a wrong port in url), restart, and read the error of Save & test: it is the message you will see in a real incident.

In the books

Hernandez (Building IoT Visualizations using Grafana) explains the data source as the origin of everything Grafana shows and adds practical chapters on SQL, NoSQL, time series databases, Google Sheets and CSV files and Grafana Live. The concepts hold. Since the book’s Grafana 8 the plugin model changed: the Angular plugins it relies on for some of these sources were removed in Grafana 12.0, so check the plugin catalogue for a React-based replacement. McCollam (Getting Started with Grafana) shows the data sources HTTP API and file provisioning; both remain, with the provisioning shape above, but the numeric data source ID endpoints are disabled by default since Grafana 13.0 (use the UID).