-
Notifications
You must be signed in to change notification settings - Fork 9.2k
/
replication_group.go
1466 lines (1252 loc) · 50.2 KB
/
replication_group.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
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package elasticache
import (
"context"
"errors"
"fmt"
"log"
"slices"
"strings"
"time"
"github.com/YakDriver/regexache"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/elasticache"
awstypes "github.com/aws/aws-sdk-go-v2/service/elasticache/types"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/go-cty/cty/gocty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/hashicorp/terraform-provider-aws/internal/conns"
"github.com/hashicorp/terraform-provider-aws/internal/enum"
"github.com/hashicorp/terraform-provider-aws/internal/errs"
"github.com/hashicorp/terraform-provider-aws/internal/errs/sdkdiag"
"github.com/hashicorp/terraform-provider-aws/internal/flex"
"github.com/hashicorp/terraform-provider-aws/internal/sdkv2/types/nullable"
"github.com/hashicorp/terraform-provider-aws/internal/semver"
tfslices "github.com/hashicorp/terraform-provider-aws/internal/slices"
tftags "github.com/hashicorp/terraform-provider-aws/internal/tags"
"github.com/hashicorp/terraform-provider-aws/internal/tfresource"
"github.com/hashicorp/terraform-provider-aws/internal/verify"
"github.com/hashicorp/terraform-provider-aws/names"
)
const (
failoverMinNumCacheClusters = 2
)
// @SDKResource("aws_elasticache_replication_group", name="Replication Group")
// @Tags(identifierAttribute="arn")
func resourceReplicationGroup() *schema.Resource {
//lintignore:R011
return &schema.Resource{
CreateWithoutTimeout: resourceReplicationGroupCreate,
ReadWithoutTimeout: resourceReplicationGroupRead,
UpdateWithoutTimeout: resourceReplicationGroupUpdate,
DeleteWithoutTimeout: resourceReplicationGroupDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
names.AttrApplyImmediately: {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
names.AttrARN: {
Type: schema.TypeString,
Computed: true,
},
"at_rest_encryption_enabled": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Computed: true,
},
"auth_token": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
ValidateFunc: validReplicationGroupAuthToken,
ConflictsWith: []string{"user_group_ids"},
},
"auth_token_update_strategy": {
Type: schema.TypeString,
Optional: true,
ValidateDiagFunc: enum.Validate[awstypes.AuthTokenUpdateStrategyType](),
Default: awstypes.AuthTokenUpdateStrategyTypeRotate,
},
names.AttrAutoMinorVersionUpgrade: {
Type: nullable.TypeNullableBool,
Optional: true,
Computed: true,
ValidateFunc: nullable.ValidateTypeStringNullableBool,
},
"automatic_failover_enabled": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"cluster_enabled": {
Type: schema.TypeBool,
Computed: true,
},
"cluster_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateDiagFunc: enum.Validate[awstypes.ClusterMode](),
},
"configuration_endpoint_address": {
Type: schema.TypeString,
Computed: true,
},
"data_tiering_enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
},
names.AttrDescription: {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},
names.AttrEngine: {
Type: schema.TypeString,
Optional: true,
Default: engineRedis,
ValidateFunc: validation.StringInSlice([]string{engineRedis, engineValkey}, true),
},
names.AttrEngineVersion: {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.Any(
validRedisVersionString,
validValkeyVersionString,
),
},
"engine_version_actual": {
Type: schema.TypeString,
Computed: true,
},
names.AttrFinalSnapshotIdentifier: {
Type: schema.TypeString,
Optional: true,
},
"global_replication_group_id": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ConflictsWith: []string{
"num_node_groups",
names.AttrParameterGroupName,
names.AttrEngine,
names.AttrEngineVersion,
"node_type",
"security_group_names",
"transit_encryption_enabled",
"transit_encryption_mode",
"at_rest_encryption_enabled",
"snapshot_arns",
"snapshot_name",
},
},
"ip_discovery": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateDiagFunc: enum.Validate[awstypes.IpDiscovery](),
},
names.AttrKMSKeyID: {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"log_delivery_configuration": {
Type: schema.TypeSet,
Optional: true,
MaxItems: 2,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"destination_type": {
Type: schema.TypeString,
Required: true,
ValidateDiagFunc: enum.Validate[awstypes.DestinationType](),
},
names.AttrDestination: {
Type: schema.TypeString,
Required: true,
},
"log_format": {
Type: schema.TypeString,
Required: true,
ValidateDiagFunc: enum.Validate[awstypes.LogFormat](),
},
"log_type": {
Type: schema.TypeString,
Required: true,
ValidateDiagFunc: enum.Validate[awstypes.LogType](),
},
},
},
},
"maintenance_window": {
Type: schema.TypeString,
Optional: true,
Computed: true,
StateFunc: func(val interface{}) string {
// ElastiCache always changes the maintenance to lowercase
return strings.ToLower(val.(string))
},
ValidateFunc: verify.ValidOnceAWeekWindowFormat,
},
"member_clusters": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"multi_az_enabled": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"network_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateDiagFunc: enum.Validate[awstypes.NetworkType](),
},
"node_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"notification_topic_arn": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: verify.ValidARN,
},
"num_cache_clusters": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
ConflictsWith: []string{"num_node_groups", "replicas_per_node_group"},
},
"num_node_groups": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ConflictsWith: []string{"num_cache_clusters", "global_replication_group_id"},
},
names.AttrParameterGroupName: {
Type: schema.TypeString,
Optional: true,
Computed: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
return strings.HasPrefix(old, "global-datastore-")
},
},
names.AttrPort: {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
// Suppress default Redis ports when not defined
if !d.IsNewResource() && new == "0" && old == defaultRedisPort {
return true
}
return false
},
},
"preferred_cache_cluster_azs": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"primary_endpoint_address": {
Type: schema.TypeString,
Computed: true,
},
"reader_endpoint_address": {
Type: schema.TypeString,
Computed: true,
},
"replicas_per_node_group": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
ConflictsWith: []string{"num_cache_clusters"},
ValidateFunc: validation.IntBetween(0, 5),
},
"replication_group_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateReplicationGroupID,
StateFunc: func(val interface{}) string {
return strings.ToLower(val.(string))
},
},
"security_group_names": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
ForceNew: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
names.AttrSecurityGroupIDs: {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"snapshot_arns": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
// Note: Unlike aws_elasticache_cluster, this does not have a limit of 1 item.
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.All(
verify.ValidARN,
validation.StringDoesNotContainAny(","),
),
},
},
"snapshot_retention_limit": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntAtMost(35),
},
"snapshot_window": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: verify.ValidOnceADayWindowFormat,
},
"snapshot_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"subnet_group_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
names.AttrTags: tftags.TagsSchema(),
names.AttrTagsAll: tftags.TagsSchemaComputed(),
"transit_encryption_enabled": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"transit_encryption_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateDiagFunc: enum.Validate[awstypes.TransitEncryptionMode](),
},
"user_group_ids": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
ConflictsWith: []string{"auth_token"},
},
},
SchemaVersion: 2,
// SchemaVersion: 1 did not include any state changes via MigrateState.
// Perform a no-operation state upgrade for Terraform 0.12 compatibility.
// Future state migrations should be performed with StateUpgraders.
MigrateState: func(v int, inst *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {
return inst, nil
},
StateUpgraders: []schema.StateUpgrader{
// v5.27.0 introduced the auth_token_update_strategy argument with a default
// value required to preserve backward compatibility. In order to prevent
// differences and attempted modifications on upgrade, the default value
// must be written to state via a state upgrader.
{
Type: resourceReplicationGroupConfigV1().CoreConfigSchema().ImpliedType(),
Upgrade: replicationGroupStateUpgradeV1,
Version: 1,
},
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
Update: schema.DefaultTimeout(40 * time.Minute),
Delete: schema.DefaultTimeout(45 * time.Minute),
},
CustomizeDiff: customdiff.All(
replicationGroupValidateMultiAZAutomaticFailover,
customizeDiffEngineVersionForceNewOnDowngrade,
customdiff.ForceNewIf(names.AttrEngine, func(_ context.Context, diff *schema.ResourceDiff, meta interface{}) bool {
if !diff.HasChange(names.AttrEngine) {
return false
}
if old, new := diff.GetChange(names.AttrEngine); old.(string) == engineRedis && new.(string) == engineValkey {
return false
}
return true
}),
customdiff.ComputedIf("member_clusters", func(ctx context.Context, diff *schema.ResourceDiff, meta interface{}) bool {
return diff.HasChange("num_cache_clusters") ||
diff.HasChange("num_node_groups") ||
diff.HasChange("replicas_per_node_group")
}),
customdiff.ForceNewIf("transit_encryption_enabled", func(_ context.Context, d *schema.ResourceDiff, meta interface{}) bool {
// For Redis engine versions < 7.0.5, transit_encryption_enabled can only
// be configured during creation of the cluster.
return semver.LessThan(d.Get("engine_version_actual").(string), "7.0.5")
}),
replicationGroupValidateAutomaticFailoverNumCacheClusters,
verify.SetTagsDiff,
),
}
}
func resourceReplicationGroupCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).ElastiCacheClient(ctx)
partition := meta.(*conns.AWSClient).Partition(ctx)
replicationGroupID := d.Get("replication_group_id").(string)
input := &elasticache.CreateReplicationGroupInput{
ReplicationGroupId: aws.String(replicationGroupID),
Tags: getTagsIn(ctx),
}
if _, ok := d.GetOk("at_rest_encryption_enabled"); ok {
input.AtRestEncryptionEnabled = aws.Bool(d.Get("at_rest_encryption_enabled").(bool))
}
if v, ok := d.GetOk("auth_token"); ok {
input.AuthToken = aws.String(v.(string))
}
if v, ok := d.GetOk(names.AttrAutoMinorVersionUpgrade); ok {
if v, null, _ := nullable.Bool(v.(string)).ValueBool(); !null {
input.AutoMinorVersionUpgrade = aws.Bool(v)
}
}
if v, ok := d.GetOk("cluster_mode"); ok {
input.ClusterMode = awstypes.ClusterMode(v.(string))
}
if v, ok := d.GetOk("data_tiering_enabled"); ok {
input.DataTieringEnabled = aws.Bool(v.(bool))
}
if v, ok := d.GetOk(names.AttrDescription); ok {
input.ReplicationGroupDescription = aws.String(v.(string))
}
if v, ok := d.GetOk(names.AttrEngineVersion); ok {
input.EngineVersion = aws.String(v.(string))
}
if v, ok := d.GetOk("global_replication_group_id"); ok {
input.GlobalReplicationGroupId = aws.String(v.(string))
} else {
// This cannot be handled at plan-time
nodeType := d.Get("node_type").(string)
if nodeType == "" {
return sdkdiag.AppendErrorf(diags, `"node_type" is required unless "global_replication_group_id" is set.`)
}
input.AutomaticFailoverEnabled = aws.Bool(d.Get("automatic_failover_enabled").(bool))
input.CacheNodeType = aws.String(nodeType)
input.Engine = aws.String(d.Get(names.AttrEngine).(string))
input.TransitEncryptionEnabled = aws.Bool(d.Get("transit_encryption_enabled").(bool))
}
if v, ok := d.GetOk("ip_discovery"); ok {
input.IpDiscovery = awstypes.IpDiscovery(v.(string))
}
if v, ok := d.GetOk(names.AttrKMSKeyID); ok {
input.KmsKeyId = aws.String(v.(string))
}
if v, ok := d.GetOk("log_delivery_configuration"); ok && v.(*schema.Set).Len() > 0 {
for _, tfMapRaw := range v.(*schema.Set).List() {
tfMap, ok := tfMapRaw.(map[string]interface{})
if !ok {
continue
}
apiObject := expandLogDeliveryConfigurationRequests(tfMap)
input.LogDeliveryConfigurations = append(input.LogDeliveryConfigurations, apiObject)
}
}
if v, ok := d.GetOk("maintenance_window"); ok {
input.PreferredMaintenanceWindow = aws.String(v.(string))
}
if v, ok := d.GetOk("multi_az_enabled"); ok {
input.MultiAZEnabled = aws.Bool(v.(bool))
}
if v, ok := d.GetOk("network_type"); ok {
input.NetworkType = awstypes.NetworkType(v.(string))
}
if v, ok := d.GetOk("notification_topic_arn"); ok {
input.NotificationTopicArn = aws.String(v.(string))
}
if v, ok := d.GetOk("num_cache_clusters"); ok {
input.NumCacheClusters = aws.Int32(int32(v.(int)))
}
if v, ok := d.GetOk("num_node_groups"); ok && v != 0 {
input.NumNodeGroups = aws.Int32(int32(v.(int)))
}
if v, ok := d.GetOk(names.AttrParameterGroupName); ok {
input.CacheParameterGroupName = aws.String(v.(string))
}
if v, ok := d.GetOk(names.AttrPort); ok {
input.Port = aws.Int32(int32(v.(int)))
}
if v, ok := d.GetOk("preferred_cache_cluster_azs"); ok && len(v.([]interface{})) > 0 {
input.PreferredCacheClusterAZs = flex.ExpandStringValueList(v.([]interface{}))
}
rawConfig := d.GetRawConfig()
rawReplicasPerNodeGroup := rawConfig.GetAttr("replicas_per_node_group")
if rawReplicasPerNodeGroup.IsKnown() && !rawReplicasPerNodeGroup.IsNull() {
var v int32
err := gocty.FromCtyValue(rawReplicasPerNodeGroup, &v)
if err != nil {
path := cty.GetAttrPath("replicas_per_node_group")
diags = append(diags, errs.NewAttributeErrorDiagnostic(
path,
"Invalid Value",
"An unexpected error occurred while reading configuration values. "+
"This is always an error in the provider. "+
"Please report the following to the provider developer:\n\n"+
fmt.Sprintf(`Reading "%s": %s`, errs.PathString(path), err),
))
}
input.ReplicasPerNodeGroup = aws.Int32(v)
}
if v, ok := d.GetOk("subnet_group_name"); ok {
input.CacheSubnetGroupName = aws.String(v.(string))
}
if v, ok := d.GetOk(names.AttrSecurityGroupIDs); ok && v.(*schema.Set).Len() > 0 {
input.SecurityGroupIds = flex.ExpandStringValueSet(v.(*schema.Set))
}
if v, ok := d.GetOk("security_group_names"); ok && v.(*schema.Set).Len() > 0 {
input.CacheSecurityGroupNames = flex.ExpandStringValueSet(v.(*schema.Set))
}
if v, ok := d.GetOk("snapshot_arns"); ok && v.(*schema.Set).Len() > 0 {
input.SnapshotArns = flex.ExpandStringValueSet(v.(*schema.Set))
}
if v, ok := d.GetOk("snapshot_name"); ok {
input.SnapshotName = aws.String(v.(string))
}
if v, ok := d.GetOk("snapshot_retention_limit"); ok {
input.SnapshotRetentionLimit = aws.Int32(int32(v.(int)))
}
if v, ok := d.GetOk("snapshot_window"); ok {
input.SnapshotWindow = aws.String(v.(string))
}
if v, ok := d.GetOk("transit_encryption_mode"); ok {
input.TransitEncryptionMode = awstypes.TransitEncryptionMode(v.(string))
}
if v, ok := d.GetOk("user_group_ids"); ok && v.(*schema.Set).Len() > 0 {
input.UserGroupIds = flex.ExpandStringValueSet(v.(*schema.Set))
}
output, err := conn.CreateReplicationGroup(ctx, input)
// Some partitions (e.g. ISO) may not support tag-on-create.
if input.Tags != nil && errs.IsUnsupportedOperationInPartitionError(partition, err) {
input.Tags = nil
output, err = conn.CreateReplicationGroup(ctx, input)
}
if err != nil {
return sdkdiag.AppendErrorf(diags, "creating ElastiCache Replication Group (%s): %s", replicationGroupID, err)
}
d.SetId(aws.ToString(output.ReplicationGroup.ReplicationGroupId))
const (
delay = 30 * time.Second
)
if _, err := waitReplicationGroupAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutCreate), delay); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for ElastiCache Replication Group (%s) create: %s", d.Id(), err)
}
if v, ok := d.GetOk("global_replication_group_id"); ok {
// When adding a replication group to a global replication group, the replication group can be in the "available"
// state, but the global replication group can still be in the "modifying" state. Wait for the replication group
// to be fully added to the global replication group.
// API calls to the global replication group can be made in any region.
if _, err := waitGlobalReplicationGroupAvailable(ctx, conn, v.(string), globalReplicationGroupDefaultCreatedTimeout); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for ElastiCache Global Replication Group (%s) available: %s", v, err)
}
}
// For partitions not supporting tag-on-create, attempt tag after create.
if tags := getTagsIn(ctx); input.Tags == nil && len(tags) > 0 {
err := createTags(ctx, conn, aws.ToString(output.ReplicationGroup.ARN), tags)
// If default tags only, continue. Otherwise, error.
if v, ok := d.GetOk(names.AttrTags); (!ok || len(v.(map[string]interface{})) == 0) && errs.IsUnsupportedOperationInPartitionError(partition, err) {
return append(diags, resourceReplicationGroupRead(ctx, d, meta)...)
}
if err != nil {
return sdkdiag.AppendErrorf(diags, "setting ElastiCache Replication Group (%s) tags: %s", d.Id(), err)
}
}
return append(diags, resourceReplicationGroupRead(ctx, d, meta)...)
}
func resourceReplicationGroupRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).ElastiCacheClient(ctx)
rgp, err := findReplicationGroupByID(ctx, conn, d.Id())
if !d.IsNewResource() && tfresource.NotFound(err) {
log.Printf("[WARN] ElastiCache Replication Group (%s) not found, removing from state", d.Id())
d.SetId("")
return diags
}
if err != nil {
return sdkdiag.AppendErrorf(diags, "reading ElastiCache Replication Group (%s): %s", d.Id(), err)
}
if aws.ToString(rgp.Status) == replicationGroupStatusDeleting {
log.Printf("[WARN] ElastiCache Replication Group (%s) is currently in the `deleting` status, removing from state", d.Id())
d.SetId("")
return diags
}
if rgp.GlobalReplicationGroupInfo != nil && rgp.GlobalReplicationGroupInfo.GlobalReplicationGroupId != nil {
d.Set("global_replication_group_id", rgp.GlobalReplicationGroupInfo.GlobalReplicationGroupId)
}
d.Set(names.AttrEngine, rgp.Engine)
switch rgp.AutomaticFailover {
case awstypes.AutomaticFailoverStatusDisabled, awstypes.AutomaticFailoverStatusDisabling:
d.Set("automatic_failover_enabled", false)
case awstypes.AutomaticFailoverStatusEnabled, awstypes.AutomaticFailoverStatusEnabling:
d.Set("automatic_failover_enabled", true)
default:
log.Printf("Unknown AutomaticFailover state %q", string(rgp.AutomaticFailover))
}
switch rgp.MultiAZ {
case awstypes.MultiAZStatusEnabled:
d.Set("multi_az_enabled", true)
case awstypes.MultiAZStatusDisabled:
d.Set("multi_az_enabled", false)
default:
log.Printf("Unknown MultiAZ state %q", string(rgp.MultiAZ))
}
d.Set(names.AttrKMSKeyID, rgp.KmsKeyId)
d.Set(names.AttrDescription, rgp.Description)
d.Set("num_cache_clusters", len(rgp.MemberClusters))
if err := d.Set("member_clusters", flex.FlattenStringValueSet(rgp.MemberClusters)); err != nil {
return sdkdiag.AppendErrorf(diags, "setting member_clusters: %s", err)
}
d.Set("num_node_groups", len(rgp.NodeGroups))
if len(rgp.NodeGroups) > 0 {
d.Set("replicas_per_node_group", len(rgp.NodeGroups[0].NodeGroupMembers)-1)
}
d.Set("cluster_enabled", rgp.ClusterEnabled)
d.Set("cluster_mode", rgp.ClusterMode)
d.Set("replication_group_id", rgp.ReplicationGroupId)
d.Set(names.AttrARN, rgp.ARN)
d.Set("data_tiering_enabled", rgp.DataTiering == awstypes.DataTieringStatusEnabled)
d.Set("ip_discovery", rgp.IpDiscovery)
d.Set("network_type", rgp.NetworkType)
d.Set("log_delivery_configuration", flattenLogDeliveryConfigurations(rgp.LogDeliveryConfigurations))
d.Set("snapshot_window", rgp.SnapshotWindow)
d.Set("snapshot_retention_limit", rgp.SnapshotRetentionLimit)
if rgp.ConfigurationEndpoint != nil {
d.Set(names.AttrPort, rgp.ConfigurationEndpoint.Port)
d.Set("configuration_endpoint_address", rgp.ConfigurationEndpoint.Address)
} else {
log.Printf("[DEBUG] ElastiCache Replication Group (%s) Configuration Endpoint is nil", d.Id())
if rgp.NodeGroups[0].PrimaryEndpoint != nil {
log.Printf("[DEBUG] ElastiCache Replication Group (%s) Primary Endpoint is not nil", d.Id())
d.Set(names.AttrPort, rgp.NodeGroups[0].PrimaryEndpoint.Port)
d.Set("primary_endpoint_address", rgp.NodeGroups[0].PrimaryEndpoint.Address)
}
if rgp.NodeGroups[0].ReaderEndpoint != nil {
d.Set("reader_endpoint_address", rgp.NodeGroups[0].ReaderEndpoint.Address)
}
}
d.Set("user_group_ids", rgp.UserGroupIds)
// Tags cannot be read when the replication group is not Available
log.Printf("[DEBUG] Waiting for ElastiCache Replication Group (%s) to become available", d.Id())
const (
delay = 0 * time.Second
)
if _, err := waitReplicationGroupAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate), delay); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for ElastiCache Replication Group (%s) create: %s", aws.ToString(rgp.ARN), err)
}
log.Printf("[DEBUG] ElastiCache Replication Group (%s): Checking underlying cache clusters", d.Id())
// This section reads settings that require checking the underlying cache clusters
if rgp.NodeGroups != nil && len(rgp.NodeGroups[0].NodeGroupMembers) != 0 {
cacheCluster := rgp.NodeGroups[0].NodeGroupMembers[0]
input := &elasticache.DescribeCacheClustersInput{
CacheClusterId: cacheCluster.CacheClusterId,
ShowCacheNodeInfo: aws.Bool(true),
}
output, err := conn.DescribeCacheClusters(ctx, input)
if err != nil {
return sdkdiag.AppendErrorf(diags, "reading ElastiCache Replication Group (%s): reading Cache Cluster (%s): %s", d.Id(), aws.ToString(cacheCluster.CacheClusterId), err)
}
if len(output.CacheClusters) == 0 {
return diags
}
c := output.CacheClusters[0]
if err := setFromCacheCluster(d, &c); err != nil {
return sdkdiag.AppendErrorf(diags, "reading ElastiCache Replication Group (%s): reading Cache Cluster (%s): %s", d.Id(), aws.ToString(cacheCluster.CacheClusterId), err)
}
d.Set("at_rest_encryption_enabled", c.AtRestEncryptionEnabled)
// `aws_elasticache_cluster` resource doesn't define `security_group_names`, but `aws_elasticache_replication_group` does.
// The value for that comes from []CacheSecurityGroupMembership which is part of CacheCluster object in AWS API.
// We need to set it here, as it is not set in setFromCacheCluster, and we cannot add it to that function
// without adding `security_group_names` property to `aws_elasticache_cluster` resource.
// This fixes the issue when importing `aws_elasticache_replication_group` where Terraform decides to recreate the imported cluster,
// because of `security_group_names` is not set and is "(known after apply)"
d.Set("security_group_names", flattenSecurityGroupNames(c.CacheSecurityGroups))
d.Set("transit_encryption_enabled", c.TransitEncryptionEnabled)
d.Set("transit_encryption_mode", c.TransitEncryptionMode)
if c.AuthTokenEnabled != nil && !aws.ToBool(c.AuthTokenEnabled) {
d.Set("auth_token", nil)
}
}
return diags
}
func resourceReplicationGroupUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
conn := meta.(*conns.AWSClient).ElastiCacheClient(ctx)
if d.HasChangesExcept(names.AttrTags, names.AttrTagsAll) {
o, n := d.GetChange("num_cache_clusters")
oldCacheClusterCount, newCacheClusterCount := o.(int), n.(int)
if d.HasChanges("num_node_groups", "replicas_per_node_group") {
if err := modifyReplicationGroupShardConfiguration(ctx, conn, d); err != nil {
return sdkdiag.AppendFromErr(diags, err)
}
} else if d.HasChange("num_cache_clusters") {
if newCacheClusterCount > oldCacheClusterCount {
if err := increaseReplicationGroupReplicaCount(ctx, conn, d.Id(), newCacheClusterCount, d.Timeout(schema.TimeoutUpdate)); err != nil {
return sdkdiag.AppendFromErr(diags, err)
}
} // Else defer until after all other modifications are made.
}
requestUpdate := false
input := &elasticache.ModifyReplicationGroupInput{
ApplyImmediately: aws.Bool(d.Get(names.AttrApplyImmediately).(bool)),
ReplicationGroupId: aws.String(d.Id()),
}
if d.HasChange(names.AttrAutoMinorVersionUpgrade) {
if v, ok := d.GetOk(names.AttrAutoMinorVersionUpgrade); ok {
if v, null, _ := nullable.Bool(v.(string)).ValueBool(); !null {
input.AutoMinorVersionUpgrade = aws.Bool(v)
requestUpdate = true
}
}
}
if d.HasChange("automatic_failover_enabled") {
input.AutomaticFailoverEnabled = aws.Bool(d.Get("automatic_failover_enabled").(bool))
requestUpdate = true
}
if d.HasChange(names.AttrDescription) {
input.ReplicationGroupDescription = aws.String(d.Get(names.AttrDescription).(string))
requestUpdate = true
}
if d.HasChange("cluster_mode") {
input.ClusterMode = awstypes.ClusterMode(d.Get("cluster_mode").(string))
requestUpdate = true
}
if old, new := d.GetChange(names.AttrEngine); old.(string) == engineRedis && new.(string) == engineValkey {
if !d.HasChange(names.AttrEngineVersion) {
return sdkdiag.AppendErrorf(diags, "must explicitly set '%s' attribute for Replication Group (%s) when updating engine to 'valkey'", names.AttrEngineVersion, d.Id())
}
input.Engine = aws.String(d.Get(names.AttrEngine).(string))
requestUpdate = true
}
if d.HasChange(names.AttrEngineVersion) {
input.EngineVersion = aws.String(d.Get(names.AttrEngineVersion).(string))
requestUpdate = true
}
if d.HasChange("ip_discovery") {
input.IpDiscovery = awstypes.IpDiscovery(d.Get("ip_discovery").(string))
requestUpdate = true
}
if d.HasChange("log_delivery_configuration") {
o, n := d.GetChange("log_delivery_configuration")
input.LogDeliveryConfigurations = []awstypes.LogDeliveryConfigurationRequest{}
logTypesToSubmit := make(map[awstypes.LogType]bool)
currentLogDeliveryConfig := n.(*schema.Set).List()
for _, current := range currentLogDeliveryConfig {
logDeliveryConfigurationRequest := expandLogDeliveryConfigurationRequests(current.(map[string]interface{}))
logTypesToSubmit[logDeliveryConfigurationRequest.LogType] = true
input.LogDeliveryConfigurations = append(input.LogDeliveryConfigurations, logDeliveryConfigurationRequest)
}
previousLogDeliveryConfig := o.(*schema.Set).List()
for _, previous := range previousLogDeliveryConfig {
logDeliveryConfigurationRequest := expandEmptyLogDeliveryConfigurationRequest(previous.(map[string]interface{}))
//if something was removed, send an empty request
if !logTypesToSubmit[logDeliveryConfigurationRequest.LogType] {
input.LogDeliveryConfigurations = append(input.LogDeliveryConfigurations, logDeliveryConfigurationRequest)
}
}
requestUpdate = true
}
if d.HasChange("maintenance_window") {
input.PreferredMaintenanceWindow = aws.String(d.Get("maintenance_window").(string))
requestUpdate = true
}
if d.HasChange("multi_az_enabled") {
input.MultiAZEnabled = aws.Bool(d.Get("multi_az_enabled").(bool))
requestUpdate = true
}
if d.HasChange("network_type") {
input.IpDiscovery = awstypes.IpDiscovery(d.Get("network_type").(string))
requestUpdate = true
}
if d.HasChange("node_type") {
input.CacheNodeType = aws.String(d.Get("node_type").(string))
requestUpdate = true
}
if d.HasChange("notification_topic_arn") {
input.NotificationTopicArn = aws.String(d.Get("notification_topic_arn").(string))
requestUpdate = true
}
if d.HasChange(names.AttrParameterGroupName) {
input.CacheParameterGroupName = aws.String(d.Get(names.AttrParameterGroupName).(string))
requestUpdate = true
}
if d.HasChange(names.AttrSecurityGroupIDs) {
if v, ok := d.GetOk(names.AttrSecurityGroupIDs); ok && v.(*schema.Set).Len() > 0 {
input.SecurityGroupIds = flex.ExpandStringValueSet(v.(*schema.Set))
requestUpdate = true
}
}
if d.HasChange("security_group_names") {
if v, ok := d.GetOk("security_group_names"); ok && v.(*schema.Set).Len() > 0 {
input.CacheSecurityGroupNames = flex.ExpandStringValueSet(v.(*schema.Set))
requestUpdate = true
}
}
if d.HasChange("snapshot_retention_limit") {
// This is a real hack to set the Snapshotting Cluster ID to be the first Cluster in the RG.
o, _ := d.GetChange("snapshot_retention_limit")
if o.(int) == 0 {
input.SnapshottingClusterId = aws.String(fmt.Sprintf("%s-001", d.Id()))
}
input.SnapshotRetentionLimit = aws.Int32(int32(d.Get("snapshot_retention_limit").(int)))
requestUpdate = true
}
if d.HasChange("snapshot_window") {
input.SnapshotWindow = aws.String(d.Get("snapshot_window").(string))
requestUpdate = true
}
if d.HasChange("transit_encryption_enabled") {
input.TransitEncryptionEnabled = aws.Bool(d.Get("transit_encryption_enabled").(bool))
requestUpdate = true
}
if d.HasChange("transit_encryption_mode") {
input.TransitEncryptionMode = awstypes.TransitEncryptionMode(d.Get("transit_encryption_mode").(string))
requestUpdate = true
}
if d.HasChange("user_group_ids") {
o, n := d.GetChange("user_group_ids")
ns, os := n.(*schema.Set), o.(*schema.Set)
add, del := ns.Difference(os), os.Difference(ns)
if add.Len() > 0 {
input.UserGroupIdsToAdd = flex.ExpandStringValueSet(add)
requestUpdate = true
}
if del.Len() > 0 {
input.UserGroupIdsToRemove = flex.ExpandStringValueSet(del)
requestUpdate = true
}
}
if requestUpdate {
// tagging may cause this resource to not yet be available, so wait for it to be available
const (
delay = 30 * time.Second
)
if _, err := waitReplicationGroupAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate), delay); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for ElastiCache Replication Group (%s) update: %s", d.Id(), err)
}
_, err := conn.ModifyReplicationGroup(ctx, input)
if err != nil {
return sdkdiag.AppendErrorf(diags, "modifying ElastiCache Replication Group (%s): %s", d.Id(), err)
}
if _, err := waitReplicationGroupAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate), delay); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for ElastiCache Replication Group (%s) update: %s", d.Id(), err)
}
}
if d.HasChanges("auth_token", "auth_token_update_strategy") {
input := &elasticache.ModifyReplicationGroupInput{
ApplyImmediately: aws.Bool(true),
AuthToken: aws.String(d.Get("auth_token").(string)),
AuthTokenUpdateStrategy: awstypes.AuthTokenUpdateStrategyType(d.Get("auth_token_update_strategy").(string)),
ReplicationGroupId: aws.String(d.Id()),
}
// tagging may cause this resource to not yet be available, so wait for it to be available
const (
delay = 0 * time.Second
)
if _, err := waitReplicationGroupAvailable(ctx, conn, d.Id(), d.Timeout(schema.TimeoutUpdate), delay); err != nil {
return sdkdiag.AppendErrorf(diags, "waiting for ElastiCache Replication Group (%s) update: %s", d.Id(), err)
}