Reading Time: 2 minutes

Add as many as prometheus datasource into grafana with the help of terraform scripts.
Prerequisite
- Prometheus Deployed & endpoint URL of prometheus. Headless service name if on same cluster or URL if prometheus deployed on another server.
- Grafana endpoint URL & Port number. (default is 3000)
- Username & Password for admin access.
Setup Authentication
- export environment variable for authentication
export GRAFANA_AUTH="admin_username:admin_password"
- Add Grafana URL & port in main.tf file
provider "grafana" {
url = "http://your-grafana-url:port"
}
Add Prometheus Datasources
Step 1
- Open datasources.auto.tfvars file.
- 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
- Install provider plugins
terraform init
- Check Terraform plan
terraform plan
- Apply the terraform configurations
terraform apply
And then you can see datasources is added into grafana
