|
| 1 | +package grafana |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "strconv" |
| 7 | + |
| 8 | + gapi "github.com/grafana/grafana-api-golang-client" |
| 9 | + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" |
| 10 | + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" |
| 11 | +) |
| 12 | + |
| 13 | +func DatasourceFolder() *schema.Resource { |
| 14 | + return &schema.Resource{ |
| 15 | + Description: ` |
| 16 | +* [Official documentation](https://grafana.com/docs/grafana/latest/dashboards/dashboard_folders/) |
| 17 | +* [HTTP API](https://grafana.com/docs/grafana/latest/http_api/folder/) |
| 18 | +`, |
| 19 | + ReadContext: dataSourceFolderRead, |
| 20 | + Schema: map[string]*schema.Schema{ |
| 21 | + "title": { |
| 22 | + Type: schema.TypeString, |
| 23 | + Required: true, |
| 24 | + Description: "The name of the Grafana folder.", |
| 25 | + }, |
| 26 | + "id": { |
| 27 | + Type: schema.TypeInt, |
| 28 | + Computed: true, |
| 29 | + Description: "The numerical ID of the Grafana folder.", |
| 30 | + }, |
| 31 | + "uid": { |
| 32 | + Type: schema.TypeString, |
| 33 | + Computed: true, |
| 34 | + Description: "The uid of the Grafana folder.", |
| 35 | + }, |
| 36 | + }, |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +func findFolderWithTitle(client *gapi.Client, title string) (*gapi.Folder, error) { |
| 41 | + folders, err := client.Folders() |
| 42 | + if err != nil { |
| 43 | + return nil, err |
| 44 | + } |
| 45 | + |
| 46 | + for _, f := range folders { |
| 47 | + if f.Title == title { |
| 48 | + return &f, nil |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return nil, fmt.Errorf("no folder with title %q", title) |
| 53 | +} |
| 54 | + |
| 55 | +func dataSourceFolderRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { |
| 56 | + client := meta.(*client).gapi |
| 57 | + title := d.Get("title").(string) |
| 58 | + folder, err := findFolderWithTitle(client, title) |
| 59 | + |
| 60 | + if err != nil { |
| 61 | + return diag.FromErr(err) |
| 62 | + } |
| 63 | + |
| 64 | + id := strconv.FormatInt(folder.ID, 10) |
| 65 | + d.SetId(id) |
| 66 | + d.Set("uid", folder.UID) |
| 67 | + d.Set("title", folder.Title) |
| 68 | + |
| 69 | + return nil |
| 70 | +} |
0 commit comments