Skip to content

Commit 326804a

Browse files
committed
Add support for providing additional HTTP headers
1 parent 42597b2 commit 326804a

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

grafana/provider.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
package grafana
22

33
import (
4+
"encoding/json"
45
"net/url"
6+
"os"
57
"strings"
68

79
"github.com/hashicorp/go-cleanhttp"
@@ -28,6 +30,14 @@ func Provider() terraform.ResourceProvider {
2830
DefaultFunc: schema.EnvDefaultFunc("GRAFANA_AUTH", nil),
2931
Description: "Credentials for accessing the Grafana API.",
3032
},
33+
"headers": {
34+
Type: schema.TypeMap,
35+
Optional: true,
36+
Sensitive: true,
37+
Elem: &schema.Schema{Type: schema.TypeString},
38+
Description: "Optional. HTTP headers mapping keys to values used for accessing the Grafana API.",
39+
DefaultFunc: JsonEnvDefaultFunc("GRAFANA_HTTP_HEADERS", nil),
40+
},
3141
},
3242

3343
ResourcesMap: map[string]*schema.Resource{
@@ -58,10 +68,46 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) {
5868
} else {
5969
cfg.APIKey = auth[0]
6070
}
71+
72+
headersObj := d.Get("headers").(map[string]interface{})
73+
if headersObj != nil && len(headersObj) == 0 {
74+
// Workaround for a bug when DefaultFunc returns a TypeMap
75+
headersObjAbs, _ := JsonEnvDefaultFunc("GRAFANA_HTTP_HEADERS", nil)()
76+
headersObj = headersObjAbs.(map[string]interface{})
77+
}
78+
if headersObj != nil {
79+
// Convert headers from map[string]interface{} to map[string]string
80+
headers := make(map[string]string)
81+
for k, v := range headersObj {
82+
switch v := v.(type) {
83+
case string:
84+
headers[k] = v
85+
}
86+
}
87+
cfg.HTTPHeaders = headers
88+
}
89+
6190
client, err := gapi.New(d.Get("url").(string), cfg)
6291
if err != nil {
6392
return nil, err
6493
}
6594

6695
return client, nil
6796
}
97+
98+
// JsonEnvDefaultFunc is a helper function that parses the given environment
99+
// variable as a JSON object, or returns the default value otherwise.
100+
func JsonEnvDefaultFunc(k string, dv interface{}) schema.SchemaDefaultFunc {
101+
return func() (interface{}, error) {
102+
if valStr := os.Getenv(k); valStr != "" {
103+
var valObj map[string]interface{}
104+
err := json.Unmarshal([]byte(valStr), &valObj)
105+
if err != nil {
106+
return nil, err
107+
}
108+
return valObj, nil
109+
}
110+
111+
return dv, nil
112+
}
113+
}

0 commit comments

Comments
 (0)