Add Prometheus Datasources in Grafana

Analyzing data.
Reading Time: 2 minutes

Add as many as prometheus datasource into grafana with the help of terraform scripts.

Prerequisite

  1. Prometheus Deployed & endpoint URL of prometheus. Headless service name if on same cluster or URL if prometheus deployed on another server.
  2. Grafana endpoint URL & Port number. (default is 3000)
  3. Username & Password for admin access.

Setup Authentication

  1. export environment variable for authentication
export GRAFANA_AUTH="admin_username:admin_password"
  1. Add Grafana URL & port in main.tf file
provider "grafana" {
  url  = "http://your-grafana-url:port"
}

Add Prometheus Datasources

Step 1

  1. Open datasources.auto.tfvars file.
  2. Add a map configs for your datasource
  {
    source_name = "test-app"
    type        = "prometheus"
    url         = "http://prometheus-operated.test.svc.cluster.local:9090"
  }

Terraform Scripts & modules

main.tf

provider "grafana" {
  url  = "localhost:3000"
}

terraform {
  required_providers {
    grafana = {
      source  = "grafana/grafana"
      version = "1.11.0"
    }
  }
}

module "grafana_datasoures" {
  source                  = "./grafana_module"
  prometheus_data_sources = var.prometheus_data_sources
}

variables.tf

variable "prometheus_data_sources" {
  description = "list of prometheus data sources"
}

datasources.auto.tfvars

prometheus_data_sources = [
#   {
#     source_name = "test-app"
#     type        = "prometheus"
#     url         = "http://prometheus-operated.test.svc.cluster.local:9090"
#   },
# uncomment below map & add your configs
#   {
#     source_name = "test-app"
#     type        = "prometheus"
#     url         = "http://prometheus-operated.test.svc.cluster.local:9090"
#   }
]

terraform grafana module

main.tf

terraform {
  required_providers {
    grafana = {
      source  = "grafana/grafana"
      version = "1.11.0"
    }
  }
}

datasource.tf

resource "grafana_data_source" "prometheus" {
  for_each = local.prometheus_data_sources_local
  type     = "prometheus"
  name     = each.key
  url      = each.value.url

  json_data {
    http_method = "POST"
  }
}


locals {
  prometheus_data_sources_local = {
    for ds in var.prometheus_data_sources :
    ds.source_name => {
      url = ds.url
    }
    if ds.type == "prometheus"
  }
}

variables.tf

variable "prometheus_data_sources" {
  description = "name, & URL for prometheus resource"
  default     = []
}

Run terraform

  1. Install provider plugins
terraform init
  1. Check Terraform plan
terraform plan
  1. Apply the terraform configurations
terraform apply

And then you can see datasources is added into grafana

Written by 

Rahul Soni is a Software Consultant at Knoldus Software. He is always charged up for new things & learnings. He is dedicated to his work and believes in quality output. He loves to take deep dives into cloud technologies & different tools.