Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions helper/schema/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ package schema

import (
"context"
"encoding/json"
"fmt"
"log"
"os"
Expand Down Expand Up @@ -296,6 +297,23 @@ func MultiEnvDefaultFunc(ks []string, dv interface{}) SchemaDefaultFunc {
}
}

// JsonEnvDefaultFunc is a helper function that parses the given environment
// variable as a JSON object, or returns the default value otherwise.
func JsonEnvDefaultFunc(k string, dv interface{}) SchemaDefaultFunc {
return func() (interface{}, error) {
if valStr := os.Getenv(k); valStr != "" {
var valObj map[string]interface{}
err := json.Unmarshal([]byte(valStr), &valObj)
if err != nil {
return nil, err
}
return valObj, nil
}

return dv, nil
}
}

// SchemaSetFunc is a function that must return a unique ID for the given
// element. This unique ID is used to store the element in a hash.
type SchemaSetFunc func(interface{}) int
Expand Down
39 changes: 39 additions & 0 deletions helper/schema/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,45 @@ func TestMultiEnvDefaultFunc(t *testing.T) {
}
}

func TestJsonEnvDefaultFunc(t *testing.T) {
key := "TF_TEST_JSON_ENV_DEFAULT_FUNC"
defer os.Unsetenv(key)

def := map[string]interface{}{"foo": "default"}
f := JsonEnvDefaultFunc(key, def)
if err := os.Setenv(key, "{\"foo\":\"bar\"}"); err != nil {
t.Fatalf("err: %s", err)
}

actualAbs, err := f()
if err != nil {
t.Fatalf("err: %s", err)
}
actual, ok := actualAbs.(map[string]interface{})
if !ok {
t.Fatalf("bad: %#v", actualAbs)
}
if actual["foo"] != "bar" {
t.Fatalf("bad: %#v", actual)
}

if err := os.Unsetenv(key); err != nil {
t.Fatalf("err: %s", err)
}

actualAbs, err = f()
if err != nil {
t.Fatalf("err: %s", err)
}
actual, ok = actualAbs.(map[string]interface{})
if !ok {
t.Fatalf("bad: %#v", actualAbs)
}
if actual["foo"] != "default" {
t.Fatalf("bad: %#v", actual)
}
}

func TestValueType_Zero(t *testing.T) {
cases := []struct {
Type ValueType
Expand Down