forked from hashicorp/terraform-provider-google
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_alloydb_instance.go
1630 lines (1456 loc) · 63.2 KB
/
resource_alloydb_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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** Type: MMv1 ***
//
// ----------------------------------------------------------------------------
//
// This code is generated by Magic Modules using the following:
//
// Configuration: https://github.com/GoogleCloudPlatform/magic-modules/tree/main/mmv1/products/alloydb/Instance.yaml
// Template: https://github.com/GoogleCloudPlatform/magic-modules/tree/main/mmv1/templates/terraform/resource.go.tmpl
//
// DO NOT EDIT this file directly. Any changes made to this file will be
// overwritten during the next generation cycle.
//
// ----------------------------------------------------------------------------
package alloydb
import (
"fmt"
"log"
"net/http"
"reflect"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-google/google/tpgresource"
transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport"
"github.com/hashicorp/terraform-provider-google/google/verify"
)
func ResourceAlloydbInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlloydbInstanceCreate,
Read: resourceAlloydbInstanceRead,
Update: resourceAlloydbInstanceUpdate,
Delete: resourceAlloydbInstanceDelete,
Importer: &schema.ResourceImporter{
State: resourceAlloydbInstanceImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(120 * time.Minute),
Update: schema.DefaultTimeout(120 * time.Minute),
Delete: schema.DefaultTimeout(120 * time.Minute),
},
CustomizeDiff: customdiff.All(
tpgresource.SetLabelsDiff,
tpgresource.SetAnnotationsDiff,
),
Schema: map[string]*schema.Schema{
"cluster": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName,
Description: `Identifies the alloydb cluster. Must be in the format
'projects/{project}/locations/{location}/clusters/{cluster_id}'`,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `The ID of the alloydb instance.`,
},
"instance_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: verify.ValidateEnum([]string{"PRIMARY", "READ_POOL", "SECONDARY"}),
Description: `The type of the instance.
If the instance type is READ_POOL, provide the associated PRIMARY/SECONDARY instance in the 'depends_on' meta-data attribute.
If the instance type is SECONDARY, point to the cluster_type of the associated secondary cluster instead of mentioning SECONDARY.
Example: {instance_type = google_alloydb_cluster.<secondary_cluster_name>.cluster_type} instead of {instance_type = SECONDARY}
If the instance type is SECONDARY, the terraform delete instance operation does not delete the secondary instance but abandons it instead.
Use deletion_policy = "FORCE" in the associated secondary cluster and delete the cluster forcefully to delete the secondary cluster as well its associated secondary instance.
Users can undo the delete secondary instance action by importing the deleted secondary instance by calling terraform import. Possible values: ["PRIMARY", "READ_POOL", "SECONDARY"]`,
},
"annotations": {
Type: schema.TypeMap,
Optional: true,
Description: `Annotations to allow client tools to store small amount of arbitrary data. This is distinct from labels.
**Note**: This field is non-authoritative, and will only manage the annotations present in your configuration.
Please refer to the field 'effective_annotations' for all of the annotations present on the resource.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"availability_type": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ValidateFunc: verify.ValidateEnum([]string{"AVAILABILITY_TYPE_UNSPECIFIED", "ZONAL", "REGIONAL", ""}),
Description: `'Availability type of an Instance. Defaults to REGIONAL for both primary and read instances.
Note that primary and read instances can have different availability types.
Primary instances can be either ZONAL or REGIONAL. Read Pool instances can also be either ZONAL or REGIONAL.
Read pools of size 1 can only have zonal availability. Read pools with a node count of 2 or more
can have regional availability (nodes are present in 2 or more zones in a region).
Possible values are: 'AVAILABILITY_TYPE_UNSPECIFIED', 'ZONAL', 'REGIONAL'.' Possible values: ["AVAILABILITY_TYPE_UNSPECIFIED", "ZONAL", "REGIONAL"]`,
},
"client_connection_config": {
Type: schema.TypeList,
Computed: true,
Optional: true,
Description: `Client connection specific configurations.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"require_connectors": {
Type: schema.TypeBool,
Optional: true,
Description: `Configuration to enforce connectors only (ex: AuthProxy) connections to the database.`,
},
"ssl_config": {
Type: schema.TypeList,
Computed: true,
Optional: true,
Description: `SSL config option for this instance.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ssl_mode": {
Type: schema.TypeString,
Computed: true,
Optional: true,
ValidateFunc: verify.ValidateEnum([]string{"ENCRYPTED_ONLY", "ALLOW_UNENCRYPTED_AND_ENCRYPTED", ""}),
Description: `SSL mode. Specifies client-server SSL/TLS connection behavior. Possible values: ["ENCRYPTED_ONLY", "ALLOW_UNENCRYPTED_AND_ENCRYPTED"]`,
},
},
},
},
},
},
},
"database_flags": {
Type: schema.TypeMap,
Computed: true,
Optional: true,
Description: `Database flags. Set at instance level. * They are copied from primary instance on read instance creation. * Read instances can set new or override existing flags that are relevant for reads, e.g. for enabling columnar cache on a read instance. Flags set on read instance may or may not be present on primary.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"display_name": {
Type: schema.TypeString,
Optional: true,
Description: `User-settable and human-readable display name for the Instance.`,
},
"gce_zone": {
Type: schema.TypeString,
Optional: true,
Description: `The Compute Engine zone that the instance should serve from, per https://cloud.google.com/compute/docs/regions-zones This can ONLY be specified for ZONAL instances. If present for a REGIONAL instance, an error will be thrown. If this is absent for a ZONAL instance, instance is created in a random zone with available capacity.`,
},
"labels": {
Type: schema.TypeMap,
Optional: true,
Description: `User-defined labels for the alloydb instance.
**Note**: This field is non-authoritative, and will only manage the labels present in your configuration.
Please refer to the field 'effective_labels' for all of the labels present on the resource.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"machine_config": {
Type: schema.TypeList,
Computed: true,
Optional: true,
Description: `Configurations for the machines that host the underlying database engine.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cpu_count": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
Description: `The number of CPU's in the VM instance.`,
},
},
},
},
"network_config": {
Type: schema.TypeList,
Optional: true,
Description: `Instance level network configuration.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"authorized_external_networks": {
Type: schema.TypeList,
Optional: true,
Description: `A list of external networks authorized to access this instance. This
field is only allowed to be set when 'enable_public_ip' is set to
true.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cidr_range": {
Type: schema.TypeString,
Optional: true,
Description: `CIDR range for one authorized network of the instance.`,
},
},
},
RequiredWith: []string{"network_config.0.enable_public_ip"},
},
"enable_outbound_public_ip": {
Type: schema.TypeBool,
Optional: true,
Description: `Enabling outbound public ip for the instance.`,
},
"enable_public_ip": {
Type: schema.TypeBool,
Optional: true,
Description: `Enabling public ip for the instance. If a user wishes to disable this,
please also clear the list of the authorized external networks set on
the same instance.`,
},
},
},
},
"psc_instance_config": {
Type: schema.TypeList,
Computed: true,
Optional: true,
Description: `Configuration for Private Service Connect (PSC) for the instance.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allowed_consumer_projects": {
Type: schema.TypeList,
Optional: true,
Description: `List of consumer projects that are allowed to create PSC endpoints to service-attachments to this instance.
These should be specified as project numbers only.`,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: verify.ValidateRegexp(`^\d+$`),
},
},
"psc_interface_configs": {
Type: schema.TypeList,
Optional: true,
Description: `Configurations for setting up PSC interfaces attached to the instance
which are used for outbound connectivity. Currently, AlloyDB supports only 0 or 1 PSC interface.`,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"network_attachment_resource": {
Type: schema.TypeString,
Optional: true,
Description: `The network attachment resource created in the consumer project to which the PSC interface will be linked.
This is of the format: "projects/${CONSUMER_PROJECT}/regions/${REGION}/networkAttachments/${NETWORK_ATTACHMENT_NAME}".
The network attachment must be in the same region as the instance.`,
},
},
},
},
"psc_dns_name": {
Type: schema.TypeString,
Computed: true,
Description: `The DNS name of the instance for PSC connectivity.
Name convention: <uid>.<uid>.<region>.alloydb-psc.goog`,
},
"service_attachment_link": {
Type: schema.TypeString,
Computed: true,
Description: `The service attachment created when Private Service Connect (PSC) is enabled for the instance.
The name of the resource will be in the format of
'projects/<alloydb-tenant-project-number>/regions/<region-name>/serviceAttachments/<service-attachment-name>'`,
},
},
},
},
"query_insights_config": {
Type: schema.TypeList,
Computed: true,
Optional: true,
Description: `Configuration for query insights.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"query_plans_per_minute": {
Type: schema.TypeInt,
Optional: true,
Description: `Number of query execution plans captured by Insights per minute for all queries combined. The default value is 5. Any integer between 0 and 20 is considered valid.`,
},
"query_string_length": {
Type: schema.TypeInt,
Optional: true,
Description: `Query string length. The default value is 1024. Any integer between 256 and 4500 is considered valid.`,
},
"record_application_tags": {
Type: schema.TypeBool,
Optional: true,
Description: `Record application tags for an instance. This flag is turned "on" by default.`,
},
"record_client_address": {
Type: schema.TypeBool,
Optional: true,
Description: `Record client address for an instance. Client address is PII information. This flag is turned "on" by default.`,
},
},
},
},
"read_pool_config": {
Type: schema.TypeList,
Optional: true,
Description: `Read pool specific config. If the instance type is READ_POOL, this configuration must be provided.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"node_count": {
Type: schema.TypeInt,
Optional: true,
Description: `Read capacity, i.e. number of nodes in a read pool instance.`,
},
},
},
},
"create_time": {
Type: schema.TypeString,
Computed: true,
Description: `Time the Instance was created in UTC.`,
},
"effective_annotations": {
Type: schema.TypeMap,
Computed: true,
Description: `All of annotations (key/value pairs) present on the resource in GCP, including the annotations configured through Terraform, other clients and services.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"effective_labels": {
Type: schema.TypeMap,
Computed: true,
Description: `All of labels (key/value pairs) present on the resource in GCP, including the labels configured through Terraform, other clients and services.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"ip_address": {
Type: schema.TypeString,
Computed: true,
Description: `The IP address for the Instance. This is the connection endpoint for an end-user application.`,
},
"name": {
Type: schema.TypeString,
Computed: true,
Description: `The name of the instance resource.`,
},
"outbound_public_ip_addresses": {
Type: schema.TypeList,
Computed: true,
Description: `The outbound public IP addresses for the instance. This is available ONLY when
networkConfig.enableOutboundPublicIp is set to true. These IP addresses are used
for outbound connections.`,
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"public_ip_address": {
Type: schema.TypeString,
Computed: true,
Description: `The public IP addresses for the Instance. This is available ONLY when
networkConfig.enablePublicIp is set to true. This is the connection
endpoint for an end-user application.`,
},
"reconciling": {
Type: schema.TypeBool,
Computed: true,
Description: `Set to true if the current state of Instance does not match the user's intended state, and the service is actively updating the resource to reconcile them. This can happen due to user-triggered updates or system actions like failover or maintenance.`,
},
"state": {
Type: schema.TypeString,
Computed: true,
Description: `The current state of the alloydb instance.`,
},
"terraform_labels": {
Type: schema.TypeMap,
Computed: true,
Description: `The combination of labels configured directly on the resource
and default labels configured on the provider.`,
Elem: &schema.Schema{Type: schema.TypeString},
},
"uid": {
Type: schema.TypeString,
Computed: true,
Description: `The system-generated UID of the resource.`,
},
"update_time": {
Type: schema.TypeString,
Computed: true,
Description: `Time the Instance was updated in UTC.`,
},
},
UseJSONNumber: true,
}
}
func resourceAlloydbInstanceCreate(d *schema.ResourceData, meta interface{}) error {
var project string
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
obj := make(map[string]interface{})
displayNameProp, err := expandAlloydbInstanceDisplayName(d.Get("display_name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("display_name"); !tpgresource.IsEmptyValue(reflect.ValueOf(displayNameProp)) && (ok || !reflect.DeepEqual(v, displayNameProp)) {
obj["displayName"] = displayNameProp
}
gceZoneProp, err := expandAlloydbInstanceGceZone(d.Get("gce_zone"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("gce_zone"); !tpgresource.IsEmptyValue(reflect.ValueOf(gceZoneProp)) && (ok || !reflect.DeepEqual(v, gceZoneProp)) {
obj["gceZone"] = gceZoneProp
}
databaseFlagsProp, err := expandAlloydbInstanceDatabaseFlags(d.Get("database_flags"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("database_flags"); !tpgresource.IsEmptyValue(reflect.ValueOf(databaseFlagsProp)) && (ok || !reflect.DeepEqual(v, databaseFlagsProp)) {
obj["databaseFlags"] = databaseFlagsProp
}
availabilityTypeProp, err := expandAlloydbInstanceAvailabilityType(d.Get("availability_type"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("availability_type"); !tpgresource.IsEmptyValue(reflect.ValueOf(availabilityTypeProp)) && (ok || !reflect.DeepEqual(v, availabilityTypeProp)) {
obj["availabilityType"] = availabilityTypeProp
}
instanceTypeProp, err := expandAlloydbInstanceInstanceType(d.Get("instance_type"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("instance_type"); !tpgresource.IsEmptyValue(reflect.ValueOf(instanceTypeProp)) && (ok || !reflect.DeepEqual(v, instanceTypeProp)) {
obj["instanceType"] = instanceTypeProp
}
queryInsightsConfigProp, err := expandAlloydbInstanceQueryInsightsConfig(d.Get("query_insights_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("query_insights_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(queryInsightsConfigProp)) && (ok || !reflect.DeepEqual(v, queryInsightsConfigProp)) {
obj["queryInsightsConfig"] = queryInsightsConfigProp
}
readPoolConfigProp, err := expandAlloydbInstanceReadPoolConfig(d.Get("read_pool_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("read_pool_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(readPoolConfigProp)) && (ok || !reflect.DeepEqual(v, readPoolConfigProp)) {
obj["readPoolConfig"] = readPoolConfigProp
}
machineConfigProp, err := expandAlloydbInstanceMachineConfig(d.Get("machine_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("machine_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(machineConfigProp)) && (ok || !reflect.DeepEqual(v, machineConfigProp)) {
obj["machineConfig"] = machineConfigProp
}
clientConnectionConfigProp, err := expandAlloydbInstanceClientConnectionConfig(d.Get("client_connection_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("client_connection_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(clientConnectionConfigProp)) && (ok || !reflect.DeepEqual(v, clientConnectionConfigProp)) {
obj["clientConnectionConfig"] = clientConnectionConfigProp
}
pscInstanceConfigProp, err := expandAlloydbInstancePscInstanceConfig(d.Get("psc_instance_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("psc_instance_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(pscInstanceConfigProp)) && (ok || !reflect.DeepEqual(v, pscInstanceConfigProp)) {
obj["pscInstanceConfig"] = pscInstanceConfigProp
}
networkConfigProp, err := expandAlloydbInstanceNetworkConfig(d.Get("network_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("network_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(networkConfigProp)) && (ok || !reflect.DeepEqual(v, networkConfigProp)) {
obj["networkConfig"] = networkConfigProp
}
labelsProp, err := expandAlloydbInstanceEffectiveLabels(d.Get("effective_labels"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("effective_labels"); !tpgresource.IsEmptyValue(reflect.ValueOf(labelsProp)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
obj["labels"] = labelsProp
}
annotationsProp, err := expandAlloydbInstanceEffectiveAnnotations(d.Get("effective_annotations"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("effective_annotations"); !tpgresource.IsEmptyValue(reflect.ValueOf(annotationsProp)) && (ok || !reflect.DeepEqual(v, annotationsProp)) {
obj["annotations"] = annotationsProp
}
url, err := tpgresource.ReplaceVars(d, config, "{{AlloydbBasePath}}{{cluster}}/instances?instanceId={{instance_id}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Creating new Instance: %#v", obj)
billingProject := ""
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
headers := make(http.Header)
// Read the config and call createsecondary api if instance_type is SECONDARY
if instanceType := d.Get("instance_type"); instanceType == "SECONDARY" {
url = strings.Replace(url, "instances?instanceId", "instances:createsecondary?instanceId", 1)
}
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutCreate),
Headers: headers,
})
if err != nil {
return fmt.Errorf("Error creating Instance: %s", err)
}
// Store the ID now
id, err := tpgresource.ReplaceVars(d, config, "{{cluster}}/instances/{{instance_id}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
err = AlloydbOperationWaitTime(
config, res, 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)
}
log.Printf("[DEBUG] Finished creating Instance %q: %#v", d.Id(), res)
return resourceAlloydbInstanceRead(d, meta)
}
func resourceAlloydbInstanceRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
url, err := tpgresource.ReplaceVars(d, config, "{{AlloydbBasePath}}{{cluster}}/instances/{{instance_id}}")
if err != nil {
return err
}
billingProject := ""
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
headers := make(http.Header)
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "GET",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Headers: headers,
})
if err != nil {
return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("AlloydbInstance %q", d.Id()))
}
if err := d.Set("name", flattenAlloydbInstanceName(res["name"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("create_time", flattenAlloydbInstanceCreateTime(res["createTime"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("update_time", flattenAlloydbInstanceUpdateTime(res["updateTime"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("uid", flattenAlloydbInstanceUid(res["uid"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("labels", flattenAlloydbInstanceLabels(res["labels"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("annotations", flattenAlloydbInstanceAnnotations(res["annotations"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("state", flattenAlloydbInstanceState(res["state"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("gce_zone", flattenAlloydbInstanceGceZone(res["gceZone"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("reconciling", flattenAlloydbInstanceReconciling(res["reconciling"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("database_flags", flattenAlloydbInstanceDatabaseFlags(res["databaseFlags"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("availability_type", flattenAlloydbInstanceAvailabilityType(res["availabilityType"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("instance_type", flattenAlloydbInstanceInstanceType(res["instanceType"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("ip_address", flattenAlloydbInstanceIpAddress(res["ipAddress"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("query_insights_config", flattenAlloydbInstanceQueryInsightsConfig(res["queryInsightsConfig"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("read_pool_config", flattenAlloydbInstanceReadPoolConfig(res["readPoolConfig"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("machine_config", flattenAlloydbInstanceMachineConfig(res["machineConfig"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("client_connection_config", flattenAlloydbInstanceClientConnectionConfig(res["clientConnectionConfig"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("psc_instance_config", flattenAlloydbInstancePscInstanceConfig(res["pscInstanceConfig"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("network_config", flattenAlloydbInstanceNetworkConfig(res["networkConfig"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("public_ip_address", flattenAlloydbInstancePublicIpAddress(res["publicIpAddress"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("outbound_public_ip_addresses", flattenAlloydbInstanceOutboundPublicIpAddresses(res["outboundPublicIpAddresses"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("terraform_labels", flattenAlloydbInstanceTerraformLabels(res["labels"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("effective_labels", flattenAlloydbInstanceEffectiveLabels(res["labels"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
if err := d.Set("effective_annotations", flattenAlloydbInstanceEffectiveAnnotations(res["annotations"], d, config)); err != nil {
return fmt.Errorf("Error reading Instance: %s", err)
}
return nil
}
func resourceAlloydbInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
var project string
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
billingProject := ""
obj := make(map[string]interface{})
displayNameProp, err := expandAlloydbInstanceDisplayName(d.Get("display_name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("display_name"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, displayNameProp)) {
obj["displayName"] = displayNameProp
}
gceZoneProp, err := expandAlloydbInstanceGceZone(d.Get("gce_zone"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("gce_zone"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, gceZoneProp)) {
obj["gceZone"] = gceZoneProp
}
databaseFlagsProp, err := expandAlloydbInstanceDatabaseFlags(d.Get("database_flags"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("database_flags"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, databaseFlagsProp)) {
obj["databaseFlags"] = databaseFlagsProp
}
availabilityTypeProp, err := expandAlloydbInstanceAvailabilityType(d.Get("availability_type"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("availability_type"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, availabilityTypeProp)) {
obj["availabilityType"] = availabilityTypeProp
}
queryInsightsConfigProp, err := expandAlloydbInstanceQueryInsightsConfig(d.Get("query_insights_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("query_insights_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, queryInsightsConfigProp)) {
obj["queryInsightsConfig"] = queryInsightsConfigProp
}
readPoolConfigProp, err := expandAlloydbInstanceReadPoolConfig(d.Get("read_pool_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("read_pool_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, readPoolConfigProp)) {
obj["readPoolConfig"] = readPoolConfigProp
}
machineConfigProp, err := expandAlloydbInstanceMachineConfig(d.Get("machine_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("machine_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, machineConfigProp)) {
obj["machineConfig"] = machineConfigProp
}
clientConnectionConfigProp, err := expandAlloydbInstanceClientConnectionConfig(d.Get("client_connection_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("client_connection_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, clientConnectionConfigProp)) {
obj["clientConnectionConfig"] = clientConnectionConfigProp
}
pscInstanceConfigProp, err := expandAlloydbInstancePscInstanceConfig(d.Get("psc_instance_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("psc_instance_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, pscInstanceConfigProp)) {
obj["pscInstanceConfig"] = pscInstanceConfigProp
}
networkConfigProp, err := expandAlloydbInstanceNetworkConfig(d.Get("network_config"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("network_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, networkConfigProp)) {
obj["networkConfig"] = networkConfigProp
}
labelsProp, err := expandAlloydbInstanceEffectiveLabels(d.Get("effective_labels"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("effective_labels"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
obj["labels"] = labelsProp
}
annotationsProp, err := expandAlloydbInstanceEffectiveAnnotations(d.Get("effective_annotations"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("effective_annotations"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, annotationsProp)) {
obj["annotations"] = annotationsProp
}
url, err := tpgresource.ReplaceVars(d, config, "{{AlloydbBasePath}}{{cluster}}/instances/{{instance_id}}")
if err != nil {
return err
}
log.Printf("[DEBUG] Updating Instance %q: %#v", d.Id(), obj)
headers := make(http.Header)
updateMask := []string{}
if d.HasChange("display_name") {
updateMask = append(updateMask, "displayName")
}
if d.HasChange("gce_zone") {
updateMask = append(updateMask, "gceZone")
}
if d.HasChange("database_flags") {
updateMask = append(updateMask, "databaseFlags")
}
if d.HasChange("availability_type") {
updateMask = append(updateMask, "availabilityType")
}
if d.HasChange("query_insights_config") {
updateMask = append(updateMask, "queryInsightsConfig")
}
if d.HasChange("read_pool_config") {
updateMask = append(updateMask, "readPoolConfig")
}
if d.HasChange("machine_config") {
updateMask = append(updateMask, "machineConfig")
}
if d.HasChange("client_connection_config") {
updateMask = append(updateMask, "clientConnectionConfig")
}
if d.HasChange("psc_instance_config") {
updateMask = append(updateMask, "pscInstanceConfig")
}
if d.HasChange("network_config") {
updateMask = append(updateMask, "networkConfig")
}
if d.HasChange("effective_labels") {
updateMask = append(updateMask, "labels")
}
if d.HasChange("effective_annotations") {
updateMask = append(updateMask, "annotations")
}
// updateMask is a URL parameter but not present in the schema, so ReplaceVars
// won't set it
url, err = transport_tpg.AddQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")})
if err != nil {
return err
}
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
// if updateMask is empty we are not updating anything so skip the post
if len(updateMask) > 0 {
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "PATCH",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutUpdate),
Headers: headers,
})
if err != nil {
return fmt.Errorf("Error updating Instance %q: %s", d.Id(), err)
} else {
log.Printf("[DEBUG] Finished updating Instance %q: %#v", d.Id(), res)
}
err = AlloydbOperationWaitTime(
config, res, project, "Updating Instance", userAgent,
d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
}
return resourceAlloydbInstanceRead(d, meta)
}
func resourceAlloydbInstanceDelete(d *schema.ResourceData, meta interface{}) error {
var project string
config := meta.(*transport_tpg.Config)
userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent)
if err != nil {
return err
}
billingProject := ""
url, err := tpgresource.ReplaceVars(d, config, "{{AlloydbBasePath}}{{cluster}}/instances/{{instance_id}}")
if err != nil {
return err
}
var obj map[string]interface{}
// err == nil indicates that the billing_project value was found
if bp, err := tpgresource.GetBillingProject(d, config); err == nil {
billingProject = bp
}
headers := make(http.Header)
// Read the config and avoid calling the delete API if the instance_type is SECONDARY and instead return nil
// Returning nil is equivalent of returning a success message to the users
// This is done because deletion of secondary instance is not supported
// Instead users should be deleting the secondary cluster which will forcefully delete the associated secondary instance
// A warning message prompts the user to delete the associated secondary cluster.
// Users can always undo the delete secondary instance action by importing the deleted secondary instance by calling terraform import
var instanceType interface{}
instanceTypeProp, err := expandAlloydbInstanceInstanceType(d.Get("instance_type"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("instance_type"); !tpgresource.IsEmptyValue(reflect.ValueOf(instanceTypeProp)) && (ok || !reflect.DeepEqual(v, instanceTypeProp)) {
instanceType = instanceTypeProp
}
if instanceType != nil && instanceType == "SECONDARY" {
log.Printf("[WARNING] This operation didn't delete the Secondary Instance %q. Please delete the associated Secondary Cluster as well to delete the entire cluster and the secondary instance.\n", d.Id())
return nil
}
log.Printf("[DEBUG] Deleting Instance %q", d.Id())
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "DELETE",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutDelete),
Headers: headers,
})
if err != nil {
return transport_tpg.HandleNotFoundError(err, d, "Instance")
}
err = AlloydbOperationWaitTime(
config, res, project, "Deleting Instance", userAgent,
d.Timeout(schema.TimeoutDelete))
if err != nil {
return err
}
log.Printf("[DEBUG] Finished deleting Instance %q: %#v", d.Id(), res)
return nil
}
func resourceAlloydbInstanceImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*transport_tpg.Config)
// current import_formats can't import fields with forward slashes in their value
if err := tpgresource.ParseImportId([]string{
"(?P<cluster>.+)/instances/(?P<instance_id>[^/]+)",
}, d, config); err != nil {
return nil, err
}
// Replace import id for the resource id
id, err := tpgresource.ReplaceVars(d, config, "{{cluster}}/instances/{{instance_id}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}
func flattenAlloydbInstanceName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenAlloydbInstanceCreateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenAlloydbInstanceUpdateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenAlloydbInstanceUid(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenAlloydbInstanceLabels(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
if v == nil {
return v
}
transformed := make(map[string]interface{})
if l, ok := d.GetOkExists("labels"); ok {
for k := range l.(map[string]interface{}) {
transformed[k] = v.(map[string]interface{})[k]
}
}
return transformed
}
func flattenAlloydbInstanceAnnotations(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
if v == nil {
return v
}
transformed := make(map[string]interface{})
if l, ok := d.GetOkExists("annotations"); ok {
for k := range l.(map[string]interface{}) {
transformed[k] = v.(map[string]interface{})[k]
}
}
return transformed
}
func flattenAlloydbInstanceState(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenAlloydbInstanceGceZone(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenAlloydbInstanceReconciling(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenAlloydbInstanceDatabaseFlags(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenAlloydbInstanceAvailabilityType(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenAlloydbInstanceInstanceType(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenAlloydbInstanceIpAddress(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
return v
}
func flattenAlloydbInstanceQueryInsightsConfig(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} {
if v == nil {
return nil
}
original := v.(map[string]interface{})
if len(original) == 0 {