|
| 1 | +package gapi |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +// This function creates a API key inside the Grafana instance running in stack `stack`. It's used in order |
| 11 | +// to provision API keys inside Grafana while just having access to a Grafana Cloud API key. |
| 12 | +// |
| 13 | +// See https://grafana.com/docs/grafana-cloud/api/#create-grafana-api-keys for more information. |
| 14 | +func (c *Client) CreateGrafanaAPIKeyFromCloud(stack string, input *CreateAPIKeyRequest) (*CreateAPIKeyResponse, error) { |
| 15 | + data, err := json.Marshal(input) |
| 16 | + if err != nil { |
| 17 | + return nil, err |
| 18 | + } |
| 19 | + |
| 20 | + resp := &CreateAPIKeyResponse{} |
| 21 | + err = c.request("POST", fmt.Sprintf("/api/instances/%s/api/auth/keys", stack), nil, bytes.NewBuffer(data), resp) |
| 22 | + return resp, err |
| 23 | +} |
| 24 | + |
| 25 | +// The Grafana Cloud API is disconnected from the Grafana API on the stacks unfortunately. That's why we can't use |
| 26 | +// the Grafana Cloud API key to fully manage API keys on the Grafana API. The only thing we can do is to create |
| 27 | +// a temporary Admin key, and create a Grafana API client with that. |
| 28 | +func (c *Client) CreateTemporaryStackGrafanaClient(stackSlug, tempKeyPrefix string, tempKeyDuration time.Duration) (tempClient *Client, cleanup func() error, err error) { |
| 29 | + stack, err := c.StackBySlug(stackSlug) |
| 30 | + if err != nil { |
| 31 | + return nil, nil, err |
| 32 | + } |
| 33 | + |
| 34 | + name := fmt.Sprintf("%s-%d", tempKeyPrefix, time.Now().UnixNano()) |
| 35 | + req := &CreateAPIKeyRequest{ |
| 36 | + Name: name, |
| 37 | + Role: "Admin", |
| 38 | + SecondsToLive: int64(tempKeyDuration.Seconds()), |
| 39 | + } |
| 40 | + |
| 41 | + apiKey, err := c.CreateGrafanaAPIKeyFromCloud(stackSlug, req) |
| 42 | + if err != nil { |
| 43 | + return nil, nil, err |
| 44 | + } |
| 45 | + |
| 46 | + client, err := New(stack.URL, Config{APIKey: apiKey.Key}) |
| 47 | + if err != nil { |
| 48 | + return nil, nil, err |
| 49 | + } |
| 50 | + |
| 51 | + cleanup = func() error { |
| 52 | + _, err = client.DeleteAPIKey(apiKey.ID) |
| 53 | + return err |
| 54 | + } |
| 55 | + |
| 56 | + return client, cleanup, nil |
| 57 | +} |
0 commit comments