forked from GoogleCloudPlatform/magic-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_sql_database_instance.go.erb
1842 lines (1658 loc) · 67.6 KB
/
resource_sql_database_instance.go.erb
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
<% autogen_exception -%>
package google
import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"google.golang.org/api/googleapi"
sqladmin "google.golang.org/api/sqladmin/v1beta4"
)
const privateNetworkLinkRegex = "projects/(" + ProjectRegex + ")/global/networks/((?:[a-z](?:[-a-z0-9]*[a-z0-9])?))$"
var sqlDatabaseAuthorizedNetWorkSchemaElem *schema.Resource = &schema.Resource{
Schema: map[string]*schema.Schema{
"expiration_time": {
Type: schema.TypeString,
Optional: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"value": {
Type: schema.TypeString,
Required: true,
},
},
}
var (
backupConfigurationKeys = []string{
"settings.0.backup_configuration.0.binary_log_enabled",
"settings.0.backup_configuration.0.enabled",
"settings.0.backup_configuration.0.start_time",
"settings.0.backup_configuration.0.location",
"settings.0.backup_configuration.0.point_in_time_recovery_enabled",
"settings.0.backup_configuration.0.backup_retention_settings",
"settings.0.backup_configuration.0.transaction_log_retention_days",
}
ipConfigurationKeys = []string{
"settings.0.ip_configuration.0.authorized_networks",
"settings.0.ip_configuration.0.ipv4_enabled",
"settings.0.ip_configuration.0.require_ssl",
"settings.0.ip_configuration.0.private_network",
"settings.0.ip_configuration.0.allocated_ip_range",
}
maintenanceWindowKeys = []string{
"settings.0.maintenance_window.0.day",
"settings.0.maintenance_window.0.hour",
"settings.0.maintenance_window.0.update_track",
}
replicaConfigurationKeys = []string{
"replica_configuration.0.ca_certificate",
"replica_configuration.0.client_certificate",
"replica_configuration.0.client_key",
"replica_configuration.0.connect_retry_interval",
"replica_configuration.0.dump_file_path",
"replica_configuration.0.failover_target",
"replica_configuration.0.master_heartbeat_period",
"replica_configuration.0.password",
"replica_configuration.0.ssl_cipher",
"replica_configuration.0.username",
"replica_configuration.0.verify_server_certificate",
}
insightsConfigKeys = []string{
"settings.0.insights_config.0.query_insights_enabled",
"settings.0.insights_config.0.query_string_length",
"settings.0.insights_config.0.record_application_tags",
"settings.0.insights_config.0.record_client_address",
}
)
func resourceSqlDatabaseInstance() *schema.Resource {
return &schema.Resource{
Create: resourceSqlDatabaseInstanceCreate,
Read: resourceSqlDatabaseInstanceRead,
Update: resourceSqlDatabaseInstanceUpdate,
Delete: resourceSqlDatabaseInstanceDelete,
Importer: &schema.ResourceImporter{
State: resourceSqlDatabaseInstanceImport,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
CustomizeDiff: customdiff.All(
customdiff.ForceNewIfChange("settings.0.disk_size", isDiskShrinkage),
privateNetworkCustomizeDiff,
pitrPostgresOnlyCustomizeDiff,
),
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `The region the instance will sit in. Note, Cloud SQL is not available in all regions. A valid region must be provided to use this resource. If a region is not provided in the resource definition, the provider region will be used instead, but this will be an apply-time error for instances if the provider region is not supported with Cloud SQL. If you choose not to provide the region argument for this resource, make sure you understand this.`,
},
"deletion_protection": {
Type: schema.TypeBool,
Default: true,
Optional: true,
Description: `Used to block Terraform from deleting a SQL Instance.`,
},
"settings": {
Type: schema.TypeList,
Optional: true,
Computed: true,
AtLeastOneOf: []string{"settings", "clone"},
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"version": {
Type: schema.TypeInt,
Computed: true,
Description: `Used to make sure changes to the settings block are atomic.`,
},
"tier": {
Type: schema.TypeString,
Required: true,
Description: `The machine type to use. See tiers for more details and supported versions. Postgres supports only shared-core machine types, and custom machine types such as db-custom-2-13312. See the Custom Machine Type Documentation to learn about specifying custom machine types.`,
},
"activation_policy": {
Type: schema.TypeString,
Optional: true,
Default: "ALWAYS",
Description: `This specifies when the instance should be active. Can be either ALWAYS, NEVER or ON_DEMAND.`,
},
"active_directory_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"domain": {
Type: schema.TypeString,
Required: true,
Description: `Domain name of the Active Directory for SQL Server (e.g., mydomain.com).`,
},
},
},
},
"sql_server_audit_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"bucket": {
Type: schema.TypeString,
Required: true,
Description: `The name of the destination bucket (e.g., gs://mybucket).`,
},
"retention_interval": {
Type: schema.TypeString,
Optional: true,
Description: `How long to keep generated audit files. A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s"..`,
},
"upload_interval": {
Type: schema.TypeString,
Optional: true,
Description: `How often to upload generated audit files. A duration in seconds with up to nine fractional digits, terminated by 's'. Example: "3.5s".`,
},
},
},
},
"availability_type": {
Type: schema.TypeString,
Optional: true,
Default: "ZONAL",
ValidateFunc: validation.StringInSlice([]string{"REGIONAL", "ZONAL"}, false),
Description: `The availability type of the Cloud SQL instance, high availability
(REGIONAL) or single zone (ZONAL). For all instances, ensure that
settings.backup_configuration.enabled is set to true.
For MySQL instances, ensure that settings.backup_configuration.binary_log_enabled is set to true.
For Postgres instances, ensure that settings.backup_configuration.point_in_time_recovery_enabled
is set to true.`,
},
"backup_configuration": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"binary_log_enabled": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: backupConfigurationKeys,
Description: `True if binary logging is enabled. If settings.backup_configuration.enabled is false, this must be as well. Can only be used with MySQL.`,
},
"enabled": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: backupConfigurationKeys,
Description: `True if backup configuration is enabled.`,
},
"start_time": {
Type: schema.TypeString,
Optional: true,
// start_time is randomly assigned if not set
Computed: true,
AtLeastOneOf: backupConfigurationKeys,
Description: `HH:MM format time indicating when backup configuration starts.`,
},
"location": {
Type: schema.TypeString,
Optional: true,
AtLeastOneOf: backupConfigurationKeys,
Description: `Location of the backup configuration.`,
},
"point_in_time_recovery_enabled": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: backupConfigurationKeys,
Description: `True if Point-in-time recovery is enabled.`,
},
"transaction_log_retention_days": {
Type: schema.TypeInt,
Computed: true,
Optional: true,
AtLeastOneOf: backupConfigurationKeys,
Description: `The number of days of transaction logs we retain for point in time restore, from 1-7.`,
},
"backup_retention_settings": {
Type: schema.TypeList,
Optional: true,
AtLeastOneOf: backupConfigurationKeys,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"retained_backups": {
Type: schema.TypeInt,
Required: true,
Description: `Number of backups to retain.`,
},
"retention_unit": {
Type: schema.TypeString,
Optional: true,
Default: "COUNT",
Description: `The unit that 'retainedBackups' represents. Defaults to COUNT`,
},
},
},
},
},
},
},
"collation": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: `The name of server instance collation.`,
},
"database_flags": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"value": {
Type: schema.TypeString,
Required: true,
Description: `Value of the flag.`,
},
"name": {
Type: schema.TypeString,
Required: true,
Description: `Name of the flag.`,
},
},
},
},
"disk_autoresize": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: `Enables auto-resizing of the storage size. Defaults to true. Set to false if you want to set disk_size.`,
},
"disk_autoresize_limit": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
Description: `The maximum size, in GB, to which storage capacity can be automatically increased. The default value is 0, which specifies that there is no limit.`,
},
"disk_size": {
Type: schema.TypeInt,
Optional: true,
// Default is likely 10gb, but it is undocumented and may change.
Computed: true,
Description: `The size of data disk, in GB. Size of a running instance cannot be reduced but can be increased. If you want to set this field, set disk_autoresize to false.`,
},
"disk_type": {
Type: schema.TypeString,
Optional: true,
Default: "PD_SSD",
DiffSuppressFunc: caseDiffDashSuppress,
Description: `The type of data disk: PD_SSD or PD_HDD.`,
},
"ip_configuration": {
Type: schema.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"authorized_networks": {
Type: schema.TypeSet,
Optional: true,
Set: schema.HashResource(sqlDatabaseAuthorizedNetWorkSchemaElem),
Elem: sqlDatabaseAuthorizedNetWorkSchemaElem,
AtLeastOneOf: ipConfigurationKeys,
},
"ipv4_enabled": {
Type: schema.TypeBool,
Optional: true,
Default: true,
AtLeastOneOf: ipConfigurationKeys,
Description: `Whether this Cloud SQL instance should be assigned a public IPV4 address. At least ipv4_enabled must be enabled or a private_network must be configured.`,
},
"require_ssl": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: ipConfigurationKeys,
},
"private_network": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: orEmpty(validateRegexp(privateNetworkLinkRegex)),
DiffSuppressFunc: compareSelfLinkRelativePaths,
AtLeastOneOf: ipConfigurationKeys,
Description: `The VPC network from which the Cloud SQL instance is accessible for private IP. For example, projects/myProject/global/networks/default. Specifying a network enables private IP. At least ipv4_enabled must be enabled or a private_network must be configured. This setting can be updated, but it cannot be removed after it is set.`,
},
"allocated_ip_range": {
Type: schema.TypeString,
Optional: true,
AtLeastOneOf: ipConfigurationKeys,
Description: `The name of the allocated ip range for the private ip CloudSQL instance. For example: "google-managed-services-default". If set, the instance ip will be created in the allocated range. The range name must comply with RFC 1035. Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])?.`,
},
},
},
},
"location_preference": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"follow_gae_application": {
Type: schema.TypeString,
Optional: true,
AtLeastOneOf: []string{"settings.0.location_preference.0.follow_gae_application", "settings.0.location_preference.0.zone"},
Description: `A Google App Engine application whose zone to remain in. Must be in the same region as this instance.`,
},
"zone": {
Type: schema.TypeString,
Optional: true,
AtLeastOneOf: []string{"settings.0.location_preference.0.follow_gae_application", "settings.0.location_preference.0.zone"},
Description: `The preferred compute engine zone.`,
},
"secondary_zone": {
Type: schema.TypeString,
Optional: true,
Description: `The preferred Compute Engine zone for the secondary/failover`,
},
},
},
},
"maintenance_window": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"day": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, 7),
AtLeastOneOf: maintenanceWindowKeys,
Description: `Day of week (1-7), starting on Monday`,
},
"hour": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 23),
AtLeastOneOf: maintenanceWindowKeys,
Description: `Hour of day (0-23), ignored if day not set`,
},
"update_track": {
Type: schema.TypeString,
Optional: true,
AtLeastOneOf: maintenanceWindowKeys,
Description: `Receive updates earlier (canary) or later (stable)`,
},
},
},
Description: `Declares a one-hour maintenance window when an Instance can automatically restart to apply updates. The maintenance window is specified in UTC time.`,
},
"pricing_plan": {
Type: schema.TypeString,
Optional: true,
Default: "PER_USE",
Description: `Pricing plan for this instance, can only be PER_USE.`,
},
"user_labels": {
Type: schema.TypeMap,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Description: `A set of key/value user label pairs to assign to the instance.`,
},
"insights_config": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"query_insights_enabled": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: insightsConfigKeys,
Description: `True if Query Insights feature is enabled.`,
},
"query_string_length": {
Type: schema.TypeInt,
Optional: true,
Default: 1024,
ValidateFunc: validation.IntBetween(256, 4500),
AtLeastOneOf: insightsConfigKeys,
Description: `Maximum query length stored in bytes. Between 256 and 4500. Default to 1024.`,
},
"record_application_tags": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: insightsConfigKeys,
Description: `True if Query Insights will record application tags from query when enabled.`,
},
"record_client_address": {
Type: schema.TypeBool,
Optional: true,
AtLeastOneOf: insightsConfigKeys,
Description: `True if Query Insights will record client address when enabled.`,
},
},
},
Description: `Configuration of Query Insights.`,
},
"password_validation_policy": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"min_length": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 2147483647),
Description: `Minimum number of characters allowed.`,
},
"complexity": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"COMPLEXITY_DEFAULT", "COMPLEXITY_UNSPECIFIED"}, false),
Description: `Password complexity.`,
},
"reuse_interval": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(0, 2147483647),
Description: `Number of previous passwords that cannot be reused.`,
},
"disallow_username_substring": {
Type: schema.TypeBool,
Optional: true,
Description: `Disallow username as a part of the password.`,
},
"password_change_interval": {
Type: schema.TypeString,
Optional: true,
Description: `Minimum interval after which the password can be changed. This flag is only supported for PostgresSQL.`,
},
"enable_password_policy": {
Type: schema.TypeBool,
Required: true,
Description: `Whether the password policy is enabled or not.`,
},
},
},
},
},
},
Description: `The settings to use for the database. The configuration is detailed below.`,
},
"connection_name": {
Type: schema.TypeString,
Computed: true,
Description: `The connection name of the instance to be used in connection strings. For example, when connecting with Cloud SQL Proxy.`,
},
"database_version": {
Type: schema.TypeString,
Required: true,
Description: `The MySQL, PostgreSQL or SQL Server (beta) version to use. Supported values include MYSQL_5_6, MYSQL_5_7, MYSQL_8_0, POSTGRES_9_6, POSTGRES_10, POSTGRES_11, POSTGRES_12, POSTGRES_13, POSTGRES_14, SQLSERVER_2017_STANDARD, SQLSERVER_2017_ENTERPRISE, SQLSERVER_2017_EXPRESS, SQLSERVER_2017_WEB. Database Version Policies includes an up-to-date reference of supported versions.`,
},
"encryption_key_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"root_password": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Sensitive: true,
Description: `Initial root password. Required for MS SQL Server.`,
},
"ip_address": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ip_address": {
Type: schema.TypeString,
Computed: true,
},
"type": {
Type: schema.TypeString,
Computed: true,
},
"time_to_retire": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
"first_ip_address": {
Type: schema.TypeString,
Computed: true,
Description: `The first IPv4 address of any type assigned. This is to support accessing the first address in the list in a terraform output when the resource is configured with a count.`,
},
"public_ip_address": {
Type: schema.TypeString,
Computed: true,
Description: `IPv4 address assigned. This is a workaround for an issue fixed in Terraform 0.12 but also provides a convenient way to access an IP of a specific type without performing filtering in a Terraform config.`,
},
"private_ip_address": {
Type: schema.TypeString,
Computed: true,
Description: `IPv4 address assigned. This is a workaround for an issue fixed in Terraform 0.12 but also provides a convenient way to access an IP of a specific type without performing filtering in a Terraform config.`,
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `The name of the instance. If the name is left blank, Terraform will randomly generate one when the instance is first created. This is done because after a name is used, it cannot be reused for up to one week.`,
},
"master_instance_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `The name of the instance that will act as the master in the replication setup. Note, this requires the master to have binary_log_enabled set, as well as existing backups.`,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `The ID of the project in which the resource belongs. If it is not provided, the provider project is used.`,
},
"replica_configuration": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
// Returned from API on all replicas
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"ca_certificate": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
AtLeastOneOf: replicaConfigurationKeys,
Description: `PEM representation of the trusted CA's x509 certificate.`,
},
"client_certificate": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
AtLeastOneOf: replicaConfigurationKeys,
Description: `PEM representation of the replica's x509 certificate.`,
},
"client_key": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
AtLeastOneOf: replicaConfigurationKeys,
Description: `PEM representation of the replica's private key. The corresponding public key in encoded in the client_certificate.`,
},
"connect_retry_interval": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
AtLeastOneOf: replicaConfigurationKeys,
Description: `The number of seconds between connect retries.`,
},
"dump_file_path": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
AtLeastOneOf: replicaConfigurationKeys,
Description: `Path to a SQL file in Google Cloud Storage from which replica instances are created. Format is gs://bucket/filename.`,
},
"failover_target": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
AtLeastOneOf: replicaConfigurationKeys,
Description: `Specifies if the replica is the failover target. If the field is set to true the replica will be designated as a failover replica. If the master instance fails, the replica instance will be promoted as the new master instance.`,
},
"master_heartbeat_period": {
Type: schema.TypeInt,
Optional: true,
ForceNew: true,
AtLeastOneOf: replicaConfigurationKeys,
Description: `Time in ms between replication heartbeats.`,
},
"password": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Sensitive: true,
AtLeastOneOf: replicaConfigurationKeys,
Description: `Password for the replication connection.`,
},
"ssl_cipher": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
AtLeastOneOf: replicaConfigurationKeys,
Description: `Permissible ciphers for use in SSL encryption.`,
},
"username": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
AtLeastOneOf: replicaConfigurationKeys,
Description: `Username for replication connection.`,
},
"verify_server_certificate": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
AtLeastOneOf: replicaConfigurationKeys,
Description: `True if the master's common name value is checked during the SSL handshake.`,
},
},
},
Description: `The configuration for replication.`,
},
"server_ca_cert": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cert": {
Type: schema.TypeString,
Computed: true,
Description: `The CA Certificate used to connect to the SQL Instance via SSL.`,
},
"common_name": {
Type: schema.TypeString,
Computed: true,
Description: `The CN valid for the CA Cert.`,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
Description: `Creation time of the CA Cert.`,
},
"expiration_time": {
Type: schema.TypeString,
Computed: true,
Description: `Expiration time of the CA Cert.`,
},
"sha1_fingerprint": {
Type: schema.TypeString,
Computed: true,
Description: `SHA Fingerprint of the CA Cert.`,
},
},
},
},
"service_account_email_address": {
Type: schema.TypeString,
Computed: true,
Description: `The service account email address assigned to the instance.`,
},
"self_link": {
Type: schema.TypeString,
Computed: true,
Description: `The URI of the created resource.`,
},
"restore_backup_context": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"backup_run_id": {
Type: schema.TypeInt,
Required: true,
Description: `The ID of the backup run to restore from.`,
},
"instance_id": {
Type: schema.TypeString,
Optional: true,
Description: `The ID of the instance that the backup was taken from.`,
},
"project": {
Type: schema.TypeString,
Optional: true,
Description: `The full project ID of the source instance.`,
},
},
},
},
"clone": {
Type: schema.TypeList,
Optional: true,
Computed: false,
AtLeastOneOf: []string{"settings", "clone"},
Description: `Configuration for creating a new instance as a clone of another instance.`,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"source_instance_name": {
Type: schema.TypeString,
Required: true,
Description: `The name of the instance from which the point in time should be restored.`,
},
"point_in_time": {
Type: schema.TypeString,
Optional: true,
DiffSuppressFunc: timestampDiffSuppress(time.RFC3339Nano),
Description: `The timestamp of the point in time that should be restored.`,
},
"allocated_ip_range": {
Type: schema.TypeString,
Optional: true,
Description: `The name of the allocated ip range for the private ip CloudSQL instance. For example: "google-managed-services-default". If set, the cloned instance ip will be created in the allocated range. The range name must comply with [RFC 1035](https://tools.ietf.org/html/rfc1035). Specifically, the name must be 1-63 characters long and match the regular expression [a-z]([-a-z0-9]*[a-z0-9])?.`,
},
},
},
},
},
UseJSONNumber: true,
}
}
// Makes private_network ForceNew if it is changing from set to nil. The API returns an error
// if this change is attempted in-place.
func privateNetworkCustomizeDiff(_ context.Context, d *schema.ResourceDiff, meta interface{}) error {
old, new := d.GetChange("settings.0.ip_configuration.0.private_network")
if old != "" && new == "" {
if err := d.ForceNew("settings.0.ip_configuration.0.private_network"); err != nil {
return err
}
}
return nil
}
// Point in time recovery for MySQL database instances needs binary_log_enabled set to true and
// not point_in_time_recovery_enabled, which is confusing to users. This checks for
// point_in_time_recovery_enabled being set to a non-PostgreSQL database instance and suggests
// binary_log_enabled.
func pitrPostgresOnlyCustomizeDiff(_ context.Context, diff *schema.ResourceDiff, v interface{}) error {
pitr := diff.Get("settings.0.backup_configuration.0.point_in_time_recovery_enabled").(bool)
dbVersion := diff.Get("database_version").(string)
if pitr && !strings.Contains(dbVersion, "POSTGRES") {
return fmt.Errorf("point_in_time_recovery_enabled is only available for Postgres. You may want to consider using binary_log_enabled instead.")
}
return nil
}
func resourceSqlDatabaseInstanceCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
userAgent, err := generateUserAgentString(d, config.userAgent)
if err != nil {
return err
}
project, err := getProject(d, config)
if err != nil {
return err
}
region, err := getRegion(d, config)
if err != nil {
return err
}
var name string
if v, ok := d.GetOk("name"); ok {
name = v.(string)
} else {
name = resource.UniqueId()
}
if err := d.Set("name", name); err != nil {
return fmt.Errorf("Error setting name: %s", err)
}
// SQL Instances that fail to create are expensive- see https://github.com/hashicorp/terraform-provider-google/issues/7154
// We can fail fast to stop instance names from getting reserved.
network := d.Get("settings.0.ip_configuration.0.private_network").(string)
if network != "" {
err = sqlDatabaseInstanceServiceNetworkPrecheck(d, config, userAgent, network)
if err != nil {
return err
}
}
instance := &sqladmin.DatabaseInstance{
Name: name,
Region: region,
DatabaseVersion: d.Get("database_version").(string),
MasterInstanceName: d.Get("master_instance_name").(string),
ReplicaConfiguration: expandReplicaConfiguration(d.Get("replica_configuration").([]interface{})),
}
cloneContext, cloneSource := expandCloneContext(d.Get("clone").([]interface{}))
s, ok := d.GetOk("settings")
desiredSettings := expandSqlDatabaseInstanceSettings(s.([]interface{}))
if ok {
instance.Settings = desiredSettings
}
instance.RootPassword = d.Get("root_password").(string)
// Modifying a replica during Create can cause problems if the master is
// modified at the same time. Lock the master until we're done in order
// to prevent that.
if !sqlDatabaseIsMaster(d) {
mutexKV.Lock(instanceMutexKey(project, instance.MasterInstanceName))
defer mutexKV.Unlock(instanceMutexKey(project, instance.MasterInstanceName))
}
if k, ok := d.GetOk("encryption_key_name"); ok {
instance.DiskEncryptionConfiguration = &sqladmin.DiskEncryptionConfiguration{
KmsKeyName: k.(string),
}
}
var patchData *sqladmin.DatabaseInstance
// BinaryLogging can be enabled on replica instances but only after creation.
if instance.MasterInstanceName != "" && instance.Settings != nil && instance.Settings.BackupConfiguration != nil {
bc := instance.Settings.BackupConfiguration
instance.Settings.BackupConfiguration = nil
if bc.BinaryLogEnabled {
patchData = &sqladmin.DatabaseInstance{Settings: &sqladmin.Settings{BackupConfiguration: bc}}
}
}
var op *sqladmin.Operation
err = retryTimeDuration(func() (operr error) {
if cloneContext != nil {
cloneContext.DestinationInstanceName = name
clodeReq := sqladmin.InstancesCloneRequest{CloneContext: cloneContext}
op, operr = config.NewSqlAdminClient(userAgent).Instances.Clone(project, cloneSource, &clodeReq).Do()
} else {
op, operr = config.NewSqlAdminClient(userAgent).Instances.Insert(project, instance).Do()
}
return operr
}, d.Timeout(schema.TimeoutCreate), isSqlOperationInProgressError)
if err != nil {
return fmt.Errorf("Error, failed to create instance %s: %s", instance.Name, err)
}
id, err := replaceVars(d, config, "projects/{{project}}/instances/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
err = sqlAdminOperationWaitTime(config, op, project, "Create Instance", userAgent, d.Timeout(schema.TimeoutCreate))
if err != nil {
d.SetId("")
return err
}
// patch any fields that need to be sent postcreation
if patchData != nil {
err = retryTimeDuration(func() (rerr error) {
op, rerr = config.NewSqlAdminClient(userAgent).Instances.Patch(project, instance.Name, patchData).Do()
return rerr
}, d.Timeout(schema.TimeoutUpdate), isSqlOperationInProgressError)
if err != nil {
return fmt.Errorf("Error, failed to update instance settings for %s: %s", instance.Name, err)
}
err = sqlAdminOperationWaitTime(config, op, project, "Patch Instance", userAgent, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
}
err = resourceSqlDatabaseInstanceRead(d, meta)
if err != nil {
return err
}
// Refresh settings from read as they may have defaulted from the API
s = d.Get("settings")
// If we've created an instance as a clone, we need to update it to set any user defined settings
if len(s.([]interface{})) != 0 && cloneContext != nil && desiredSettings != nil {
instanceUpdate := &sqladmin.DatabaseInstance{
Settings: desiredSettings,
}
_settings := s.([]interface{})[0].(map[string]interface{})
instanceUpdate.Settings.SettingsVersion = int64(_settings["version"].(int))
var op *sqladmin.Operation
err = retryTimeDuration(func() (rerr error) {
op, rerr = config.NewSqlAdminClient(userAgent).Instances.Update(project, name, instanceUpdate).Do()
return rerr
}, d.Timeout(schema.TimeoutUpdate), isSqlOperationInProgressError)
if err != nil {
return fmt.Errorf("Error, failed to update instance settings for %s: %s", instance.Name, err)
}
err = sqlAdminOperationWaitTime(config, op, project, "Update Instance", userAgent, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
// Refresh the state of the instance after updating the settings
err = resourceSqlDatabaseInstanceRead(d, meta)
if err != nil {
return err
}
}
// If a default root user was created with a wildcard ('%') hostname, delete it.
// Users in a replica instance are inherited from the master instance and should be left alone.
if sqlDatabaseIsMaster(d) {
var users *sqladmin.UsersListResponse
err = retryTimeDuration(func() error {
users, err = config.NewSqlAdminClient(userAgent).Users.List(project, instance.Name).Do()
return err
}, d.Timeout(schema.TimeoutRead), isSqlOperationInProgressError)
if err != nil {
return fmt.Errorf("Error, attempting to list users associated with instance %s: %s", instance.Name, err)
}
for _, u := range users.Items {
if u.Name == "root" && u.Host == "%" {
err = retry(func() error {
op, err = config.NewSqlAdminClient(userAgent).Users.Delete(project, instance.Name).Host(u.Host).Name(u.Name).Do()
if err == nil {
err = sqlAdminOperationWaitTime(config, op, project, "Delete default root User", userAgent, d.Timeout(schema.TimeoutCreate))
}
return err
})
if err != nil {