-
Notifications
You must be signed in to change notification settings - Fork 10.3k
Expand file tree
/
Copy pathgenerate_config.go
More file actions
728 lines (626 loc) · 24.1 KB
/
generate_config.go
File metadata and controls
728 lines (626 loc) · 24.1 KB
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package genconfig
import (
"bytes"
"encoding/json"
"fmt"
"maps"
"slices"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/zclconf/go-cty/cty"
ctyjson "github.com/zclconf/go-cty/cty/json"
"github.com/hashicorp/terraform/internal/addrs"
"github.com/hashicorp/terraform/internal/configs/configschema"
"github.com/hashicorp/terraform/internal/tfdiags"
)
// ImportGroup represents one or more resource and import configuration blocks.
type ImportGroup struct {
Imports []ResourceImport
}
// ResourceImport pairs up the import and associated resource when generating
// configuration, so that query output can be more structured for easier
// consumption.
type ResourceImport struct {
ImportBody []byte
Resource Resource
}
type Resource struct {
Addr addrs.AbsResourceInstance
// HCL Body of the resource, which is the attributes and blocks
// that are part of the resource.
Body []byte
}
func (r Resource) String() string {
var buf strings.Builder
buf.WriteString(fmt.Sprintf("resource %q %q {\n", r.Addr.Resource.Resource.Type, r.Addr.Resource.Resource.Name))
buf.Write(r.Body)
buf.WriteString("}")
formatted := hclwrite.Format([]byte(buf.String()))
return string(formatted)
}
func (i ImportGroup) String() string {
var buf strings.Builder
for _, imp := range i.Imports {
buf.WriteString(imp.Resource.String())
buf.WriteString("\n\n")
buf.WriteString(string(imp.ImportBody))
buf.WriteString("\n\n")
}
// The output better be valid HCL which can be parsed and formatted.
formatted := hclwrite.Format([]byte(buf.String()))
return string(formatted)
}
func (i ImportGroup) ResourcesString() string {
var buf strings.Builder
for _, imp := range i.Imports {
buf.WriteString(imp.Resource.String())
buf.WriteString("\n")
}
// The output better be valid HCL which can be parsed and formatted.
formatted := hclwrite.Format([]byte(buf.String()))
return string(formatted)
}
func (i ImportGroup) ImportsString() string {
var buf strings.Builder
for _, imp := range i.Imports {
buf.WriteString(string(imp.ImportBody))
buf.WriteString("\n")
}
// The output better be valid HCL which can be parsed and formatted.
formatted := hclwrite.Format([]byte(buf.String()))
return string(formatted)
}
// GenerateResourceContents generates HCL configuration code for the provided
// resource and state value.
//
// If you want to generate actual valid Terraform code you should follow this
// call up with a call to WrapResourceContents, which will place a Terraform
// resource header around the attributes and blocks returned by this function.
func GenerateResourceContents(addr addrs.AbsResourceInstance,
schema *configschema.Block,
pc addrs.LocalProviderConfig,
configVal cty.Value,
forceProviderAddr bool,
) (Resource, tfdiags.Diagnostics) {
var buf strings.Builder
var diags tfdiags.Diagnostics
generateProviderAddr := pc.LocalName != addr.Resource.Resource.ImpliedProvider() || pc.Alias != ""
if generateProviderAddr || forceProviderAddr {
buf.WriteString(strings.Repeat(" ", 2))
buf.WriteString(fmt.Sprintf("provider = %s\n", pc.StringCompact()))
}
if configVal.RawEquals(cty.NilVal) {
diags = diags.Append(writeConfigAttributes(addr, &buf, schema.Attributes, 2))
diags = diags.Append(writeConfigBlocks(addr, &buf, schema.BlockTypes, 2))
} else {
diags = diags.Append(writeConfigAttributesFromExisting(addr, &buf, configVal, schema.Attributes, 2))
diags = diags.Append(writeConfigBlocksFromExisting(addr, &buf, configVal, schema.BlockTypes, 2))
}
// The output better be valid HCL which can be parsed and formatted.
formatted := hclwrite.Format([]byte(buf.String()))
return Resource{Addr: addr, Body: formatted}, diags
}
// ResourceListElement is a single Resource state and identity pair derived from
// a list resource response.
type ResourceListElement struct {
// Config is the cty value extracted from the resource state which is
// intended to be written into the HCL resource block.
Config cty.Value
Identity cty.Value
// ExpansionEnum is a unique enumeration of the list resource address relative to its expanded siblings.
ExpansionEnum int
}
func GenerateListResourceContents(addr addrs.AbsResourceInstance,
schema *configschema.Block,
idSchema *configschema.Object,
pc addrs.LocalProviderConfig,
resources []ResourceListElement,
) (ImportGroup, tfdiags.Diagnostics) {
var diags tfdiags.Diagnostics
ret := ImportGroup{}
for idx, res := range resources {
// Generate a unique resource name for each instance in the list.
resAddr := addrs.AbsResourceInstance{
Module: addr.Module,
Resource: addrs.ResourceInstance{
Resource: addrs.Resource{
Mode: addrs.ManagedResourceMode,
Type: addr.Resource.Resource.Type,
},
},
}
// If the list resource instance is keyed, the expansion counter is included in the address
// to ensure uniqueness across the entire configuration.
if addr.Resource.Key == addrs.NoKey {
resAddr.Resource.Resource.Name = fmt.Sprintf("%s_%d", addr.Resource.Resource.Name, idx)
} else {
resAddr.Resource.Resource.Name = fmt.Sprintf("%s_%d_%d", addr.Resource.Resource.Name, res.ExpansionEnum, idx)
}
content, gDiags := GenerateResourceContents(resAddr, schema, pc, res.Config, true)
if gDiags.HasErrors() {
diags = diags.Append(gDiags)
continue
}
resImport := ResourceImport{
Resource: Resource{
Addr: resAddr,
Body: content.Body,
},
}
importContent, gDiags := GenerateImportBlock(resAddr, idSchema, pc, res.Identity)
if gDiags.HasErrors() {
diags = diags.Append(gDiags)
continue
}
resImport.ImportBody = bytes.TrimSpace(hclwrite.Format(importContent.ImportBody))
ret.Imports = append(ret.Imports, resImport)
}
return ret, diags
}
func GenerateImportBlock(addr addrs.AbsResourceInstance, idSchema *configschema.Object, pc addrs.LocalProviderConfig, identity cty.Value) (ResourceImport, tfdiags.Diagnostics) {
var buf strings.Builder
var diags tfdiags.Diagnostics
buf.WriteString("\n")
buf.WriteString("import {\n")
buf.WriteString(fmt.Sprintf(" to = %s\n", addr.String()))
buf.WriteString(fmt.Sprintf(" provider = %s\n", pc.StringCompact()))
buf.WriteString(" identity = {\n")
diags = diags.Append(writeConfigAttributesFromExisting(addr, &buf, identity, idSchema.Attributes, 2))
buf.WriteString(strings.Repeat(" ", 2))
buf.WriteString("}\n}\n")
formatted := hclwrite.Format([]byte(buf.String()))
return ResourceImport{ImportBody: formatted}, diags
}
func writeConfigAttributes(addr addrs.AbsResourceInstance, buf *strings.Builder, attrs map[string]*configschema.Attribute, indent int) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
if len(attrs) == 0 {
return diags
}
// Get a list of sorted attribute names so the output will be consistent between runs.
for _, name := range slices.Sorted(maps.Keys(attrs)) {
attrS := attrs[name]
if attrS.NestedType != nil {
diags = diags.Append(writeConfigNestedTypeAttribute(addr, buf, name, attrS, indent))
continue
}
if attrS.Required {
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = ", name))
tok := hclwrite.TokensForValue(attrS.EmptyValue())
if _, err := tok.WriteTo(buf); err != nil {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagWarning,
Summary: "Skipped part of config generation",
Detail: fmt.Sprintf("Could not create attribute %s in %s when generating import configuration. The plan will likely report the missing attribute as being deleted.", name, addr),
Extra: err,
})
continue
}
writeAttrTypeConstraint(buf, attrS)
} else if attrS.Optional {
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = ", name))
tok := hclwrite.TokensForValue(attrS.EmptyValue())
if _, err := tok.WriteTo(buf); err != nil {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagWarning,
Summary: "Skipped part of config generation",
Detail: fmt.Sprintf("Could not create attribute %s in %s when generating import configuration. The plan will likely report the missing attribute as being deleted.", name, addr),
Extra: err,
})
continue
}
writeAttrTypeConstraint(buf, attrS)
}
}
return diags
}
func writeConfigAttributesFromExisting(addr addrs.AbsResourceInstance, buf *strings.Builder, stateVal cty.Value, attrs map[string]*configschema.Attribute, indent int) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
if len(attrs) == 0 {
return diags
}
// Sort attribute names so the output will be consistent between runs.
for _, name := range slices.Sorted(maps.Keys(attrs)) {
attrS := attrs[name]
var val cty.Value
if !stateVal.IsNull() && stateVal.Type().HasAttribute(name) {
val = stateVal.GetAttr(name)
} else {
val = attrS.EmptyValue()
}
if attrS.Computed && val.IsNull() {
// Computed attributes should never be written in the config. These
// will be filtered out of the given cty value if they are not also
// optional, and we want to skip writing `null` in the config.
continue
}
if attrS.Deprecated {
// We also want to skip showing deprecated attributes as null in the HCL.
continue
}
if attrS.NestedType != nil {
writeConfigNestedTypeAttributeFromExisting(addr, buf, name, attrS, stateVal, indent)
continue
}
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = ", name))
if attrS.Sensitive {
buf.WriteString("null # sensitive")
} else {
// If the value is a string storing a JSON value we want to represent it in a terraform native way
// and encapsulate it in `jsonencode` as it is the idiomatic representation
if !val.IsNull() && val.Type() == cty.String && json.Valid([]byte(val.AsString())) {
var ctyValue ctyjson.SimpleJSONValue
err := ctyValue.UnmarshalJSON([]byte(val.AsString()))
if err != nil {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagWarning,
Summary: "Failed to parse JSON",
Detail: fmt.Sprintf("Could not parse JSON value of attribute %s in %s when generating import configuration. The plan will likely report the missing attribute as being deleted. This is most likely a bug in Terraform, please report it.", name, addr),
Extra: err,
})
continue
}
// Lone deserializable primitive types are valid json, but should be treated as strings
if ctyValue.Type().IsPrimitiveType() {
if d := writeTokens(val, buf); d != nil {
diags = diags.Append(d)
continue
}
} else {
buf.WriteString("jsonencode(")
if d := writeTokens(ctyValue.Value, buf); d != nil {
diags = diags.Append(d)
continue
}
buf.WriteString(")")
}
} else {
if d := writeTokens(val, buf); d != nil {
diags = diags.Append(d)
continue
}
}
}
buf.WriteString("\n")
}
return diags
}
func writeTokens(val cty.Value, buf *strings.Builder) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
tok := hclwrite.TokensForValue(val)
if _, err := tok.WriteTo(buf); err != nil {
return diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagWarning,
Summary: "Skipped part of config generation",
Detail: "Could not create attribute in import configuration. The plan will likely report the missing attribute as being deleted.",
Extra: err,
})
}
return diags
}
func writeConfigBlocks(addr addrs.AbsResourceInstance, buf *strings.Builder, blocks map[string]*configschema.NestedBlock, indent int) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
if len(blocks) == 0 {
return diags
}
// Get a list of sorted block names so the output will be consistent between runs.
for _, name := range slices.Sorted(maps.Keys(blocks)) {
blockS := blocks[name]
diags = diags.Append(writeConfigNestedBlock(addr, buf, name, blockS, indent))
}
return diags
}
func writeConfigNestedBlock(addr addrs.AbsResourceInstance, buf *strings.Builder, name string, schema *configschema.NestedBlock, indent int) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
switch schema.Nesting {
case configschema.NestingSingle, configschema.NestingGroup:
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s {", name))
writeBlockTypeConstraint(buf, schema)
diags = diags.Append(writeConfigAttributes(addr, buf, schema.Attributes, indent+2))
diags = diags.Append(writeConfigBlocks(addr, buf, schema.BlockTypes, indent+2))
buf.WriteString("}\n")
return diags
case configschema.NestingList, configschema.NestingSet:
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s {", name))
writeBlockTypeConstraint(buf, schema)
diags = diags.Append(writeConfigAttributes(addr, buf, schema.Attributes, indent+2))
diags = diags.Append(writeConfigBlocks(addr, buf, schema.BlockTypes, indent+2))
buf.WriteString("}\n")
return diags
case configschema.NestingMap:
buf.WriteString(strings.Repeat(" ", indent))
// we use an arbitrary placeholder key (block label) "key"
buf.WriteString(fmt.Sprintf("%s \"key\" {", name))
writeBlockTypeConstraint(buf, schema)
diags = diags.Append(writeConfigAttributes(addr, buf, schema.Attributes, indent+2))
diags = diags.Append(writeConfigBlocks(addr, buf, schema.BlockTypes, indent+2))
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString("}\n")
return diags
default:
// This should not happen, the above should be exhaustive.
panic(fmt.Errorf("unsupported NestingMode %s", schema.Nesting.String()))
}
}
func writeConfigNestedTypeAttribute(addr addrs.AbsResourceInstance, buf *strings.Builder, name string, schema *configschema.Attribute, indent int) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = ", name))
switch schema.NestedType.Nesting {
case configschema.NestingSingle:
buf.WriteString("{")
writeAttrTypeConstraint(buf, schema)
diags = diags.Append(writeConfigAttributes(addr, buf, schema.NestedType.Attributes, indent+2))
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString("}\n")
return diags
case configschema.NestingList, configschema.NestingSet:
buf.WriteString("[{")
writeAttrTypeConstraint(buf, schema)
diags = diags.Append(writeConfigAttributes(addr, buf, schema.NestedType.Attributes, indent+2))
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString("}]\n")
return diags
case configschema.NestingMap:
buf.WriteString("{")
writeAttrTypeConstraint(buf, schema)
buf.WriteString(strings.Repeat(" ", indent+2))
// we use an arbitrary placeholder key "key"
buf.WriteString("key = {\n")
diags = diags.Append(writeConfigAttributes(addr, buf, schema.NestedType.Attributes, indent+4))
buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString("}\n")
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString("}\n")
return diags
default:
// This should not happen, the above should be exhaustive.
panic(fmt.Errorf("unsupported NestingMode %s", schema.NestedType.Nesting.String()))
}
}
func writeConfigBlocksFromExisting(addr addrs.AbsResourceInstance, buf *strings.Builder, stateVal cty.Value, blocks map[string]*configschema.NestedBlock, indent int) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
if len(blocks) == 0 {
return diags
}
// Sort block names so the output will be consistent between runs.
for _, name := range slices.Sorted(maps.Keys(blocks)) {
blockS := blocks[name]
// This shouldn't happen in real usage; state always has all values (set
// to null as needed), but it protects against panics in tests (and any
// really weird and unlikely cases).
if !stateVal.Type().HasAttribute(name) {
continue
}
blockVal := stateVal.GetAttr(name)
diags = diags.Append(writeConfigNestedBlockFromExisting(addr, buf, name, blockS, blockVal, indent))
}
return diags
}
func writeConfigNestedTypeAttributeFromExisting(addr addrs.AbsResourceInstance, buf *strings.Builder, name string, schema *configschema.Attribute, stateVal cty.Value, indent int) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
switch schema.NestedType.Nesting {
case configschema.NestingSingle:
if schema.Sensitive {
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = {} # sensitive\n", name))
return diags
}
// This shouldn't happen in real usage; state always has all values (set
// to null as needed), but it protects against panics in tests (and any
// really weird and unlikely cases).
if !stateVal.Type().HasAttribute(name) {
return diags
}
nestedVal := stateVal.GetAttr(name)
if nestedVal.IsNull() {
// There is a difference between a null object, and an object with
// no attributes.
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = null\n", name))
return diags
}
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = {\n", name))
diags = diags.Append(writeConfigAttributesFromExisting(addr, buf, nestedVal, schema.NestedType.Attributes, indent+2))
buf.WriteString("}\n")
return diags
case configschema.NestingList, configschema.NestingSet:
if schema.Sensitive {
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = [] # sensitive\n", name))
return diags
}
vals := stateVal.GetAttr(name)
if vals.IsNull() {
// There is a difference between an empty list and a null list
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = null\n", name))
return diags
}
listVals := vals.AsValueSlice()
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = [\n", name))
for i := range listVals {
buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString("{\n")
diags = diags.Append(writeConfigAttributesFromExisting(addr, buf, listVals[i], schema.NestedType.Attributes, indent+4))
buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString("},\n")
}
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString("]\n")
return diags
case configschema.NestingMap:
if schema.Sensitive {
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = {} # sensitive\n", name))
return diags
}
attr := stateVal.GetAttr(name)
if attr.IsNull() {
// There is a difference between an empty map and a null map.
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = null\n", name))
return diags
}
vals := attr.AsValueMap()
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s = {\n", name))
for _, key := range slices.Sorted(maps.Keys(vals)) {
buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString(fmt.Sprintf("%s = {", hclEscapeString(key)))
buf.WriteString("\n")
diags = diags.Append(writeConfigAttributesFromExisting(addr, buf, vals[key], schema.NestedType.Attributes, indent+4))
buf.WriteString(strings.Repeat(" ", indent+2))
buf.WriteString("}\n")
}
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString("}\n")
return diags
default:
// This should not happen, the above should be exhaustive.
panic(fmt.Errorf("unsupported NestingMode %s", schema.NestedType.Nesting.String()))
}
}
func writeConfigNestedBlockFromExisting(addr addrs.AbsResourceInstance, buf *strings.Builder, name string, schema *configschema.NestedBlock, stateVal cty.Value, indent int) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
if stateVal.IsNull() {
return diags
}
switch schema.Nesting {
case configschema.NestingSingle, configschema.NestingGroup:
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s {", name))
buf.WriteString("\n")
diags = diags.Append(writeConfigAttributesFromExisting(addr, buf, stateVal, schema.Attributes, indent+2))
diags = diags.Append(writeConfigBlocksFromExisting(addr, buf, stateVal, schema.BlockTypes, indent+2))
buf.WriteString("}\n")
return diags
case configschema.NestingList, configschema.NestingSet:
listVals := stateVal.AsValueSlice()
for i := range listVals {
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s {\n", name))
diags = diags.Append(writeConfigAttributesFromExisting(addr, buf, listVals[i], schema.Attributes, indent+2))
diags = diags.Append(writeConfigBlocksFromExisting(addr, buf, listVals[i], schema.BlockTypes, indent+2))
buf.WriteString("}\n")
}
return diags
case configschema.NestingMap:
vals := stateVal.AsValueMap()
for _, key := range slices.Sorted(maps.Keys(vals)) {
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString(fmt.Sprintf("%s %q {", name, key))
buf.WriteString("\n")
diags = diags.Append(writeConfigAttributesFromExisting(addr, buf, vals[key], schema.Attributes, indent+2))
diags = diags.Append(writeConfigBlocksFromExisting(addr, buf, vals[key], schema.BlockTypes, indent+2))
buf.WriteString(strings.Repeat(" ", indent))
buf.WriteString("}\n")
}
return diags
default:
// This should not happen, the above should be exhaustive.
panic(fmt.Errorf("unsupported NestingMode %s", schema.Nesting.String()))
}
}
func writeAttrTypeConstraint(buf *strings.Builder, schema *configschema.Attribute) {
if schema.Required {
buf.WriteString(" # REQUIRED ")
} else {
buf.WriteString(" # OPTIONAL ")
}
if schema.NestedType != nil {
buf.WriteString(fmt.Sprintf("%s\n", schema.NestedType.ImpliedType().FriendlyName()))
} else {
buf.WriteString(fmt.Sprintf("%s\n", schema.Type.FriendlyName()))
}
}
func writeBlockTypeConstraint(buf *strings.Builder, schema *configschema.NestedBlock) {
if schema.MinItems > 0 {
buf.WriteString(" # REQUIRED block\n")
} else {
buf.WriteString(" # OPTIONAL block\n")
}
}
// hclEscapeString formats the input string into a format that is safe for
// rendering within HCL.
//
// Note, this function doesn't actually do a very good job of this currently. We
// need to expose some internal functions from HCL in a future version and call
// them from here. For now, just use "%q" formatting.
//
// Note, the similar function in jsonformat/computed/renderers/map.go is doing
// something similar.
func hclEscapeString(str string) string {
// TODO: Replace this with more complete HCL logic instead of the simple
// go workaround.
if !hclsyntax.ValidIdentifier(str) {
return fmt.Sprintf("%q", str)
}
return str
}
// ExtractLegacyConfigFromState takes the state value of a resource, and filters the
// value down to what would be acceptable as a resource configuration value.
// This is used when the provider does not implement GenerateResourceConfig to
// create a suitable value.
func ExtractLegacyConfigFromState(schema *configschema.Block, state cty.Value) cty.Value {
config, _ := cty.Transform(state, func(path cty.Path, v cty.Value) (cty.Value, error) {
if v.IsNull() {
return v, nil
}
if len(path) == 0 {
return v, nil
}
ty := v.Type()
null := cty.NullVal(ty)
// find the attribute or block schema representing the value
attr := schema.AttributeByPath(path)
block := schema.BlockByPath(path)
switch {
case attr != nil:
// deprecated attributes
if attr.Deprecated {
return null, nil
}
// read-only attributes are not written in the configuration
if attr.Computed && !attr.Optional {
return null, nil
}
// The legacy SDK adds an Optional+Computed "id" attribute to the
// resource schema even if not defined in provider code.
// During validation, however, the presence of an extraneous "id"
// attribute in config will cause an error.
// Remove this attribute so we do not generate an "id" attribute
// where there is a risk that it is not in the real resource schema.
if path.Equals(cty.GetAttrPath("id")) && attr.Computed && attr.Optional {
return null, nil
}
// If we have "" for an optional value, assume it is actually null
// due to the legacy SDK.
if ty == cty.String {
if !v.IsNull() && attr.Optional && len(v.AsString()) == 0 {
return null, nil
}
}
return v, nil
case block != nil:
if block.Deprecated {
return null, nil
}
}
// We're only filtering out values which correspond to specific
// attributes or blocks from the schema, anything else is passed through
// as it will be a leaf value within a container.
return v, nil
})
return config
}