Skip to content

Commit fe74d69

Browse files
committed
terraform: validation should succeed if env var set [hashicorpGH-1930]
1 parent 442376c commit fe74d69

3 files changed

Lines changed: 27 additions & 10 deletions

File tree

‎terraform/context.go‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ package terraform
33
import (
44
"fmt"
55
"log"
6+
"os"
67
"sort"
8+
"strings"
79
"sync"
810

911
"github.com/hashicorp/go-multierror"
@@ -98,6 +100,26 @@ func NewContext(opts *ContextOpts) *Context {
98100
par = 10
99101
}
100102

103+
// Setup the variables. We first take the variables given to us.
104+
// We then merge in the variables set in the environment.
105+
variables := make(map[string]string)
106+
for k, v := range opts.Variables {
107+
variables[k] = v
108+
}
109+
for _, v := range os.Environ() {
110+
if !strings.HasPrefix(v, VarEnvPrefix) {
111+
continue
112+
}
113+
114+
// Strip off the prefix and get the value after the first "="
115+
idx := strings.Index(v, "=")
116+
k := v[len(VarEnvPrefix):idx]
117+
v = v[idx+1:]
118+
119+
// Override the command-line set variable
120+
variables[k] = v
121+
}
122+
101123
return &Context{
102124
destroy: opts.Destroy,
103125
diff: opts.Diff,
@@ -108,7 +130,7 @@ func NewContext(opts *ContextOpts) *Context {
108130
state: state,
109131
targets: opts.Targets,
110132
uiInput: opts.UIInput,
111-
variables: opts.Variables,
133+
variables: variables,
112134

113135
parallelSem: NewSemaphore(par),
114136
providerInputConfig: make(map[string]map[string]interface{}),

‎terraform/context_test.go‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6417,6 +6417,10 @@ func TestContext2Apply_vars(t *testing.T) {
64176417
}
64186418

64196419
func TestContext2Apply_varsEnv(t *testing.T) {
6420+
// Set the env var
6421+
old := tempEnv(t, "TF_VAR_ami", "baz")
6422+
defer os.Setenv("TF_VAR_ami", old)
6423+
64206424
m := testModule(t, "apply-vars-env")
64216425
p := testProvider("aws")
64226426
p.ApplyFn = testApplyFn
@@ -6428,10 +6432,6 @@ func TestContext2Apply_varsEnv(t *testing.T) {
64286432
},
64296433
})
64306434

6431-
// Set the env var
6432-
old := tempEnv(t, "TF_VAR_ami", "baz")
6433-
defer os.Setenv("TF_VAR_ami", old)
6434-
64356435
w, e := ctx.Validate()
64366436
if len(w) > 0 {
64376437
t.Fatalf("bad: %#v", w)

‎terraform/interpolate.go‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,6 @@ func (i *Interpolater) Values(
4949
}
5050
for _, v := range mod.Config().Variables {
5151
for k, val := range v.DefaultsMap() {
52-
envKey := VarEnvPrefix + strings.TrimPrefix(k, "var.")
53-
if v := os.Getenv(envKey); v != "" {
54-
val = v
55-
}
56-
5752
result[k] = ast.Variable{
5853
Value: val,
5954
Type: ast.TypeString,

0 commit comments

Comments
 (0)