-
Notifications
You must be signed in to change notification settings - Fork 218
/
data_source_service_account.go
63 lines (58 loc) · 2 KB
/
data_source_service_account.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package grafana
import (
"context"
"fmt"
"github.com/grafana/grafana-openapi-client-go/client"
"github.com/grafana/grafana-openapi-client-go/client/service_accounts"
"github.com/grafana/grafana-openapi-client-go/models"
"github.com/grafana/terraform-provider-grafana/v2/internal/common"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
func datasourceServiceAccount() *schema.Resource {
return &schema.Resource{
Description: `
* [Official documentation](https://grafana.com/docs/grafana/latest/administration/service-accounts/)
* [HTTP API](https://grafana.com/docs/grafana/latest/developers/http_api/serviceaccount/#service-account-api)
`,
ReadContext: datasourceServiceAccountRead,
Schema: common.CloneResourceSchemaForDatasource(resourceServiceAccount().Schema, map[string]*schema.Schema{
"org_id": orgIDAttribute(),
"name": {
Type: schema.TypeString,
Required: true,
Description: "The name of the Service Account.",
},
}),
}
}
func datasourceServiceAccountRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client, orgID := OAPIClientFromNewOrgResource(meta, d)
name := d.Get("name").(string)
sa, err := findServiceAccountByName(client, name)
if err != nil {
return diag.FromErr(err)
}
d.SetId(MakeOrgResourceID(orgID, sa.ID))
return ReadServiceAccount(ctx, d, meta)
}
func findServiceAccountByName(client *client.GrafanaHTTPAPI, name string) (*models.ServiceAccountDTO, error) {
var page int64 = 0
for {
params := service_accounts.NewSearchOrgServiceAccountsWithPagingParams().WithPage(&page)
resp, err := client.ServiceAccounts.SearchOrgServiceAccountsWithPaging(params)
if err != nil {
return nil, err
}
serviceAccounts := resp.Payload.ServiceAccounts
if len(serviceAccounts) == 0 {
break
}
for _, sa := range serviceAccounts {
if sa.Name == name {
return sa, nil
}
}
}
return nil, fmt.Errorf("service account %q not found", name)
}