github.com/GoogleCloudPlatform/terraformer@v0.8.18/providers/grafana/dashboard.go (about) 1 package grafana 2 3 import ( 4 "encoding/json" 5 "fmt" 6 7 "github.com/GoogleCloudPlatform/terraformer/terraformutils" 8 gapi "github.com/grafana/grafana-api-golang-client" 9 ) 10 11 type DashboardGenerator struct { 12 GrafanaService 13 } 14 15 func (g *DashboardGenerator) InitResources() error { 16 client, err := g.buildClient() 17 if err != nil { 18 return fmt.Errorf("unable to build grafana client: %v", err) 19 } 20 21 err = g.createDashboardResources(client) 22 if err != nil { 23 return err 24 } 25 26 return nil 27 } 28 29 func (g *DashboardGenerator) createDashboardResources(client *gapi.Client) error { 30 dashboards, err := client.Dashboards() 31 if err != nil { 32 return fmt.Errorf("unable to list grafana dashboards: %v", err) 33 } 34 35 for _, dashboard := range dashboards { 36 // search result doesn't include slug, so need to look up dashboard. 37 dash, err := client.DashboardByUID(dashboard.UID) 38 if err != nil { 39 return fmt.Errorf("unable to read grafana dashboard %s: %v", dashboard.Title, err) 40 } 41 42 configJSON, err := json.MarshalIndent(dash.Model, "", " ") 43 if err != nil { 44 return fmt.Errorf("unable to marshal configuration for grafana dashboard %s: %v", dashboard.Title, err) 45 } 46 47 filename := fmt.Sprintf("dashboard-%s.json", dash.Meta.Slug) 48 resource := terraformutils.NewResource( 49 dashboard.UID, 50 dashboard.Title, 51 "grafana_dashboard", 52 "grafana", 53 map[string]string{}, 54 []string{}, 55 map[string]interface{}{ 56 "config_json": fmt.Sprintf("file(\"data/%s\")", filename), 57 "folder": dashboard.FolderID, 58 }, 59 ) 60 resource.DataFiles = map[string][]byte{ 61 filename: configJSON, 62 } 63 g.Resources = append(g.Resources, resource) 64 } 65 66 return nil 67 }