11package grafana
22
33import (
4+ "encoding/json"
5+ "os"
6+
47 "github.com/hashicorp/terraform/helper/logging"
58 "github.com/hashicorp/terraform/helper/schema"
69 "github.com/hashicorp/terraform/terraform"
@@ -24,6 +27,14 @@ func Provider() terraform.ResourceProvider {
2427 DefaultFunc : schema .EnvDefaultFunc ("GRAFANA_AUTH" , nil ),
2528 Description : "Credentials for accessing the Grafana API." ,
2629 },
30+ "headers" : {
31+ Type : schema .TypeMap ,
32+ Optional : true ,
33+ Sensitive : true ,
34+ Elem : & schema.Schema {Type : schema .TypeString },
35+ Description : "Optional. HTTP headers mapping keys to values used for accessing the Grafana API." ,
36+ DefaultFunc : EnvDefaultJsonFunc ("GRAFANA_HTTP_HEADERS" , nil ),
37+ },
2738 },
2839
2940 ResourcesMap : map [string ]* schema.Resource {
@@ -39,9 +50,28 @@ func Provider() terraform.ResourceProvider {
3950}
4051
4152func providerConfigure (d * schema.ResourceData ) (interface {}, error ) {
53+ headersObj := d .Get ("headers" ).(map [string ]interface {})
54+ if headersObj != nil && len (headersObj ) == 0 {
55+ // Workaround for a bug when DefaultFunc returns a TypeMap
56+ headersObjAbs , _ := EnvDefaultJsonFunc ("GRAFANA_HTTP_HEADERS" , nil )()
57+ headersObj = headersObjAbs .(map [string ]interface {})
58+ }
59+
60+ // Convert headers from map[string]interface{} to map[string]string
61+ headers := make (map [string ]string )
62+ if headersObj != nil {
63+ for k , v := range headersObj {
64+ switch v := v .(type ) {
65+ case string :
66+ headers [k ] = v
67+ }
68+ }
69+ }
70+
4271 client , err := gapi .New (
4372 d .Get ("auth" ).(string ),
4473 d .Get ("url" ).(string ),
74+ headers ,
4575 )
4676 if err != nil {
4777 return nil , err
@@ -51,3 +81,20 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) {
5181
5282 return client , nil
5383}
84+
85+ // EnvDefaultJsonFunc is a helper function that parses the given environment
86+ // variable as a JSON object, or returns the default value otherwise.
87+ func EnvDefaultJsonFunc (k string , dv interface {}) schema.SchemaDefaultFunc {
88+ return func () (interface {}, error ) {
89+ if valStr := os .Getenv (k ); valStr != "" {
90+ var valObj map [string ]interface {}
91+ err := json .Unmarshal ([]byte (valStr ), & valObj )
92+ if err != nil {
93+ return nil , err
94+ }
95+ return valObj , nil
96+ }
97+
98+ return dv , nil
99+ }
100+ }
0 commit comments