diff --git a/terraform/context.go b/terraform/context.go index 66e954245..e6b9b4b23 100644 --- a/terraform/context.go +++ b/terraform/context.go @@ -3,7 +3,9 @@ package terraform import ( "fmt" "log" + "os" "sort" + "strings" "sync" "github.com/hashicorp/go-multierror" @@ -98,6 +100,26 @@ func NewContext(opts *ContextOpts) *Context { par = 10 } + // Setup the variables. We first take the variables given to us. + // We then merge in the variables set in the environment. + variables := make(map[string]string) + for k, v := range opts.Variables { + variables[k] = v + } + for _, v := range os.Environ() { + if !strings.HasPrefix(v, VarEnvPrefix) { + continue + } + + // Strip off the prefix and get the value after the first "=" + idx := strings.Index(v, "=") + k := v[len(VarEnvPrefix):idx] + v = v[idx+1:] + + // Override the command-line set variable + variables[k] = v + } + return &Context{ destroy: opts.Destroy, diff: opts.Diff, @@ -108,7 +130,7 @@ func NewContext(opts *ContextOpts) *Context { state: state, targets: opts.Targets, uiInput: opts.UIInput, - variables: opts.Variables, + variables: variables, parallelSem: NewSemaphore(par), providerInputConfig: make(map[string]map[string]interface{}), diff --git a/terraform/context_test.go b/terraform/context_test.go index 31308e8d5..ed8184650 100644 --- a/terraform/context_test.go +++ b/terraform/context_test.go @@ -6417,6 +6417,10 @@ func TestContext2Apply_vars(t *testing.T) { } func TestContext2Apply_varsEnv(t *testing.T) { + // Set the env var + old := tempEnv(t, "TF_VAR_ami", "baz") + defer os.Setenv("TF_VAR_ami", old) + m := testModule(t, "apply-vars-env") p := testProvider("aws") p.ApplyFn = testApplyFn @@ -6428,10 +6432,6 @@ func TestContext2Apply_varsEnv(t *testing.T) { }, }) - // Set the env var - old := tempEnv(t, "TF_VAR_ami", "baz") - defer os.Setenv("TF_VAR_ami", old) - w, e := ctx.Validate() if len(w) > 0 { t.Fatalf("bad: %#v", w) diff --git a/terraform/interpolate.go b/terraform/interpolate.go index 96c2c7521..15b51fcb2 100644 --- a/terraform/interpolate.go +++ b/terraform/interpolate.go @@ -49,11 +49,6 @@ func (i *Interpolater) Values( } for _, v := range mod.Config().Variables { for k, val := range v.DefaultsMap() { - envKey := VarEnvPrefix + strings.TrimPrefix(k, "var.") - if v := os.Getenv(envKey); v != "" { - val = v - } - result[k] = ast.Variable{ Value: val, Type: ast.TypeString,