Skip to content

Instantly share code, notes, and snippets.

@tcnksm
Last active March 3, 2022 06:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tcnksm/5ab02360dfea8bb7cd1836f61d62021c to your computer and use it in GitHub Desktop.
Save tcnksm/5ab02360dfea8bb7cd1836f61d62021c to your computer and use it in GitHub Desktop.
Export all Grafana dashboards via HTTP API in Golang
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)
func main() {
os.Exit(run())
}
func run() int {
host := "grafana.example.com"
auth := os.Getenv("GF_AUTH")
if len(auth) == 0 {
log.Printf("[ERROR] Set GF_AUTH")
return 1
}
client := http.DefaultClient
// Get all dashboards URI via search API
urlStr := fmt.Sprintf("https://%s/%s", host, "api/search")
req, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
log.Printf("[ERROR] %s", err)
return 1
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+auth)
res, err := client.Do(req)
if err != nil {
log.Printf("[ERROR] %s", err)
return 1
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
log.Printf("[ERROR] Invalid status: %s", res.Status)
return 1
}
search := []struct {
URI string `json:"uri"`
}{}
decorder := json.NewDecoder(res.Body)
if err := decorder.Decode(&search); err != nil {
log.Printf("[ERROR] %s", err)
return 1
}
log.Printf("[INFO] Number of dashbord: %d", len(search))
for _, s := range search {
urlStr := fmt.Sprintf("https://%s/api/dashboards/%s", host, s.URI)
req, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
log.Printf("[ERROR] %s", err)
return 1
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+auth)
res, err := client.Do(req)
if err != nil {
log.Printf("[ERROR] %s", err)
return 1
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
log.Printf("[ERROR] Invalid status: %s", res.Status)
return 1
}
var db map[string]interface{}
decorder := json.NewDecoder(res.Body)
if err := decorder.Decode(&db); err != nil {
log.Printf("[ERROR] %s", err)
return 1
}
f, err := os.Create(s.URI + ".json")
if err != nil {
log.Printf("[ERROR] %s", err)
return 1
}
encoder := json.NewEncoder(f)
if err := encoder.Encode(db["dashboard"]); err != nil {
log.Printf("[ERROR] %s", err)
return 1
}
}
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment