forked from hashicorp/terraform-provider-google
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_redis_instance.go
2024 lines (1795 loc) · 73.5 KB
/
resource_redis_instance.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
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** Type: MMv1 ***
//
// ----------------------------------------------------------------------------
//
// This file is automatically generated by Magic Modules and manual
// changes will be clobbered when the file is regenerated.
//
// Please read more about how to change this file in
// .github/CONTRIBUTING.md.
//
// ----------------------------------------------------------------------------
package google
import (
"context"
"fmt"
"log"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
// Is the new redis version less than the old one?
func isRedisVersionDecreasing(_ context.Context, old, new, _ interface{}) bool {
return isRedisVersionDecreasingFunc(old, new)
}
// separate function for unit testing
func isRedisVersionDecreasingFunc(old, new interface{}) bool {
if old == nil || new == nil {
return false
}
re := regexp.MustCompile(`REDIS_(\d+)_(\d+)`)
oldParsed := re.FindSubmatch([]byte(old.(string)))
newParsed := re.FindSubmatch([]byte(new.(string)))
if oldParsed == nil || newParsed == nil {
return false
}
oldVersion, err := strconv.ParseFloat(fmt.Sprintf("%s.%s", oldParsed[1], oldParsed[2]), 32)
if err != nil {
return false
}
newVersion, err := strconv.ParseFloat(fmt.Sprintf("%s.%s", newParsed[1], newParsed[2]), 32)
if err != nil {
return false
}
return newVersion < oldVersion
}
// returns true if old=new or old='auto'
func secondaryIpDiffSuppress(_, old, new string, _ *schema.ResourceData) bool {
if (strings.ToLower(new) == "auto" && old != "") || old == new {
return true
}
return false
}
func resourceRedisInstance() *schema.Resource {
return &schema.Resource{
Create: resourceRedisInstanceCreate,
Read: resourceRedisInstanceRead,
Update: resourceRedisInstanceUpdate,
Delete: resourceRedisInstanceDelete,
Importer: &schema.ResourceImporter{
State: resourceRedisInstanceImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(20 * time.Minute),
Update: schema.DefaultTimeout(20 * time.Minute),
Delete: schema.DefaultTimeout(20 * time.Minute),
},
CustomizeDiff: customdiff.All(
customdiff.ForceNewIfChange("redis_version", isRedisVersionDecreasing)),
Schema: map[string]*schema.Schema{
"memory_size_gb": {
Type: schema.TypeInt,
Required: true,
Description: `Redis memory size in GiB.`,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateRegexp(`^[a-z][a-z0-9-]{0,39}[a-z0-9]$`),
Description: `The ID of the instance or a fully qualified identifier for the instance.`,
},
"alternative_location_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
Description: `Only applicable to STANDARD_HA tier which protects the instance
against zonal failures by provisioning it across two zones.
If provided, it must be a different zone from the one provided in
[locationId].`,
},
"auth_enabled": {
Type: schema.TypeBool,
Optional: true,
Description: `Optional. Indicates whether OSS Redis AUTH is enabled for the
instance. If set to "true" AUTH is enabled on the instance.
Default value is "false" meaning AUTH is disabled.`,
Default: false,
},
"authorized_network": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
DiffSuppressFunc: compareSelfLinkOrResourceName,
Description: `The full name of the Google Compute Engine network to which the
instance is connected. If left unspecified, the default network
will be used.`,
},
"connect_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validateEnum([]string{"DIRECT_PEERING", "PRIVATE_SERVICE_ACCESS", ""}),
Description: `The connection mode of the Redis instance. Default value: "DIRECT_PEERING" Possible values: ["DIRECT_PEERING", "PRIVATE_SERVICE_ACCESS"]`,
Default: "DIRECT_PEERING",
},
"customer_managed_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `Optional. The KMS key reference that you want to use to encrypt the data at rest for this Redis
instance. If this is provided, CMEK is enabled.`,
},
"display_name": {
Type: schema.TypeString,
Optional: true,
Description: `An arbitrary and optional user-provided name for the instance.`,
},
"labels": {
Type: schema.TypeMap,
Optional: true,
Description: `Resource labels to represent user provided metadata.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"location_id": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
Description: `The zone where the instance will be provisioned. If not provided,
the service will choose a zone for the instance. For STANDARD_HA tier,
instances will be created across two zones for protection against
zonal failures. If [alternativeLocationId] is also provided, it must
be different from [locationId].`,
},
"maintenance_policy": {
Type: schema.TypeList,
Optional: true,
Description: `Maintenance policy for an instance.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"description": {
Type: schema.TypeString,
Optional: true,
Description: `Optional. Description of what this policy is for.
Create/Update methods return INVALID_ARGUMENT if the
length is greater than 512.`,
},
"weekly_maintenance_window": {
Type: schema.TypeList,
Optional: true,
Description: `Optional. Maintenance window that is applied to resources covered by this policy.
Minimum 1. For the current version, the maximum number
of weekly_window is expected to be one.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"day": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validateEnum([]string{"DAY_OF_WEEK_UNSPECIFIED", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"}),
Description: `Required. The day of week that maintenance updates occur.
- DAY_OF_WEEK_UNSPECIFIED: The day of the week is unspecified.
- MONDAY: Monday
- TUESDAY: Tuesday
- WEDNESDAY: Wednesday
- THURSDAY: Thursday
- FRIDAY: Friday
- SATURDAY: Saturday
- SUNDAY: Sunday Possible values: ["DAY_OF_WEEK_UNSPECIFIED", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]`,
},
"start_time": {
Type: schema.TypeList,
Required: true,
Description: `Required. Start time of the window in UTC time.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"hours": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 23),
Description: `Hours of day in 24 hour format. Should be from 0 to 23.
An API may choose to allow the value "24:00:00" for scenarios like business closing time.`,
},
"minutes": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 59),
Description: `Minutes of hour of day. Must be from 0 to 59.`,
},
"nanos": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 999999999),
Description: `Fractions of seconds in nanoseconds. Must be from 0 to 999,999,999.`,
},
"seconds": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 60),
Description: `Seconds of minutes of the time. Must normally be from 0 to 59.
An API may allow the value 60 if it allows leap-seconds.`,
},
},
},
},
"duration": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Duration of the maintenance window.
The current window is fixed at 1 hour.
A duration in seconds with up to nine fractional digits,
terminated by 's'. Example: "3.5s".`,
},
},
},
},
"create_time": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. The time when the policy was created.
A timestamp in RFC3339 UTC "Zulu" format, with nanosecond
resolution and up to nine fractional digits.`,
},
"update_time": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. The time when the policy was last updated.
A timestamp in RFC3339 UTC "Zulu" format, with nanosecond
resolution and up to nine fractional digits.`,
},
},
},
},
"maintenance_schedule": {
Type: schema.TypeList,
Optional: true,
Description: `Upcoming maintenance schedule.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"end_time": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. The end time of any upcoming scheduled maintenance for this instance.
A timestamp in RFC3339 UTC "Zulu" format, with nanosecond
resolution and up to nine fractional digits.`,
},
"schedule_deadline_time": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. The deadline that the maintenance schedule start time
can not go beyond, including reschedule.
A timestamp in RFC3339 UTC "Zulu" format, with nanosecond
resolution and up to nine fractional digits.`,
},
"start_time": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. The start time of any upcoming scheduled maintenance for this instance.
A timestamp in RFC3339 UTC "Zulu" format, with nanosecond
resolution and up to nine fractional digits.`,
},
},
},
},
"persistence_config": {
Type: schema.TypeList,
Computed: true,
Optional: true,
Description: `Maintenance policy for an instance.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"persistence_mode": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ValidateFunc: validateEnum([]string{"DISABLED", "RDB"}),
Description: `Optional. Controls whether Persistence features are enabled. If not provided, the existing value will be used.
- DISABLED: Persistence is disabled for the instance, and any existing snapshots are deleted.
- RDB: RDB based Persistence is enabled. Possible values: ["DISABLED", "RDB"]`,
},
"rdb_snapshot_period": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateEnum([]string{"ONE_HOUR", "SIX_HOURS", "TWELVE_HOURS", "TWENTY_FOUR_HOURS", ""}),
Description: `Optional. Available snapshot periods for scheduling.
- ONE_HOUR: Snapshot every 1 hour.
- SIX_HOURS: Snapshot every 6 hours.
- TWELVE_HOURS: Snapshot every 12 hours.
- TWENTY_FOUR_HOURS: Snapshot every 24 horus. Possible values: ["ONE_HOUR", "SIX_HOURS", "TWELVE_HOURS", "TWENTY_FOUR_HOURS"]`,
},
"rdb_snapshot_start_time": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: `Optional. Date and time that the first snapshot was/will be attempted,
and to which future snapshots will be aligned. If not provided,
the current time will be used.
A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution
and up to nine fractional digits.
Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".`,
},
"rdb_next_snapshot_time": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. The next time that a snapshot attempt is scheduled to occur.
A timestamp in RFC3339 UTC "Zulu" format, with nanosecond resolution and up
to nine fractional digits.
Examples: "2014-10-02T15:01:23Z" and "2014-10-02T15:01:23.045123456Z".`,
},
},
},
},
"read_replicas_mode": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ValidateFunc: validateEnum([]string{"READ_REPLICAS_DISABLED", "READ_REPLICAS_ENABLED", ""}),
Description: `Optional. Read replica mode. Can only be specified when trying to create the instance.
If not set, Memorystore Redis backend will default to READ_REPLICAS_DISABLED.
- READ_REPLICAS_DISABLED: If disabled, read endpoint will not be provided and the
instance cannot scale up or down the number of replicas.
- READ_REPLICAS_ENABLED: If enabled, read endpoint will be provided and the instance
can scale up and down the number of replicas. Possible values: ["READ_REPLICAS_DISABLED", "READ_REPLICAS_ENABLED"]`,
},
"redis_configs": {
Type: schema.TypeMap,
Optional: true,
Description: `Redis configuration parameters, according to http://redis.io/topics/config.
Please check Memorystore documentation for the list of supported parameters:
https://cloud.google.com/memorystore/docs/redis/reference/rest/v1/projects.locations.instances#Instance.FIELDS.redis_configs`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"redis_version": {
Type: schema.TypeString,
Computed: true,
Optional: true,
Description: `The version of Redis software. If not provided, latest supported
version will be used. Please check the API documentation linked
at the top for the latest valid values.`,
},
"region": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
Description: `The name of the Redis region of the instance.`,
},
"replica_count": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
Description: `Optional. The number of replica nodes. The valid range for the Standard Tier with
read replicas enabled is [1-5] and defaults to 2. If read replicas are not enabled
for a Standard Tier instance, the only valid value is 1 and the default is 1.
The valid value for basic tier is 0 and the default is also 0.`,
},
"reserved_ip_range": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ForceNew: true,
Description: `The CIDR range of internal addresses that are reserved for this
instance. If not provided, the service will choose an unused /29
block, for example, 10.0.0.0/29 or 192.168.0.0/29. Ranges must be
unique and non-overlapping with existing subnets in an authorized
network.`,
},
"secondary_ip_range": {
Type: schema.TypeString,
Computed: true,
Optional: true,
DiffSuppressFunc: secondaryIpDiffSuppress,
Description: `Optional. Additional IP range for node placement. Required when enabling read replicas on
an existing instance. For DIRECT_PEERING mode value must be a CIDR range of size /28, or
"auto". For PRIVATE_SERVICE_ACCESS mode value must be the name of an allocated address
range associated with the private service access connection, or "auto".`,
},
"tier": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validateEnum([]string{"BASIC", "STANDARD_HA", ""}),
Description: `The service tier of the instance. Must be one of these values:
- BASIC: standalone instance
- STANDARD_HA: highly available primary/replica instances Default value: "BASIC" Possible values: ["BASIC", "STANDARD_HA"]`,
Default: "BASIC",
},
"transit_encryption_mode": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validateEnum([]string{"SERVER_AUTHENTICATION", "DISABLED", ""}),
Description: `The TLS mode of the Redis instance, If not provided, TLS is disabled for the instance.
- SERVER_AUTHENTICATION: Client to Server traffic encryption enabled with server authentication Default value: "DISABLED" Possible values: ["SERVER_AUTHENTICATION", "DISABLED"]`,
Default: "DISABLED",
},
"create_time": {
Type: schema.TypeString,
Computed: true,
Description: `The time the instance was created in RFC3339 UTC "Zulu" format,
accurate to nanoseconds.`,
},
"current_location_id": {
Type: schema.TypeString,
Computed: true,
Description: `The current zone where the Redis endpoint is placed.
For Basic Tier instances, this will always be the same as the
[locationId] provided by the user at creation time. For Standard Tier
instances, this can be either [locationId] or [alternativeLocationId]
and can change after a failover event.`,
},
"host": {
Type: schema.TypeString,
Computed: true,
Description: `Hostname or IP address of the exposed Redis endpoint used by clients
to connect to the service.`,
},
"nodes": {
Type: schema.TypeList,
Computed: true,
Description: `Output only. Info per node.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
Description: `Node identifying string. e.g. 'node-0', 'node-1'`,
},
"zone": {
Type: schema.TypeString,
Computed: true,
Description: `Location of the node.`,
},
},
},
},
"persistence_iam_identity": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Cloud IAM identity used by import / export operations
to transfer data to/from Cloud Storage. Format is "serviceAccount:".
The value may change over time for a given instance so should be
checked before each import/export operation.`,
},
"port": {
Type: schema.TypeInt,
Computed: true,
Description: `The port number of the exposed Redis endpoint.`,
},
"read_endpoint": {
Type: schema.TypeString,
Computed: true,
Description: `Output only. Hostname or IP address of the exposed readonly Redis endpoint. Standard tier only.
Targets all healthy replica nodes in instance. Replication is asynchronous and replica nodes
will exhibit some lag behind the primary. Write requests must target 'host'.`,
},
"read_endpoint_port": {
Type: schema.TypeInt,
Computed: true,
Description: `Output only. The port number of the exposed readonly redis endpoint. Standard tier only.
Write requests should target 'port'.`,
},
"server_ca_certs": {
Type: schema.TypeList,
Computed: true,
Description: `List of server CA certificates for the instance.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cert": {
Type: schema.TypeString,
Computed: true,
Description: `The certificate data in PEM format.`,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
Description: `The time when the certificate was created.`,
},
"expire_time": {
Type: schema.TypeString,
Computed: true,
Description: `The time when the certificate expires.`,
},
"serial_number": {
Type: schema.TypeString,
Computed: true,
Description: `Serial number, as extracted from the certificate.`,
},
"sha1_fingerprint": {
Type: schema.TypeString,
Computed: true,
Description: `Sha1 Fingerprint of the certificate.`,
},
},
},
},
"auth_string": {
Type: schema.TypeString,
Description: "AUTH String set on the instance. This field will only be populated if auth_enabled is true.",
Computed: true,
Sensitive: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
UseJSONNumber: true,
}
}
func resourceRedisInstanceCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
obj := make(map[string]interface{})
alternativeLocationIdProp, err := expandRedisInstanceAlternativeLocationId(d.Get("alternative_location_id"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("alternative_location_id"); !isEmptyValue(reflect.ValueOf(alternativeLocationIdProp)) && (ok || !reflect.DeepEqual(v, alternativeLocationIdProp)) {
obj["alternativeLocationId"] = alternativeLocationIdProp
}
authEnabledProp, err := expandRedisInstanceAuthEnabled(d.Get("auth_enabled"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("auth_enabled"); !isEmptyValue(reflect.ValueOf(authEnabledProp)) && (ok || !reflect.DeepEqual(v, authEnabledProp)) {
obj["authEnabled"] = authEnabledProp
}
authorizedNetworkProp, err := expandRedisInstanceAuthorizedNetwork(d.Get("authorized_network"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("authorized_network"); !isEmptyValue(reflect.ValueOf(authorizedNetworkProp)) && (ok || !reflect.DeepEqual(v, authorizedNetworkProp)) {
obj["authorizedNetwork"] = authorizedNetworkProp
}
connectModeProp, err := expandRedisInstanceConnectMode(d.Get("connect_mode"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("connect_mode"); !isEmptyValue(reflect.ValueOf(connectModeProp)) && (ok || !reflect.DeepEqual(v, connectModeProp)) {
obj["connectMode"] = connectModeProp
}
displayNameProp, err := expandRedisInstanceDisplayName(d.Get("display_name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("display_name"); !isEmptyValue(reflect.ValueOf(displayNameProp)) && (ok || !reflect.DeepEqual(v, displayNameProp)) {
obj["displayName"] = displayNameProp
}
labelsProp, err := expandRedisInstanceLabels(d.Get("labels"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(labelsProp)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
obj["labels"] = labelsProp
}
redisConfigsProp, err := expandRedisInstanceRedisConfigs(d.Get("redis_configs"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("redis_configs"); !isEmptyValue(reflect.ValueOf(redisConfigsProp)) && (ok || !reflect.DeepEqual(v, redisConfigsProp)) {
obj["redisConfigs"] = redisConfigsProp
}
locationIdProp, err := expandRedisInstanceLocationId(d.Get("location_id"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("location_id"); !isEmptyValue(reflect.ValueOf(locationIdProp)) && (ok || !reflect.DeepEqual(v, locationIdProp)) {
obj["locationId"] = locationIdProp
}
nameProp, err := expandRedisInstanceName(d.Get("name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("name"); !isEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) {
obj["name"] = nameProp
}
persistenceConfigProp, err := expandRedisInstancePersistenceConfig(d.Get("persistence_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("persistence_config"); !isEmptyValue(reflect.ValueOf(persistenceConfigProp)) && (ok || !reflect.DeepEqual(v, persistenceConfigProp)) {
obj["persistenceConfig"] = persistenceConfigProp
}
maintenancePolicyProp, err := expandRedisInstanceMaintenancePolicy(d.Get("maintenance_policy"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("maintenance_policy"); !isEmptyValue(reflect.ValueOf(maintenancePolicyProp)) && (ok || !reflect.DeepEqual(v, maintenancePolicyProp)) {
obj["maintenancePolicy"] = maintenancePolicyProp
}
maintenanceScheduleProp, err := expandRedisInstanceMaintenanceSchedule(d.Get("maintenance_schedule"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("maintenance_schedule"); !isEmptyValue(reflect.ValueOf(maintenanceScheduleProp)) && (ok || !reflect.DeepEqual(v, maintenanceScheduleProp)) {
obj["maintenanceSchedule"] = maintenanceScheduleProp
}
memorySizeGbProp, err := expandRedisInstanceMemorySizeGb(d.Get("memory_size_gb"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("memory_size_gb"); !isEmptyValue(reflect.ValueOf(memorySizeGbProp)) && (ok || !reflect.DeepEqual(v, memorySizeGbProp)) {
obj["memorySizeGb"] = memorySizeGbProp
}
redisVersionProp, err := expandRedisInstanceRedisVersion(d.Get("redis_version"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("redis_version"); !isEmptyValue(reflect.ValueOf(redisVersionProp)) && (ok || !reflect.DeepEqual(v, redisVersionProp)) {
obj["redisVersion"] = redisVersionProp
}
reservedIpRangeProp, err := expandRedisInstanceReservedIpRange(d.Get("reserved_ip_range"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("reserved_ip_range"); !isEmptyValue(reflect.ValueOf(reservedIpRangeProp)) && (ok || !reflect.DeepEqual(v, reservedIpRangeProp)) {
obj["reservedIpRange"] = reservedIpRangeProp
}
tierProp, err := expandRedisInstanceTier(d.Get("tier"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("tier"); !isEmptyValue(reflect.ValueOf(tierProp)) && (ok || !reflect.DeepEqual(v, tierProp)) {
obj["tier"] = tierProp
}
transitEncryptionModeProp, err := expandRedisInstanceTransitEncryptionMode(d.Get("transit_encryption_mode"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("transit_encryption_mode"); !isEmptyValue(reflect.ValueOf(transitEncryptionModeProp)) && (ok || !reflect.DeepEqual(v, transitEncryptionModeProp)) {
obj["transitEncryptionMode"] = transitEncryptionModeProp
}
replicaCountProp, err := expandRedisInstanceReplicaCount(d.Get("replica_count"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("replica_count"); !isEmptyValue(reflect.ValueOf(replicaCountProp)) && (ok || !reflect.DeepEqual(v, replicaCountProp)) {
obj["replicaCount"] = replicaCountProp
}
readReplicasModeProp, err := expandRedisInstanceReadReplicasMode(d.Get("read_replicas_mode"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("read_replicas_mode"); !isEmptyValue(reflect.ValueOf(readReplicasModeProp)) && (ok || !reflect.DeepEqual(v, readReplicasModeProp)) {
obj["readReplicasMode"] = readReplicasModeProp
}
secondaryIpRangeProp, err := expandRedisInstanceSecondaryIpRange(d.Get("secondary_ip_range"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("secondary_ip_range"); !isEmptyValue(reflect.ValueOf(secondaryIpRangeProp)) && (ok || !reflect.DeepEqual(v, secondaryIpRangeProp)) {
obj["secondaryIpRange"] = secondaryIpRangeProp
}
customerManagedKeyProp, err := expandRedisInstanceCustomerManagedKey(d.Get("customer_managed_key"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("customer_managed_key"); !isEmptyValue(reflect.ValueOf(customerManagedKeyProp)) && (ok || !reflect.DeepEqual(v, customerManagedKeyProp)) {
obj["customerManagedKey"] = customerManagedKeyProp
}
obj, err = resourceRedisInstanceEncoder(d, meta, obj)
if err != nil {
return err
}
url, err := replaceVars(d, config, "{{RedisBasePath}}projects/{{project}}/locations/{{region}}/instances?instanceId={{name}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new Instance: %#v", obj)
billingProject := ""
project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Instance: %s", err)
}
billingProject = project
// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}
res, err := sendRequestWithTimeout(config, "POST", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate))
if err != nil {
return fmt.Errorf("Error creating Instance: %s", err)
}
// Store the ID now
id, err := replaceVars(d, config, "projects/{{project}}/locations/{{region}}/instances/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
// Use the resource in the operation response to populate
// identity fields and d.Id() before read
var opRes map[string]interface{}
err = redisOperationWaitTimeWithResponse(
config, res, &opRes, project, "Creating Instance", userAgent,
d.Timeout(schema.TimeoutCreate))
if err != nil {
// The resource didn't actually create
d.SetId("")
return fmt.Errorf("Error waiting to create Instance: %s", err)
}
opRes, err = resourceRedisInstanceDecoder(d, meta, opRes)
if err != nil {
return fmt.Errorf("Error decoding response from operation: %s", err)
}
if opRes == nil {
return fmt.Errorf("Error decoding response from operation, could not find object")
}
if err := d.Set("name", flattenRedisInstanceName(opRes["name"], d, config)); err != nil {
return err
}
// This may have caused the ID to update - update it if so.
id, err = replaceVars(d, config, "projects/{{project}}/locations/{{region}}/instances/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
log.Printf("[DEBUG] Finished creating Instance %q: %#v", d.Id(), res)
return resourceRedisInstanceRead(d, meta)
}
func resourceRedisInstanceRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
url, err := replaceVars(d, config, "{{RedisBasePath}}projects/{{project}}/locations/{{region}}/instances/{{name}}")
if err != nil {
return err
}
billingProject := ""
project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Instance: %s", err)
}
billingProject = project
// err == nil indicates that the billing_project value was found
if bp, err := getBillingProject(d, config); err == nil {
billingProject = bp
}
res, err := sendRequest(config, "GET", billingProject, url, userAgent, nil)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("RedisInstance %q", d.Id()))
}
res, err = resourceRedisInstanceDecoder(d, meta, res)
if err != nil {
return err
}
if res == nil {
// Decoding the object has resulted in it being gone. It may be marked deleted
log.Printf("[DEBUG] Removing RedisInstance because it no longer exists.")
d.SetId("")
return nil
}
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
region, err := getRegion(d, config)
if err != nil {
return err
}
if err := d.Set("region", region); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("alternative_location_id", flattenRedisInstanceAlternativeLocationId(res["alternativeLocationId"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("auth_enabled", flattenRedisInstanceAuthEnabled(res["authEnabled"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("authorized_network", flattenRedisInstanceAuthorizedNetwork(res["authorizedNetwork"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("connect_mode", flattenRedisInstanceConnectMode(res["connectMode"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("create_time", flattenRedisInstanceCreateTime(res["createTime"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("current_location_id", flattenRedisInstanceCurrentLocationId(res["currentLocationId"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("display_name", flattenRedisInstanceDisplayName(res["displayName"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("host", flattenRedisInstanceHost(res["host"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("labels", flattenRedisInstanceLabels(res["labels"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("redis_configs", flattenRedisInstanceRedisConfigs(res["redisConfigs"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("location_id", flattenRedisInstanceLocationId(res["locationId"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("name", flattenRedisInstanceName(res["name"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("persistence_config", flattenRedisInstancePersistenceConfig(res["persistenceConfig"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("maintenance_policy", flattenRedisInstanceMaintenancePolicy(res["maintenancePolicy"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("maintenance_schedule", flattenRedisInstanceMaintenanceSchedule(res["maintenanceSchedule"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("memory_size_gb", flattenRedisInstanceMemorySizeGb(res["memorySizeGb"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("port", flattenRedisInstancePort(res["port"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("persistence_iam_identity", flattenRedisInstancePersistenceIamIdentity(res["persistenceIamIdentity"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("redis_version", flattenRedisInstanceRedisVersion(res["redisVersion"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("reserved_ip_range", flattenRedisInstanceReservedIpRange(res["reservedIpRange"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("tier", flattenRedisInstanceTier(res["tier"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("transit_encryption_mode", flattenRedisInstanceTransitEncryptionMode(res["transitEncryptionMode"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("server_ca_certs", flattenRedisInstanceServerCaCerts(res["serverCaCerts"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("replica_count", flattenRedisInstanceReplicaCount(res["replicaCount"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("nodes", flattenRedisInstanceNodes(res["nodes"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("read_endpoint", flattenRedisInstanceReadEndpoint(res["readEndpoint"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("read_endpoint_port", flattenRedisInstanceReadEndpointPort(res["readEndpointPort"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("read_replicas_mode", flattenRedisInstanceReadReplicasMode(res["readReplicasMode"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("secondary_ip_range", flattenRedisInstanceSecondaryIpRange(res["secondaryIpRange"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("customer_managed_key", flattenRedisInstanceCustomerManagedKey(res["customerManagedKey"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
return nil
}
func resourceRedisInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
billingProject := ""
project, err := getProject(d, config)
if err != nil {
return fmt.Errorf("Error fetching project for Instance: %s", err)
}
billingProject = project
obj := make(map[string]interface{})
authEnabledProp, err := expandRedisInstanceAuthEnabled(d.Get("auth_enabled"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("auth_enabled"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, authEnabledProp)) {
obj["authEnabled"] = authEnabledProp
}
displayNameProp, err := expandRedisInstanceDisplayName(d.Get("display_name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("display_name"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, displayNameProp)) {
obj["displayName"] = displayNameProp
}
labelsProp, err := expandRedisInstanceLabels(d.Get("labels"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("labels"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
obj["labels"] = labelsProp
}
redisConfigsProp, err := expandRedisInstanceRedisConfigs(d.Get("redis_configs"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("redis_configs"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, redisConfigsProp)) {
obj["redisConfigs"] = redisConfigsProp
}
persistenceConfigProp, err := expandRedisInstancePersistenceConfig(d.Get("persistence_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("persistence_config"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, persistenceConfigProp)) {
obj["persistenceConfig"] = persistenceConfigProp
}
maintenancePolicyProp, err := expandRedisInstanceMaintenancePolicy(d.Get("maintenance_policy"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("maintenance_policy"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, maintenancePolicyProp)) {
obj["maintenancePolicy"] = maintenancePolicyProp
}
maintenanceScheduleProp, err := expandRedisInstanceMaintenanceSchedule(d.Get("maintenance_schedule"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("maintenance_schedule"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, maintenanceScheduleProp)) {
obj["maintenanceSchedule"] = maintenanceScheduleProp
}
memorySizeGbProp, err := expandRedisInstanceMemorySizeGb(d.Get("memory_size_gb"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("memory_size_gb"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, memorySizeGbProp)) {
obj["memorySizeGb"] = memorySizeGbProp
}
replicaCountProp, err := expandRedisInstanceReplicaCount(d.Get("replica_count"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("replica_count"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, replicaCountProp)) {
obj["replicaCount"] = replicaCountProp
}
readReplicasModeProp, err := expandRedisInstanceReadReplicasMode(d.Get("read_replicas_mode"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("read_replicas_mode"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, readReplicasModeProp)) {
obj["readReplicasMode"] = readReplicasModeProp
}
secondaryIpRangeProp, err := expandRedisInstanceSecondaryIpRange(d.Get("secondary_ip_range"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("secondary_ip_range"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, secondaryIpRangeProp)) {
obj["secondaryIpRange"] = secondaryIpRangeProp
}
obj, err = resourceRedisInstanceEncoder(d, meta, obj)
if err != nil {
return err
}
url, err := replaceVars(d, config, "{{RedisBasePath}}projects/{{project}}/locations/{{region}}/instances/{{name}}")
if err != nil {