Skip to content

Commit 6b9b83b

Browse files
committed
helper/schema: Add helper function JsonEnvDefaultFunc
1 parent 486198a commit 6b9b83b

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

Diff for: helper/schema/schema.go

+18
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ package schema
1313

1414
import (
1515
"context"
16+
"encoding/json"
1617
"fmt"
1718
"log"
1819
"os"
@@ -296,6 +297,23 @@ func MultiEnvDefaultFunc(ks []string, dv interface{}) SchemaDefaultFunc {
296297
}
297298
}
298299

300+
// JsonEnvDefaultFunc is a helper function that parses the given environment
301+
// variable as a JSON object, or returns the default value otherwise.
302+
func JsonEnvDefaultFunc(k string, dv interface{}) SchemaDefaultFunc {
303+
return func() (interface{}, error) {
304+
if valStr := os.Getenv(k); valStr != "" {
305+
var valObj map[string]interface{}
306+
err := json.Unmarshal([]byte(valStr), &valObj)
307+
if err != nil {
308+
return nil, err
309+
}
310+
return valObj, nil
311+
}
312+
313+
return dv, nil
314+
}
315+
}
316+
299317
// SchemaSetFunc is a function that must return a unique ID for the given
300318
// element. This unique ID is used to store the element in a hash.
301319
type SchemaSetFunc func(interface{}) int

Diff for: helper/schema/schema_test.go

+39
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,45 @@ func TestMultiEnvDefaultFunc(t *testing.T) {
107107
}
108108
}
109109

110+
func TestJsonEnvDefaultFunc(t *testing.T) {
111+
key := "TF_TEST_JSON_ENV_DEFAULT_FUNC"
112+
defer os.Unsetenv(key)
113+
114+
def := map[string]interface{}{"foo": "default"}
115+
f := JsonEnvDefaultFunc(key, def)
116+
if err := os.Setenv(key, "{\"foo\":\"bar\"}"); err != nil {
117+
t.Fatalf("err: %s", err)
118+
}
119+
120+
actualAbs, err := f()
121+
if err != nil {
122+
t.Fatalf("err: %s", err)
123+
}
124+
actual, ok := actualAbs.(map[string]interface{})
125+
if !ok {
126+
t.Fatalf("bad: %#v", actualAbs)
127+
}
128+
if actual["foo"] != "bar" {
129+
t.Fatalf("bad: %#v", actual)
130+
}
131+
132+
if err := os.Unsetenv(key); err != nil {
133+
t.Fatalf("err: %s", err)
134+
}
135+
136+
actualAbs, err = f()
137+
if err != nil {
138+
t.Fatalf("err: %s", err)
139+
}
140+
actual, ok = actualAbs.(map[string]interface{})
141+
if !ok {
142+
t.Fatalf("bad: %#v", actualAbs)
143+
}
144+
if actual["foo"] != "default" {
145+
t.Fatalf("bad: %#v", actual)
146+
}
147+
}
148+
110149
func TestValueType_Zero(t *testing.T) {
111150
cases := []struct {
112151
Type ValueType

0 commit comments

Comments
 (0)