Hello!

In the previous post I showed how you can export dashboards from Grafana. Now let’s see how they can be imported into Grafana.

As always at the beginning there will be imports and main function

package grafana

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"

	"github.com/grafana-tools/sdk"
)

func main() {

}

I will add some parameters:

	var (
		filesInDir []os.FileInfo
		rawBoard   []byte
        err        error
        grafanaURL string
        apiKey     string
        directory  string
    )

filesInDir will store all dashboards from the file system. And rawBoard will contain the content of the file. directory directory in which dashboards will be read from. grafanaURL - Grafana url with port in the format http://127.0.0.1: 3030 and apiKey for authorization in Grafana. You need to enter your value in grafanaUR, apiKey and directory.

I am creating a Grafana client with which I will make requests to Grafana Api

	ctx := context.Background()

    c := sdk.NewClient(grafanaURL, apiKey, sdk.DefaultHTTPClient)

What left is to read the files and export them.

	filesInDir, err = ioutil.ReadDir(directory)
	if err != nil {
		log.Fatal(err)
    }

Now I loop through all files. Dashboards should be in json, if there other files except for json i need to skip them. If the file is json I write its content in rawBoard. And I am unmarshal this file into structure sdk.Board. I also create an object of type sdk.SetDashboardParams in which I specify in which folder to import the dashboard and whether to overwrite if such dashboard already exists. When all the parameters are ready, I call the SetDashboard method, which will export.

	for _, file := range filesInDir {
		if strings.HasSuffix(file.Name(), ".json") {
			if rawBoard, err = ioutil.ReadFile(fmt.Sprintf("%s/%s", directory, file.Name())); err != nil {
				log.Println(err)
				continue
			}
			var board sdk.Board
			if err = json.Unmarshal(rawBoard, &board); err != nil {
				log.Println(err)
				continue
			}
			params := sdk.SetDashboardParams{
				FolderID:  sdk.DefaultFolderId,
				Overwrite: true,
			}
			_, err := c.SetDashboard(ctx, board, params)
			if err != nil {
				log.Printf("error on importing dashboard %s", board.Title)
				continue
			}
		}
    }