|
| 1 | +package grafana |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + gapi "github.com/grafana/grafana-api-golang-client" |
| 8 | + "github.com/hashicorp/terraform-plugin-sdk/v2/diag" |
| 9 | + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" |
| 10 | +) |
| 11 | + |
| 12 | +func DatasourceUser() *schema.Resource { |
| 13 | + return &schema.Resource{ |
| 14 | + Description: ` |
| 15 | +* [Official documentation](https://grafana.com/docs/grafana/latest/manage-users/server-admin/server-admin-manage-users/) |
| 16 | +* [HTTP API](https://grafana.com/docs/grafana/latest/http_api/user/) |
| 17 | +
|
| 18 | +This resource uses Grafana's admin APIs for creating and updating users which |
| 19 | +does not currently work with API Tokens. You must use basic auth. |
| 20 | +`, |
| 21 | + ReadContext: dataSourceUserRead, |
| 22 | + Schema: map[string]*schema.Schema{ |
| 23 | + "user_id": { |
| 24 | + Type: schema.TypeInt, |
| 25 | + Optional: true, |
| 26 | + Default: -1, |
| 27 | + Description: "The numerical ID of the Grafana user.", |
| 28 | + }, |
| 29 | + "email": { |
| 30 | + Type: schema.TypeString, |
| 31 | + Optional: true, |
| 32 | + Default: "", |
| 33 | + Description: "The email address of the Grafana user.", |
| 34 | + }, |
| 35 | + "login": { |
| 36 | + Type: schema.TypeString, |
| 37 | + Optional: true, |
| 38 | + Default: "", |
| 39 | + Description: "The username for the Grafana user.", |
| 40 | + }, |
| 41 | + "name": { |
| 42 | + Type: schema.TypeString, |
| 43 | + Computed: true, |
| 44 | + Description: "The display name for the Grafana user.", |
| 45 | + }, |
| 46 | + "is_admin": { |
| 47 | + Type: schema.TypeBool, |
| 48 | + Computed: true, |
| 49 | + Description: "Whether the user is an admin.", |
| 50 | + }, |
| 51 | + }, |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +func dataSourceUserRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics { |
| 56 | + client := meta.(*client).gapi |
| 57 | + |
| 58 | + var user gapi.User |
| 59 | + var err error |
| 60 | + if id := d.Get("user_id").(int); id >= 0 { |
| 61 | + user, err = client.User(int64(id)) |
| 62 | + } else if email := d.Get("email").(string); email != "" { |
| 63 | + user, err = client.UserByEmail(email) |
| 64 | + } else if login := d.Get("login").(string); login != "" { |
| 65 | + user, err = client.UserByEmail(login) |
| 66 | + } else { |
| 67 | + err = fmt.Errorf("must specify one of user_id, email, or login") |
| 68 | + } |
| 69 | + |
| 70 | + if err != nil { |
| 71 | + return diag.FromErr(err) |
| 72 | + } |
| 73 | + |
| 74 | + d.SetId(fmt.Sprintf("%d", user.ID)) |
| 75 | + d.Set("email", user.Email) |
| 76 | + d.Set("name", user.Name) |
| 77 | + d.Set("login", user.Login) |
| 78 | + d.Set("is_admin", user.IsAdmin) |
| 79 | + |
| 80 | + return nil |
| 81 | +} |
0 commit comments