/
backend_context_test.go
469 lines (436 loc) · 13.6 KB
/
backend_context_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
package remote
import (
"context"
"github.com/hashicorp/terraform/internal/terraform"
"github.com/hashicorp/terraform/internal/tfdiags"
"reflect"
"testing"
tfe "github.com/hashicorp/go-tfe"
"github.com/hashicorp/terraform/internal/backend"
"github.com/hashicorp/terraform/internal/command/arguments"
"github.com/hashicorp/terraform/internal/command/clistate"
"github.com/hashicorp/terraform/internal/command/views"
"github.com/hashicorp/terraform/internal/configs"
"github.com/hashicorp/terraform/internal/initwd"
"github.com/hashicorp/terraform/internal/states/statemgr"
"github.com/hashicorp/terraform/internal/terminal"
"github.com/zclconf/go-cty/cty"
)
func TestRemoteStoredVariableValue(t *testing.T) {
tests := map[string]struct {
Def *tfe.Variable
Want cty.Value
WantError string
}{
"string literal": {
&tfe.Variable{
Key: "test",
Value: "foo",
HCL: false,
Sensitive: false,
},
cty.StringVal("foo"),
``,
},
"string HCL": {
&tfe.Variable{
Key: "test",
Value: `"foo"`,
HCL: true,
Sensitive: false,
},
cty.StringVal("foo"),
``,
},
"list HCL": {
&tfe.Variable{
Key: "test",
Value: `[]`,
HCL: true,
Sensitive: false,
},
cty.EmptyTupleVal,
``,
},
"null HCL": {
&tfe.Variable{
Key: "test",
Value: `null`,
HCL: true,
Sensitive: false,
},
cty.NullVal(cty.DynamicPseudoType),
``,
},
"literal sensitive": {
&tfe.Variable{
Key: "test",
HCL: false,
Sensitive: true,
},
cty.UnknownVal(cty.String),
``,
},
"HCL sensitive": {
&tfe.Variable{
Key: "test",
HCL: true,
Sensitive: true,
},
cty.DynamicVal,
``,
},
"HCL computation": {
// This (stored expressions containing computation) is not a case
// we intentionally supported, but it became possible for remote
// operations in Terraform 0.12 (due to Terraform Cloud/Enterprise
// just writing the HCL verbatim into generated `.tfvars` files).
// We support it here for consistency, and we continue to support
// it in both places for backward-compatibility. In practice,
// there's little reason to do computation in a stored variable
// value because references are not supported.
&tfe.Variable{
Key: "test",
Value: `[for v in ["a"] : v]`,
HCL: true,
Sensitive: false,
},
cty.TupleVal([]cty.Value{cty.StringVal("a")}),
``,
},
"HCL syntax error": {
&tfe.Variable{
Key: "test",
Value: `[`,
HCL: true,
Sensitive: false,
},
cty.DynamicVal,
`Invalid expression for var.test: The value of variable "test" is marked in the remote workspace as being specified in HCL syntax, but the given value is not valid HCL. Stored variable values must be valid literal expressions and may not contain references to other variables or calls to functions.`,
},
"HCL with references": {
&tfe.Variable{
Key: "test",
Value: `foo.bar`,
HCL: true,
Sensitive: false,
},
cty.DynamicVal,
`Invalid expression for var.test: The value of variable "test" is marked in the remote workspace as being specified in HCL syntax, but the given value is not valid HCL. Stored variable values must be valid literal expressions and may not contain references to other variables or calls to functions.`,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
v := &remoteStoredVariableValue{
definition: test.Def,
}
// This ParseVariableValue implementation ignores the parsing mode,
// so we'll just always parse literal here. (The parsing mode is
// selected by the remote server, not by our local configuration.)
gotIV, diags := v.ParseVariableValue(configs.VariableParseLiteral)
if test.WantError != "" {
if !diags.HasErrors() {
t.Fatalf("missing expected error\ngot: <no error>\nwant: %s", test.WantError)
}
errStr := diags.Err().Error()
if errStr != test.WantError {
t.Fatalf("wrong error\ngot: %s\nwant: %s", errStr, test.WantError)
}
} else {
if diags.HasErrors() {
t.Fatalf("unexpected error\ngot: %s\nwant: <no error>", diags.Err().Error())
}
got := gotIV.Value
if !test.Want.RawEquals(got) {
t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want)
}
}
})
}
}
func TestRemoteContextWithVars(t *testing.T) {
catTerraform := tfe.CategoryTerraform
catEnv := tfe.CategoryEnv
tests := map[string]struct {
Opts *tfe.VariableCreateOptions
WantError string
}{
"Terraform variable": {
&tfe.VariableCreateOptions{
Category: &catTerraform,
},
`Value for undeclared variable: A variable named "key" was assigned a value, but the root module does not declare a variable of that name. To use this value, add a "variable" block to the configuration.`,
},
"environment variable": {
&tfe.VariableCreateOptions{
Category: &catEnv,
},
``,
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
configDir := "./testdata/empty"
b, bCleanup := testBackendDefault(t)
defer bCleanup()
_, configLoader, configCleanup := initwd.MustLoadConfigForTests(t, configDir)
defer configCleanup()
workspaceID, err := b.getRemoteWorkspaceID(context.Background(), backend.DefaultStateName)
if err != nil {
t.Fatal(err)
}
streams, _ := terminal.StreamsForTesting(t)
view := views.NewStateLocker(arguments.ViewHuman, views.NewView(streams))
op := &backend.Operation{
ConfigDir: configDir,
ConfigLoader: configLoader,
StateLocker: clistate.NewLocker(0, view),
Workspace: backend.DefaultStateName,
}
v := test.Opts
if v.Key == nil {
key := "key"
v.Key = &key
}
b.client.Variables.Create(context.TODO(), workspaceID, *v)
_, _, diags := b.LocalRun(op)
if test.WantError != "" {
if !diags.HasErrors() {
t.Fatalf("missing expected error\ngot: <no error>\nwant: %s", test.WantError)
}
errStr := diags.Err().Error()
if errStr != test.WantError {
t.Fatalf("wrong error\ngot: %s\nwant: %s", errStr, test.WantError)
}
// When Context() returns an error, it should unlock the state,
// so re-locking it is expected to succeed.
stateMgr, _ := b.StateMgr(backend.DefaultStateName)
if _, err := stateMgr.Lock(statemgr.NewLockInfo()); err != nil {
t.Fatalf("unexpected error locking state: %s", err.Error())
}
} else {
if diags.HasErrors() {
t.Fatalf("unexpected error\ngot: %s\nwant: <no error>", diags.Err().Error())
}
// When Context() succeeds, this should fail w/ "workspace already locked"
stateMgr, _ := b.StateMgr(backend.DefaultStateName)
if _, err := stateMgr.Lock(statemgr.NewLockInfo()); err == nil {
t.Fatal("unexpected success locking state after Context")
}
}
})
}
}
func TestRemoteVariablesDoNotOverride(t *testing.T) {
catTerraform := tfe.CategoryTerraform
varName1 := "key1"
varName2 := "key2"
varName3 := "key3"
varValue1 := "value1"
varValue2 := "value2"
varValue3 := "value3"
tests := map[string]struct {
localVariables map[string]backend.UnparsedVariableValue
remoteVariables []*tfe.VariableCreateOptions
expectedVariables terraform.InputValues
}{
"no local variables": {
map[string]backend.UnparsedVariableValue{},
[]*tfe.VariableCreateOptions{
{
Key: &varName1,
Value: &varValue1,
Category: &catTerraform,
},
{
Key: &varName2,
Value: &varValue2,
Category: &catTerraform,
},
{
Key: &varName3,
Value: &varValue3,
Category: &catTerraform,
},
},
terraform.InputValues{
varName1: &terraform.InputValue{
Value: cty.StringVal(varValue1),
SourceType: terraform.ValueFromInput,
SourceRange: tfdiags.SourceRange{
Filename: "",
Start: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
End: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
},
},
varName2: &terraform.InputValue{
Value: cty.StringVal(varValue2),
SourceType: terraform.ValueFromInput,
SourceRange: tfdiags.SourceRange{
Filename: "",
Start: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
End: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
},
},
varName3: &terraform.InputValue{
Value: cty.StringVal(varValue3),
SourceType: terraform.ValueFromInput,
SourceRange: tfdiags.SourceRange{
Filename: "",
Start: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
End: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
},
},
},
},
"single conflicting local variable": {
map[string]backend.UnparsedVariableValue{
varName3: testUnparsedVariableValue(varValue3),
},
[]*tfe.VariableCreateOptions{
{
Key: &varName1,
Value: &varValue1,
Category: &catTerraform,
}, {
Key: &varName2,
Value: &varValue2,
Category: &catTerraform,
}, {
Key: &varName3,
Value: &varValue3,
Category: &catTerraform,
},
},
terraform.InputValues{
varName1: &terraform.InputValue{
Value: cty.StringVal(varValue1),
SourceType: terraform.ValueFromInput,
SourceRange: tfdiags.SourceRange{
Filename: "",
Start: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
End: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
},
},
varName2: &terraform.InputValue{
Value: cty.StringVal(varValue2),
SourceType: terraform.ValueFromInput,
SourceRange: tfdiags.SourceRange{
Filename: "",
Start: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
End: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
},
},
varName3: &terraform.InputValue{
Value: cty.StringVal(varValue3),
SourceType: terraform.ValueFromNamedFile,
SourceRange: tfdiags.SourceRange{
Filename: "fake.tfvars",
Start: tfdiags.SourcePos{Line: 1, Column: 1, Byte: 0},
End: tfdiags.SourcePos{Line: 1, Column: 1, Byte: 0},
},
},
},
},
"no-conflicting local variable": {
map[string]backend.UnparsedVariableValue{
varName3: testUnparsedVariableValue(varValue3),
},
[]*tfe.VariableCreateOptions{
{
Key: &varName1,
Value: &varValue1,
Category: &catTerraform,
}, {
Key: &varName2,
Value: &varValue2,
Category: &catTerraform,
},
},
terraform.InputValues{
varName1: &terraform.InputValue{
Value: cty.StringVal(varValue1),
SourceType: terraform.ValueFromInput,
SourceRange: tfdiags.SourceRange{
Filename: "",
Start: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
End: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
},
},
varName2: &terraform.InputValue{
Value: cty.StringVal(varValue2),
SourceType: terraform.ValueFromInput,
SourceRange: tfdiags.SourceRange{
Filename: "",
Start: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
End: tfdiags.SourcePos{Line: 0, Column: 0, Byte: 0},
},
},
varName3: &terraform.InputValue{
Value: cty.StringVal(varValue3),
SourceType: terraform.ValueFromNamedFile,
SourceRange: tfdiags.SourceRange{
Filename: "fake.tfvars",
Start: tfdiags.SourcePos{Line: 1, Column: 1, Byte: 0},
End: tfdiags.SourcePos{Line: 1, Column: 1, Byte: 0},
},
},
},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
configDir := "./testdata/variables"
b, bCleanup := testBackendDefault(t)
defer bCleanup()
_, configLoader, configCleanup := initwd.MustLoadConfigForTests(t, configDir)
defer configCleanup()
workspaceID, err := b.getRemoteWorkspaceID(context.Background(), backend.DefaultStateName)
if err != nil {
t.Fatal(err)
}
streams, _ := terminal.StreamsForTesting(t)
view := views.NewStateLocker(arguments.ViewHuman, views.NewView(streams))
op := &backend.Operation{
ConfigDir: configDir,
ConfigLoader: configLoader,
StateLocker: clistate.NewLocker(0, view),
Workspace: backend.DefaultStateName,
Variables: test.localVariables,
}
for _, v := range test.remoteVariables {
b.client.Variables.Create(context.TODO(), workspaceID, *v)
}
lr, _, diags := b.LocalRun(op)
if diags.HasErrors() {
t.Fatalf("unexpected error\ngot: %s\nwant: <no error>", diags.Err().Error())
}
// When Context() succeeds, this should fail w/ "workspace already locked"
stateMgr, _ := b.StateMgr(backend.DefaultStateName)
if _, err := stateMgr.Lock(statemgr.NewLockInfo()); err == nil {
t.Fatal("unexpected success locking state after Context")
}
actual := lr.PlanOpts.SetVariables
expected := test.expectedVariables
for expectedKey := range expected {
actualValue := actual[expectedKey]
expectedValue := expected[expectedKey]
if !reflect.DeepEqual(*actualValue, *expectedValue) {
t.Fatalf("unexpected variable '%s'\ngot: %v\nwant: %v", expectedKey, actualValue, expectedValue)
}
}
})
}
}
type testUnparsedVariableValue string
func (v testUnparsedVariableValue) ParseVariableValue(mode configs.VariableParsingMode) (*terraform.InputValue, tfdiags.Diagnostics) {
return &terraform.InputValue{
Value: cty.StringVal(string(v)),
SourceType: terraform.ValueFromNamedFile,
SourceRange: tfdiags.SourceRange{
Filename: "fake.tfvars",
Start: tfdiags.SourcePos{Line: 1, Column: 1, Byte: 0},
End: tfdiags.SourcePos{Line: 1, Column: 1, Byte: 0},
},
}, nil
}