terraformgrafana

How to Dynamically Referrancing UID in Grafana Dashboard Via Terraform?


Sample tf code

data "grafana_data_source" "azure_monitor" {
  name = "grafana-azure-monitor-datasource"

resource "grafana_dashboard" "test" {
  folder      = grafana_folder.rule_folder.uid
  config_json = file("${path.module}/VMDASHBOARD.json")
}

But here Problem is that when I referencing uid inside json file

VMDASHBOARD.json

uid: ${data.grafana_data_source.azure_monitor.uid}

it is not taking dynamically and showing illegal uid


Solution

  • This can be fixed by using the templatefile built-in function instead of file. The templatefile function enables you to dynamically populate the values in a templated file. In your case it would look something like:

    data "grafana_data_source" "azure_monitor" {
      name = "grafana-azure-monitor-datasource"
    
    resource "grafana_dashboard" "test" {
      folder      = grafana_folder.rule_folder.uid
      config_json = templatefile("${path.module}/VMDASHBOARD.json", {
        dasbhoard_uid = data.grafana_data_source.azure_monitor.uid
      })
    }
    

    For this to work as expected, the change would also need to happen in the VMDASHBOARD.json file, by doing the following:

    uid: ${dasbhoard_uid}
    

    This way, you are telling terraform to replace the variable dasbhoard_uid in the templated file by the value you are getting from the data source.