Skip to content
This repository was archived by the owner on Jan 15, 2024. It is now read-only.

Commit b2e5a8c

Browse files
Allow creating Grafana API keys from Cloud (#69)
* Allow creating Grafana API keys from Cloud Also add a function to create a temporary client. This will be used by Terraform. See grafana/terraform-provider-grafana#416 * Apply suggestions from code review Co-authored-by: Leandro López <leandro.lopez@grafana.com> Co-authored-by: Leandro López <leandro.lopez@grafana.com>
1 parent 544e218 commit b2e5a8c

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

cloud_grafana_api_key.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
}
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)