forked from hashicorp/terraform-provider-aws
/
resource_aws_dynamodb_table.go
932 lines (828 loc) · 26.2 KB
/
resource_aws_dynamodb_table.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
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
package aws
import (
"bytes"
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/hashicorp/terraform/helper/customdiff"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
)
func resourceAwsDynamoDbTable() *schema.Resource {
return &schema.Resource{
Create: resourceAwsDynamoDbTableCreate,
Read: resourceAwsDynamoDbTableRead,
Update: resourceAwsDynamoDbTableUpdate,
Delete: resourceAwsDynamoDbTableDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
},
CustomizeDiff: customdiff.Sequence(
func(diff *schema.ResourceDiff, v interface{}) error {
return validateDynamoDbStreamSpec(diff)
},
func(diff *schema.ResourceDiff, v interface{}) error {
return validateDynamoDbTableAttributes(diff)
},
func(diff *schema.ResourceDiff, v interface{}) error {
if diff.Id() != "" && diff.HasChange("server_side_encryption") {
o, n := diff.GetChange("server_side_encryption")
if isDynamoDbTableOptionDisabled(o) && isDynamoDbTableOptionDisabled(n) {
return diff.Clear("server_side_encryption")
}
}
return nil
},
func(diff *schema.ResourceDiff, v interface{}) error {
if diff.Id() != "" && diff.HasChange("point_in_time_recovery") {
o, n := diff.GetChange("point_in_time_recovery")
if isDynamoDbTableOptionDisabled(o) && isDynamoDbTableOptionDisabled(n) {
return diff.Clear("point_in_time_recovery")
}
}
return nil
},
),
SchemaVersion: 1,
MigrateState: resourceAwsDynamoDbTableMigrateState,
Schema: map[string]*schema.Schema{
"arn": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"hash_key": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"range_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"billing_mode": {
Type: schema.TypeString,
Optional: true,
Default: dynamodb.BillingModeProvisioned,
ValidateFunc: validation.StringInSlice([]string{
dynamodb.BillingModePayPerRequest,
dynamodb.BillingModeProvisioned,
}, false),
},
"write_capacity": {
Type: schema.TypeInt,
Optional: true,
},
"read_capacity": {
Type: schema.TypeInt,
Optional: true,
},
"attribute": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"type": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
dynamodb.ScalarAttributeTypeB,
dynamodb.ScalarAttributeTypeN,
dynamodb.ScalarAttributeTypeS,
}, false),
},
},
},
Set: func(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["name"].(string)))
return hashcode.String(buf.String())
},
},
"ttl": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"attribute_name": {
Type: schema.TypeString,
Required: true,
},
"enabled": {
Type: schema.TypeBool,
Required: true,
},
},
},
},
"local_secondary_index": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"range_key": {
Type: schema.TypeString,
Required: true,
},
"projection_type": {
Type: schema.TypeString,
Required: true,
},
"non_key_attributes": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
Set: func(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
buf.WriteString(fmt.Sprintf("%s-", m["name"].(string)))
return hashcode.String(buf.String())
},
},
"global_secondary_index": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
},
"write_capacity": {
Type: schema.TypeInt,
Optional: true,
},
"read_capacity": {
Type: schema.TypeInt,
Optional: true,
},
"hash_key": {
Type: schema.TypeString,
Required: true,
},
"range_key": {
Type: schema.TypeString,
Optional: true,
},
"projection_type": {
Type: schema.TypeString,
Required: true,
},
"non_key_attributes": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"stream_enabled": {
Type: schema.TypeBool,
Optional: true,
},
"stream_view_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
StateFunc: func(v interface{}) string {
value := v.(string)
return strings.ToUpper(value)
},
ValidateFunc: validation.StringInSlice([]string{
"",
dynamodb.StreamViewTypeNewImage,
dynamodb.StreamViewTypeOldImage,
dynamodb.StreamViewTypeNewAndOldImages,
dynamodb.StreamViewTypeKeysOnly,
}, false),
},
"stream_arn": {
Type: schema.TypeString,
Computed: true,
},
"stream_label": {
Type: schema.TypeString,
Computed: true,
},
"server_side_encryption": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Required: true,
ForceNew: true,
},
},
},
},
"tags": tagsSchema(),
"point_in_time_recovery": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"enabled": {
Type: schema.TypeBool,
Required: true,
},
},
},
},
},
}
}
func resourceAwsDynamoDbTableCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dynamodbconn
keySchemaMap := map[string]interface{}{
"hash_key": d.Get("hash_key").(string),
}
if v, ok := d.GetOk("range_key"); ok {
keySchemaMap["range_key"] = v.(string)
}
log.Printf("[DEBUG] Creating DynamoDB table with key schema: %#v", keySchemaMap)
req := &dynamodb.CreateTableInput{
TableName: aws.String(d.Get("name").(string)),
BillingMode: aws.String(d.Get("billing_mode").(string)),
KeySchema: expandDynamoDbKeySchema(keySchemaMap),
}
billingMode := d.Get("billing_mode").(string)
capacityMap := map[string]interface{}{
"write_capacity": d.Get("write_capacity"),
"read_capacity": d.Get("read_capacity"),
}
if err := validateDynamoDbProvisionedThroughput(capacityMap, billingMode); err != nil {
return err
}
req.ProvisionedThroughput = expandDynamoDbProvisionedThroughput(capacityMap, billingMode)
if v, ok := d.GetOk("attribute"); ok {
aSet := v.(*schema.Set)
req.AttributeDefinitions = expandDynamoDbAttributes(aSet.List())
}
if v, ok := d.GetOk("local_secondary_index"); ok {
lsiSet := v.(*schema.Set)
req.LocalSecondaryIndexes = expandDynamoDbLocalSecondaryIndexes(lsiSet.List(), keySchemaMap)
}
if v, ok := d.GetOk("global_secondary_index"); ok {
globalSecondaryIndexes := []*dynamodb.GlobalSecondaryIndex{}
gsiSet := v.(*schema.Set)
for _, gsiObject := range gsiSet.List() {
gsi := gsiObject.(map[string]interface{})
if err := validateDynamoDbProvisionedThroughput(gsi, billingMode); err != nil {
return fmt.Errorf("Failed to create GSI: %v", err)
}
gsiObject := expandDynamoDbGlobalSecondaryIndex(gsi, billingMode)
globalSecondaryIndexes = append(globalSecondaryIndexes, gsiObject)
}
req.GlobalSecondaryIndexes = globalSecondaryIndexes
}
if v, ok := d.GetOk("stream_enabled"); ok {
req.StreamSpecification = &dynamodb.StreamSpecification{
StreamEnabled: aws.Bool(v.(bool)),
StreamViewType: aws.String(d.Get("stream_view_type").(string)),
}
}
if v, ok := d.GetOk("server_side_encryption"); ok {
options := v.([]interface{})
if options[0] == nil {
return fmt.Errorf("At least one field is expected inside server_side_encryption")
}
s := options[0].(map[string]interface{})
req.SSESpecification = expandDynamoDbEncryptAtRestOptions(s)
}
var output *dynamodb.CreateTableOutput
err := resource.Retry(2*time.Minute, func() *resource.RetryError {
var err error
output, err = conn.CreateTable(req)
if err != nil {
if isAWSErr(err, "ThrottlingException", "") {
return resource.RetryableError(err)
}
if isAWSErr(err, dynamodb.ErrCodeLimitExceededException, "can be created, updated, or deleted simultaneously") {
return resource.RetryableError(err)
}
if isAWSErr(err, dynamodb.ErrCodeLimitExceededException, "indexed tables that can be created simultaneously") {
return resource.RetryableError(err)
}
// AWS GovCloud (US) and others may reply with the following until their API is updated:
// ValidationException: One or more parameter values were invalid: Unsupported input parameter BillingMode
if isAWSErr(err, "ValidationException", "Unsupported input parameter BillingMode") {
req.BillingMode = nil
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return fmt.Errorf("error creating DynamoDB Table: %s", err)
}
d.SetId(*output.TableDescription.TableName)
d.Set("arn", output.TableDescription.TableArn)
if err := waitForDynamoDbTableToBeActive(d.Id(), d.Timeout(schema.TimeoutCreate), conn); err != nil {
return err
}
return resourceAwsDynamoDbTableUpdate(d, meta)
}
func resourceAwsDynamoDbTableUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dynamodbconn
billingMode := d.Get("billing_mode").(string)
if d.HasChange("billing_mode") && !d.IsNewResource() {
req := &dynamodb.UpdateTableInput{
TableName: aws.String(d.Id()),
BillingMode: aws.String(billingMode),
}
capacityMap := map[string]interface{}{
"write_capacity": d.Get("write_capacity"),
"read_capacity": d.Get("read_capacity"),
}
if err := validateDynamoDbProvisionedThroughput(capacityMap, billingMode); err != nil {
return err
}
_, err := conn.UpdateTable(req)
if err != nil {
return fmt.Errorf("Error updating DynamoDB Table (%s) billing mode: %s", d.Id(), err)
}
if err := waitForDynamoDbTableToBeActive(d.Id(), d.Timeout(schema.TimeoutUpdate), conn); err != nil {
return fmt.Errorf("Error waiting for DynamoDB Table update: %s", err)
}
}
// Cannot create or delete index while updating table IOPS
// so we update IOPS separately
if !d.HasChange("billing_mode") && d.Get("billing_mode").(string) == dynamodb.BillingModeProvisioned && (d.HasChange("read_capacity") || d.HasChange("write_capacity")) && !d.IsNewResource() {
_, err := conn.UpdateTable(&dynamodb.UpdateTableInput{
TableName: aws.String(d.Id()),
ProvisionedThroughput: expandDynamoDbProvisionedThroughput(map[string]interface{}{
"read_capacity": d.Get("read_capacity"),
"write_capacity": d.Get("write_capacity"),
}, billingMode),
})
if err != nil {
return err
}
if err := waitForDynamoDbTableToBeActive(d.Id(), d.Timeout(schema.TimeoutUpdate), conn); err != nil {
return fmt.Errorf("Error waiting for DynamoDB Table update: %s", err)
}
}
if (d.HasChange("stream_enabled") || d.HasChange("stream_view_type")) && !d.IsNewResource() {
toEnable := d.Get("stream_enabled").(bool)
streamSpec := dynamodb.StreamSpecification{
StreamEnabled: aws.Bool(toEnable),
}
if toEnable {
streamSpec.StreamViewType = aws.String(d.Get("stream_view_type").(string))
}
input := &dynamodb.UpdateTableInput{
TableName: aws.String(d.Id()),
StreamSpecification: &streamSpec,
}
_, err := conn.UpdateTable(input)
if err != nil {
return err
}
if err := waitForDynamoDbTableToBeActive(d.Id(), d.Timeout(schema.TimeoutUpdate), conn); err != nil {
return fmt.Errorf("Error waiting for DynamoDB Table update: %s", err)
}
}
// Indexes and attributes are tightly coupled (DynamoDB requires attribute definitions
// for all indexed attributes) so it's necessary to update these together.
if (d.HasChange("global_secondary_index") || d.HasChange("attribute")) && !d.IsNewResource() {
attributes := d.Get("attribute").(*schema.Set).List()
o, n := d.GetChange("global_secondary_index")
ops, err := diffDynamoDbGSI(o.(*schema.Set).List(), n.(*schema.Set).List(), billingMode)
if err != nil {
return fmt.Errorf("Computing difference for global_secondary_index failed: %s", err)
}
log.Printf("[DEBUG] Updating global secondary indexes:\n%s", ops)
input := &dynamodb.UpdateTableInput{
TableName: aws.String(d.Id()),
AttributeDefinitions: expandDynamoDbAttributes(attributes),
}
// Only 1 online index can be created or deleted simultaneously per table
for _, op := range ops {
input.GlobalSecondaryIndexUpdates = []*dynamodb.GlobalSecondaryIndexUpdate{op}
log.Printf("[DEBUG] Updating DynamoDB Table: %s", input)
_, err := conn.UpdateTable(input)
if err != nil {
return err
}
if op.Create != nil {
idxName := *op.Create.IndexName
if err := waitForDynamoDbGSIToBeActive(d.Id(), idxName, conn); err != nil {
return fmt.Errorf("Error waiting for DynamoDB GSI %q to be created: %s", idxName, err)
}
}
if op.Update != nil {
idxName := *op.Update.IndexName
if err := waitForDynamoDbGSIToBeActive(d.Id(), idxName, conn); err != nil {
return fmt.Errorf("Error waiting for DynamoDB GSI %q to be updated: %s", idxName, err)
}
}
if op.Delete != nil {
idxName := *op.Delete.IndexName
if err := waitForDynamoDbGSIToBeDeleted(d.Id(), idxName, conn); err != nil {
return fmt.Errorf("Error waiting for DynamoDB GSI %q to be deleted: %s", idxName, err)
}
}
}
// We may only be changing the attribute type
if len(ops) == 0 {
_, err := conn.UpdateTable(input)
if err != nil {
return err
}
}
if err := waitForDynamoDbTableToBeActive(d.Id(), d.Timeout(schema.TimeoutUpdate), conn); err != nil {
return fmt.Errorf("Error waiting for DynamoDB Table op: %s", err)
}
}
if d.HasChange("ttl") {
if err := updateDynamoDbTimeToLive(d, conn); err != nil {
log.Printf("[DEBUG] Error updating table TimeToLive: %s", err)
return err
}
}
if d.HasChange("tags") {
if err := setTagsDynamoDb(conn, d); err != nil {
return err
}
}
if d.HasChange("point_in_time_recovery") {
_, enabled := d.GetChange("point_in_time_recovery.0.enabled")
if !d.IsNewResource() || enabled.(bool) {
if err := updateDynamoDbPITR(d, conn); err != nil {
return err
}
}
}
return resourceAwsDynamoDbTableRead(d, meta)
}
func resourceAwsDynamoDbTableRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dynamodbconn
result, err := conn.DescribeTable(&dynamodb.DescribeTableInput{
TableName: aws.String(d.Id()),
})
if err != nil {
if isAWSErr(err, dynamodb.ErrCodeResourceNotFoundException, "") {
log.Printf("[WARN] Dynamodb Table (%s) not found, error code (404)", d.Id())
d.SetId("")
return nil
}
return err
}
err = flattenAwsDynamoDbTableResource(d, result.Table)
if err != nil {
return err
}
ttlOut, err := conn.DescribeTimeToLive(&dynamodb.DescribeTimeToLiveInput{
TableName: aws.String(d.Id()),
})
if err != nil {
return err
}
if ttlOut.TimeToLiveDescription != nil {
err := d.Set("ttl", flattenDynamoDbTtl(ttlOut.TimeToLiveDescription))
if err != nil {
return err
}
}
tags, err := readDynamoDbTableTags(d.Get("arn").(string), conn)
if err != nil {
return err
}
d.Set("tags", tags)
pitrOut, err := conn.DescribeContinuousBackups(&dynamodb.DescribeContinuousBackupsInput{
TableName: aws.String(d.Id()),
})
if err != nil && !isAWSErr(err, "UnknownOperationException", "") {
return err
}
d.Set("point_in_time_recovery", flattenDynamoDbPitr(pitrOut))
return nil
}
func resourceAwsDynamoDbTableDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).dynamodbconn
log.Printf("[DEBUG] DynamoDB delete table: %s", d.Id())
err := deleteAwsDynamoDbTable(d.Id(), conn)
if err != nil {
if isAWSErr(err, dynamodb.ErrCodeResourceNotFoundException, "Requested resource not found: Table: ") {
return nil
}
return err
}
stateConf := &resource.StateChangeConf{
Pending: []string{
dynamodb.TableStatusActive,
dynamodb.TableStatusDeleting,
},
Target: []string{},
Timeout: d.Timeout(schema.TimeoutDelete),
Refresh: func() (interface{}, string, error) {
out, err := conn.DescribeTable(&dynamodb.DescribeTableInput{
TableName: aws.String(d.Id()),
})
if err != nil {
if isAWSErr(err, dynamodb.ErrCodeResourceNotFoundException, "") {
return nil, "", nil
}
return 42, "", err
}
table := out.Table
return table, *table.TableStatus, nil
},
}
_, err = stateConf.WaitForState()
return err
}
func deleteAwsDynamoDbTable(tableName string, conn *dynamodb.DynamoDB) error {
input := &dynamodb.DeleteTableInput{
TableName: aws.String(tableName),
}
return resource.Retry(5*time.Minute, func() *resource.RetryError {
_, err := conn.DeleteTable(input)
if err != nil {
// Subscriber limit exceeded: Only 10 tables can be created, updated, or deleted simultaneously
if isAWSErr(err, dynamodb.ErrCodeLimitExceededException, "simultaneously") {
return resource.RetryableError(err)
}
// This handles multiple scenarios in the DynamoDB API:
// 1. Updating a table immediately before deletion may return:
// ResourceInUseException: Attempt to change a resource which is still in use: Table is being updated:
// 2. Removing a table from a DynamoDB global table may return:
// ResourceInUseException: Attempt to change a resource which is still in use: Table is being deleted:
if isAWSErr(err, dynamodb.ErrCodeResourceInUseException, "") {
return resource.RetryableError(err)
}
if isAWSErr(err, dynamodb.ErrCodeResourceNotFoundException, "Requested resource not found: Table: ") {
return resource.NonRetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
}
func updateDynamoDbTimeToLive(d *schema.ResourceData, conn *dynamodb.DynamoDB) error {
toBeEnabled := false
attributeName := ""
o, n := d.GetChange("ttl")
newTtl, ok := n.(*schema.Set)
blockExists := ok && newTtl.Len() > 0
if blockExists {
ttlList := newTtl.List()
ttlMap := ttlList[0].(map[string]interface{})
attributeName = ttlMap["attribute_name"].(string)
toBeEnabled = ttlMap["enabled"].(bool)
} else if !d.IsNewResource() {
oldTtlList := o.(*schema.Set).List()
ttlMap := oldTtlList[0].(map[string]interface{})
attributeName = ttlMap["attribute_name"].(string)
toBeEnabled = false
}
if attributeName != "" {
_, err := conn.UpdateTimeToLive(&dynamodb.UpdateTimeToLiveInput{
TableName: aws.String(d.Id()),
TimeToLiveSpecification: &dynamodb.TimeToLiveSpecification{
AttributeName: aws.String(attributeName),
Enabled: aws.Bool(toBeEnabled),
},
})
if err != nil {
if isAWSErr(err, "ValidationException", "TimeToLive is already disabled") {
return nil
}
return err
}
err = waitForDynamoDbTtlUpdateToBeCompleted(d.Id(), toBeEnabled, conn)
if err != nil {
return fmt.Errorf("Error waiting for DynamoDB TimeToLive to be updated: %s", err)
}
}
return nil
}
func updateDynamoDbPITR(d *schema.ResourceData, conn *dynamodb.DynamoDB) error {
toEnable := d.Get("point_in_time_recovery.0.enabled").(bool)
input := &dynamodb.UpdateContinuousBackupsInput{
TableName: aws.String(d.Id()),
PointInTimeRecoverySpecification: &dynamodb.PointInTimeRecoverySpecification{
PointInTimeRecoveryEnabled: aws.Bool(toEnable),
},
}
log.Printf("[DEBUG] Updating DynamoDB point in time recovery status to %v", toEnable)
err := resource.Retry(20*time.Minute, func() *resource.RetryError {
_, err := conn.UpdateContinuousBackups(input)
if err != nil {
// Backups are still being enabled for this newly created table
if isAWSErr(err, dynamodb.ErrCodeContinuousBackupsUnavailableException, "Backups are being enabled") {
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return err
}
if err := waitForDynamoDbBackupUpdateToBeCompleted(d.Id(), toEnable, conn); err != nil {
return fmt.Errorf("Error waiting for DynamoDB PITR update: %s", err)
}
return nil
}
func readDynamoDbTableTags(arn string, conn *dynamodb.DynamoDB) (map[string]string, error) {
output, err := conn.ListTagsOfResource(&dynamodb.ListTagsOfResourceInput{
ResourceArn: aws.String(arn),
})
// Do not fail if interfacing with dynamodb-local
if err != nil && !isAWSErr(err, "UnknownOperationException", "Tagging is not currently supported in DynamoDB Local.") {
return nil, fmt.Errorf("Error reading tags from dynamodb resource: %s", err)
}
result := tagsToMapDynamoDb(output.Tags)
// TODO Read NextToken if available
return result, nil
}
// Waiters
func waitForDynamoDbGSIToBeActive(tableName string, gsiName string, conn *dynamodb.DynamoDB) error {
stateConf := &resource.StateChangeConf{
Pending: []string{
dynamodb.IndexStatusCreating,
dynamodb.IndexStatusUpdating,
},
Target: []string{dynamodb.IndexStatusActive},
Timeout: 10 * time.Minute,
Refresh: func() (interface{}, string, error) {
result, err := conn.DescribeTable(&dynamodb.DescribeTableInput{
TableName: aws.String(tableName),
})
if err != nil {
return 42, "", err
}
table := result.Table
// Find index
var targetGSI *dynamodb.GlobalSecondaryIndexDescription
for _, gsi := range table.GlobalSecondaryIndexes {
if *gsi.IndexName == gsiName {
targetGSI = gsi
}
}
if targetGSI != nil {
return table, *targetGSI.IndexStatus, nil
}
return nil, "", nil
},
}
_, err := stateConf.WaitForState()
return err
}
func waitForDynamoDbGSIToBeDeleted(tableName string, gsiName string, conn *dynamodb.DynamoDB) error {
stateConf := &resource.StateChangeConf{
Pending: []string{
dynamodb.IndexStatusActive,
dynamodb.IndexStatusDeleting,
},
Target: []string{},
Timeout: 10 * time.Minute,
Refresh: func() (interface{}, string, error) {
result, err := conn.DescribeTable(&dynamodb.DescribeTableInput{
TableName: aws.String(tableName),
})
if err != nil {
return 42, "", err
}
table := result.Table
// Find index
var targetGSI *dynamodb.GlobalSecondaryIndexDescription
for _, gsi := range table.GlobalSecondaryIndexes {
if *gsi.IndexName == gsiName {
targetGSI = gsi
}
}
if targetGSI == nil {
return nil, "", nil
}
return targetGSI, *targetGSI.IndexStatus, nil
},
}
_, err := stateConf.WaitForState()
return err
}
func waitForDynamoDbTableToBeActive(tableName string, timeout time.Duration, conn *dynamodb.DynamoDB) error {
stateConf := &resource.StateChangeConf{
Pending: []string{dynamodb.TableStatusCreating, dynamodb.TableStatusUpdating},
Target: []string{dynamodb.TableStatusActive},
Timeout: timeout,
Refresh: func() (interface{}, string, error) {
result, err := conn.DescribeTable(&dynamodb.DescribeTableInput{
TableName: aws.String(tableName),
})
if err != nil {
return 42, "", err
}
return result, *result.Table.TableStatus, nil
},
}
_, err := stateConf.WaitForState()
return err
}
func waitForDynamoDbBackupUpdateToBeCompleted(tableName string, toEnable bool, conn *dynamodb.DynamoDB) error {
var pending []string
target := []string{dynamodb.TimeToLiveStatusDisabled}
if toEnable {
pending = []string{
"ENABLING",
}
target = []string{dynamodb.PointInTimeRecoveryStatusEnabled}
}
stateConf := &resource.StateChangeConf{
Pending: pending,
Target: target,
Timeout: 10 * time.Second,
Refresh: func() (interface{}, string, error) {
result, err := conn.DescribeContinuousBackups(&dynamodb.DescribeContinuousBackupsInput{
TableName: aws.String(tableName),
})
if err != nil {
return 42, "", err
}
if result.ContinuousBackupsDescription == nil || result.ContinuousBackupsDescription.PointInTimeRecoveryDescription == nil {
return 42, "", errors.New("Error reading backup status from dynamodb resource: empty description")
}
pitr := result.ContinuousBackupsDescription.PointInTimeRecoveryDescription
return result, *pitr.PointInTimeRecoveryStatus, nil
},
}
_, err := stateConf.WaitForState()
return err
}
func waitForDynamoDbTtlUpdateToBeCompleted(tableName string, toEnable bool, conn *dynamodb.DynamoDB) error {
pending := []string{
dynamodb.TimeToLiveStatusEnabled,
dynamodb.TimeToLiveStatusDisabling,
}
target := []string{dynamodb.TimeToLiveStatusDisabled}
if toEnable {
pending = []string{
dynamodb.TimeToLiveStatusDisabled,
dynamodb.TimeToLiveStatusEnabling,
}
target = []string{dynamodb.TimeToLiveStatusEnabled}
}
stateConf := &resource.StateChangeConf{
Pending: pending,
Target: target,
Timeout: 10 * time.Second,
Refresh: func() (interface{}, string, error) {
result, err := conn.DescribeTimeToLive(&dynamodb.DescribeTimeToLiveInput{
TableName: aws.String(tableName),
})
if err != nil {
return 42, "", err
}
ttlDesc := result.TimeToLiveDescription
return result, *ttlDesc.TimeToLiveStatus, nil
},
}
_, err := stateConf.WaitForState()
return err
}
func isDynamoDbTableOptionDisabled(v interface{}) bool {
options := v.([]interface{})
if len(options) == 0 {
return true
}
e := options[0].(map[string]interface{})["enabled"]
return !e.(bool)
}