Skip to content

Commit

Permalink
helper/schema: Add helper function JsonEnvDefaultFunc
Browse files Browse the repository at this point in the history
  • Loading branch information
gw0 committed Sep 30, 2020
1 parent 9355d02 commit 1fa7ac2
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
18 changes: 18 additions & 0 deletions helper/schema/schema.go
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
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

0 comments on commit 1fa7ac2

Please sign in to comment.