forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgresql_server_resource.go
1132 lines (962 loc) · 38.8 KB
/
postgresql_server_resource.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
package postgres
import (
"context"
"fmt"
"log"
"strconv"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/postgresql/mgmt/2020-01-01/postgresql"
"github.com/Azure/go-autorest/autorest/date"
"github.com/kevinklinger/terraform-provider-azurerm/v2/helpers/azure"
"github.com/kevinklinger/terraform-provider-azurerm/v2/helpers/tf"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/clients"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/locks"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/services/postgres/parse"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/services/postgres/validate"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tags"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tf/pluginsdk"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tf/suppress"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/tf/validation"
"github.com/kevinklinger/terraform-provider-azurerm/v2/internal/timeouts"
"github.com/kevinklinger/terraform-provider-azurerm/v2/utils"
)
const (
postgreSQLServerResourceName = "azurerm_postgresql_server"
)
var skuList = []string{
"B_Gen4_1",
"B_Gen4_2",
"B_Gen5_1",
"B_Gen5_2",
"GP_Gen4_2",
"GP_Gen4_4",
"GP_Gen4_8",
"GP_Gen4_16",
"GP_Gen4_32",
"GP_Gen5_2",
"GP_Gen5_4",
"GP_Gen5_8",
"GP_Gen5_16",
"GP_Gen5_32",
"GP_Gen5_64",
"MO_Gen5_2",
"MO_Gen5_4",
"MO_Gen5_8",
"MO_Gen5_16",
"MO_Gen5_32",
}
func resourcePostgreSQLServer() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourcePostgreSQLServerCreate,
Read: resourcePostgreSQLServerRead,
Update: resourcePostgreSQLServerUpdate,
Delete: resourcePostgreSQLServerDelete,
Importer: pluginsdk.ImporterValidatingResourceIdThen(func(id string) error {
_, err := parse.ServerID(id)
return err
}, func(ctx context.Context, d *pluginsdk.ResourceData, meta interface{}) ([]*pluginsdk.ResourceData, error) {
client := meta.(*clients.Client).Postgres.ServersClient
id, err := parse.ServerID(d.Id())
if err != nil {
return []*pluginsdk.ResourceData{d}, err
}
resp, err := client.Get(ctx, id.ResourceGroup, id.Name)
if err != nil {
return []*pluginsdk.ResourceData{d}, fmt.Errorf("reading PostgreSQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
d.Set("create_mode", "Default")
if resp.ReplicationRole != nil && *resp.ReplicationRole != "Master" && *resp.ReplicationRole != "None" {
d.Set("create_mode", resp.ReplicationRole)
sourceServerId, err := parse.ServerID(*resp.MasterServerID)
if err != nil {
return []*pluginsdk.ResourceData{d}, fmt.Errorf("parsing Postgres Main Server ID : %v", err)
}
d.Set("creation_source_server_id", sourceServerId.ID())
}
return []*pluginsdk.ResourceData{d}, nil
}),
Timeouts: &pluginsdk.ResourceTimeout{
Create: pluginsdk.DefaultTimeout(60 * time.Minute),
Read: pluginsdk.DefaultTimeout(5 * time.Minute),
Update: pluginsdk.DefaultTimeout(60 * time.Minute),
Delete: pluginsdk.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*pluginsdk.Schema{
"name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.ServerName,
},
"location": azure.SchemaLocation(),
"resource_group_name": azure.SchemaResourceGroupName(),
"sku_name": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(skuList, false),
},
"version": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
string(postgresql.NineFullStopFive),
string(postgresql.NineFullStopSix),
string(postgresql.OneOne),
string(postgresql.OneZero),
string(postgresql.OneZeroFullStopZero),
}, true),
DiffSuppressFunc: suppress.CaseDifference, // TODO: make case sensitive in 3.0
},
"storage_profile": {
Type: pluginsdk.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Deprecated: "all storage_profile properties have been move to the top level. This block will be removed in version 3.0 of the provider.",
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"storage_mb": {
Type: pluginsdk.TypeInt,
Optional: true,
ConflictsWith: []string{"storage_mb"},
Deprecated: "this has been moved to the top level and will be removed in version 3.0 of the provider.",
ValidateFunc: validation.All(
validation.IntBetween(5120, 4194304),
validation.IntDivisibleBy(1024),
),
},
"backup_retention_days": {
Type: pluginsdk.TypeInt,
Optional: true,
Default: 7,
ConflictsWith: []string{"backup_retention_days"},
Deprecated: "this has been moved to the top level and will be removed in version 3.0 of the provider.",
ValidateFunc: validation.IntBetween(7, 35),
},
"auto_grow": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true,
ConflictsWith: []string{"auto_grow_enabled"},
Deprecated: "this has been moved to the top level and will be removed in version 3.0 of the provider.",
ValidateFunc: validation.StringInSlice([]string{
string(postgresql.StorageAutogrowEnabled),
string(postgresql.StorageAutogrowDisabled),
}, false),
},
"geo_redundant_backup": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"geo_redundant_backup_enabled"},
Deprecated: "this has been moved to the top level and will be removed in version 3.0 of the provider.",
ValidateFunc: validation.StringInSlice([]string{
"Enabled",
"Disabled",
}, true),
DiffSuppressFunc: suppress.CaseDifference,
},
},
},
},
"administrator_login": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validation.All(validation.StringIsNotWhiteSpace, validate.AdminUsernames),
},
"administrator_login_password": {
Type: pluginsdk.TypeString,
Optional: true,
Sensitive: true,
},
"auto_grow_enabled": {
Type: pluginsdk.TypeBool,
Optional: true,
Computed: true, // TODO: remove in 3.0 and default to true
ConflictsWith: []string{"storage_profile", "storage_profile.0.auto_grow"},
},
"backup_retention_days": {
Type: pluginsdk.TypeInt,
Optional: true,
Computed: true,
ConflictsWith: []string{"storage_profile", "storage_profile.0.backup_retention_days"},
ValidateFunc: validation.IntBetween(7, 35),
},
"geo_redundant_backup_enabled": {
Type: pluginsdk.TypeBool,
Optional: true,
ForceNew: true,
Computed: true, // TODO: remove in 2.0 and default to false
ConflictsWith: []string{"storage_profile", "storage_profile.0.geo_redundant_backup"},
},
"create_mode": {
Type: pluginsdk.TypeString,
Optional: true,
Default: string(postgresql.CreateModeDefault),
ValidateFunc: validation.StringInSlice([]string{
string(postgresql.CreateModeDefault),
string(postgresql.CreateModeGeoRestore),
string(postgresql.CreateModePointInTimeRestore),
string(postgresql.CreateModeReplica),
}, false),
},
"creation_source_server_id": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: validate.ServerID,
},
"identity": {
Type: pluginsdk.TypeList,
Optional: true,
MaxItems: 1,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"type": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(postgresql.SystemAssigned),
}, false),
},
"principal_id": {
Type: pluginsdk.TypeString,
Computed: true,
},
"tenant_id": {
Type: pluginsdk.TypeString,
Computed: true,
},
},
},
},
"infrastructure_encryption_enabled": {
Type: pluginsdk.TypeBool,
Optional: true,
ForceNew: true,
},
"public_network_access_enabled": {
Type: pluginsdk.TypeBool,
Optional: true,
Default: true,
},
"restore_point_in_time": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: validation.IsRFC3339Time,
},
"storage_mb": {
Type: pluginsdk.TypeInt,
Optional: true,
Computed: true,
ConflictsWith: []string{"storage_profile", "storage_profile.0.storage_mb"},
ValidateFunc: validation.All(
validation.IntBetween(5120, 16777216),
validation.IntDivisibleBy(1024),
),
},
"ssl_minimal_tls_version_enforced": {
Type: pluginsdk.TypeString,
Optional: true,
Default: string(postgresql.TLSEnforcementDisabled),
ValidateFunc: validation.StringInSlice([]string{
string(postgresql.TLSEnforcementDisabled),
string(postgresql.TLS10),
string(postgresql.TLS11),
string(postgresql.TLS12),
}, false),
},
"ssl_enforcement_enabled": {
Type: pluginsdk.TypeBool,
Optional: true, // required in 3.0
ExactlyOneOf: []string{"ssl_enforcement", "ssl_enforcement_enabled"},
},
"ssl_enforcement": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true,
Deprecated: "this has been renamed to the boolean `ssl_enforcement_enabled` and will be removed in version 3.0 of the provider.",
ExactlyOneOf: []string{"ssl_enforcement", "ssl_enforcement_enabled"},
ValidateFunc: validation.StringInSlice([]string{
string(postgresql.SslEnforcementEnumDisabled),
string(postgresql.SslEnforcementEnumEnabled),
}, true),
DiffSuppressFunc: suppress.CaseDifference,
},
"threat_detection_policy": {
Type: pluginsdk.TypeList,
Optional: true,
MaxItems: 1,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"enabled": {
Type: pluginsdk.TypeBool,
Optional: true,
AtLeastOneOf: []string{"threat_detection_policy.0.enabled", "threat_detection_policy.0.disabled_alerts", "threat_detection_policy.0.email_account_admins",
"threat_detection_policy.0.email_addresses", "threat_detection_policy.0.retention_days", "threat_detection_policy.0.storage_account_access_key",
"threat_detection_policy.0.storage_endpoint",
},
},
"disabled_alerts": {
Type: pluginsdk.TypeSet,
Optional: true,
Set: pluginsdk.HashString,
Elem: &pluginsdk.Schema{
Type: pluginsdk.TypeString,
ValidateFunc: validation.StringInSlice([]string{
"Sql_Injection",
"Sql_Injection_Vulnerability",
"Access_Anomaly",
"Data_Exfiltration",
"Unsafe_Action",
}, false),
},
AtLeastOneOf: []string{"threat_detection_policy.0.enabled", "threat_detection_policy.0.disabled_alerts", "threat_detection_policy.0.email_account_admins",
"threat_detection_policy.0.email_addresses", "threat_detection_policy.0.retention_days", "threat_detection_policy.0.storage_account_access_key",
"threat_detection_policy.0.storage_endpoint",
},
},
"email_account_admins": {
Type: pluginsdk.TypeBool,
Optional: true,
AtLeastOneOf: []string{"threat_detection_policy.0.enabled", "threat_detection_policy.0.disabled_alerts", "threat_detection_policy.0.email_account_admins",
"threat_detection_policy.0.email_addresses", "threat_detection_policy.0.retention_days", "threat_detection_policy.0.storage_account_access_key",
"threat_detection_policy.0.storage_endpoint",
},
},
"email_addresses": {
Type: pluginsdk.TypeSet,
Optional: true,
Elem: &pluginsdk.Schema{
Type: pluginsdk.TypeString,
// todo email validation in code
},
Set: pluginsdk.HashString,
AtLeastOneOf: []string{"threat_detection_policy.0.enabled", "threat_detection_policy.0.disabled_alerts", "threat_detection_policy.0.email_account_admins",
"threat_detection_policy.0.email_addresses", "threat_detection_policy.0.retention_days", "threat_detection_policy.0.storage_account_access_key",
"threat_detection_policy.0.storage_endpoint",
},
},
"retention_days": {
Type: pluginsdk.TypeInt,
Optional: true,
ValidateFunc: validation.IntAtLeast(0),
AtLeastOneOf: []string{"threat_detection_policy.0.enabled", "threat_detection_policy.0.disabled_alerts", "threat_detection_policy.0.email_account_admins",
"threat_detection_policy.0.email_addresses", "threat_detection_policy.0.retention_days", "threat_detection_policy.0.storage_account_access_key",
"threat_detection_policy.0.storage_endpoint",
},
},
"storage_account_access_key": {
Type: pluginsdk.TypeString,
Optional: true,
Sensitive: true,
ValidateFunc: validation.StringIsNotEmpty,
AtLeastOneOf: []string{"threat_detection_policy.0.enabled", "threat_detection_policy.0.disabled_alerts", "threat_detection_policy.0.email_account_admins",
"threat_detection_policy.0.email_addresses", "threat_detection_policy.0.retention_days", "threat_detection_policy.0.storage_account_access_key",
"threat_detection_policy.0.storage_endpoint",
},
},
"storage_endpoint": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: validation.StringIsNotEmpty,
AtLeastOneOf: []string{"threat_detection_policy.0.enabled", "threat_detection_policy.0.disabled_alerts", "threat_detection_policy.0.email_account_admins",
"threat_detection_policy.0.email_addresses", "threat_detection_policy.0.retention_days", "threat_detection_policy.0.storage_account_access_key",
"threat_detection_policy.0.storage_endpoint",
},
},
},
},
},
"fqdn": {
Type: pluginsdk.TypeString,
Computed: true,
},
"tags": tags.Schema(),
},
CustomizeDiff: pluginsdk.CustomDiffWithAll(
pluginsdk.ForceNewIfChange("sku_name", func(ctx context.Context, old, new, meta interface{}) bool {
oldTier := strings.Split(old.(string), "_")
newTier := strings.Split(new.(string), "_")
// If the sku tier was not changed, we don't need ForceNew
if oldTier[0] == newTier[0] {
return false
}
// Basic tier could not be changed to other tiers
if oldTier[0] == "B" || newTier[0] == "B" {
return true
}
return false
}),
),
}
}
func resourcePostgreSQLServerCreate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Postgres.ServersClient
securityClient := meta.(*clients.Client).Postgres.ServerSecurityAlertPoliciesClient
ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d)
defer cancel()
log.Printf("[INFO] preparing arguments for AzureRM PostgreSQL Server creation.")
name := d.Get("name").(string)
location := azure.NormalizeLocation(d.Get("location").(string))
resourceGroup := d.Get("resource_group_name").(string)
existing, err := client.Get(ctx, resourceGroup, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("checking for presence of existing PostgreSQL Server %q (Resource Group %q): %+v", name, resourceGroup, err)
}
}
if existing.ID != nil && *existing.ID != "" {
return tf.ImportAsExistsError("azurerm_postgresql_server", *existing.ID)
}
mode := postgresql.CreateMode(d.Get("create_mode").(string))
tlsMin := postgresql.MinimalTLSVersionEnum(d.Get("ssl_minimal_tls_version_enforced").(string))
source := d.Get("creation_source_server_id").(string)
version := postgresql.ServerVersion(d.Get("version").(string))
sku, err := expandServerSkuName(d.Get("sku_name").(string))
if err != nil {
return fmt.Errorf("expanding `sku_name` for PostgreSQL Server %s (Resource Group %q): %v", name, resourceGroup, err)
}
infraEncrypt := postgresql.InfrastructureEncryptionEnabled
if v := d.Get("infrastructure_encryption_enabled"); !v.(bool) {
infraEncrypt = postgresql.InfrastructureEncryptionDisabled
}
publicAccess := postgresql.PublicNetworkAccessEnumEnabled
if v := d.Get("public_network_access_enabled"); !v.(bool) {
publicAccess = postgresql.PublicNetworkAccessEnumDisabled
}
ssl := postgresql.SslEnforcementEnumEnabled
if v := d.Get("ssl_enforcement_enabled"); !v.(bool) {
ssl = postgresql.SslEnforcementEnumDisabled
}
storage := expandPostgreSQLStorageProfile(d)
var props postgresql.BasicServerPropertiesForCreate
switch mode {
case postgresql.CreateModeDefault:
admin := d.Get("administrator_login").(string)
pass := d.Get("administrator_login_password").(string)
if admin == "" {
return fmt.Errorf("`administrator_login` must not be empty when `create_mode` is `default`")
}
if pass == "" {
return fmt.Errorf("`administrator_login_password` must not be empty when `create_mode` is `default`")
}
if _, ok := d.GetOk("restore_point_in_time"); ok {
return fmt.Errorf("`restore_point_in_time` cannot be set when `create_mode` is `default`")
}
// check admin
props = &postgresql.ServerPropertiesForDefaultCreate{
AdministratorLogin: &admin,
AdministratorLoginPassword: &pass,
CreateMode: mode,
InfrastructureEncryption: infraEncrypt,
PublicNetworkAccess: publicAccess,
MinimalTLSVersion: tlsMin,
SslEnforcement: ssl,
StorageProfile: storage,
Version: version,
}
case postgresql.CreateModePointInTimeRestore:
v, ok := d.GetOk("restore_point_in_time")
if !ok || v.(string) == "" {
return fmt.Errorf("restore_point_in_time must be set when create_mode is PointInTimeRestore")
}
time, _ := time.Parse(time.RFC3339, v.(string)) // should be validated by the schema
props = &postgresql.ServerPropertiesForRestore{
CreateMode: mode,
SourceServerID: &source,
RestorePointInTime: &date.Time{
Time: time,
},
InfrastructureEncryption: infraEncrypt,
PublicNetworkAccess: publicAccess,
MinimalTLSVersion: tlsMin,
SslEnforcement: ssl,
StorageProfile: storage,
Version: version,
}
case postgresql.CreateModeGeoRestore:
props = &postgresql.ServerPropertiesForGeoRestore{
CreateMode: mode,
SourceServerID: &source,
InfrastructureEncryption: infraEncrypt,
PublicNetworkAccess: publicAccess,
MinimalTLSVersion: tlsMin,
SslEnforcement: ssl,
StorageProfile: storage,
Version: version,
}
case postgresql.CreateModeReplica:
props = &postgresql.ServerPropertiesForReplica{
CreateMode: mode,
SourceServerID: &source,
InfrastructureEncryption: infraEncrypt,
PublicNetworkAccess: publicAccess,
MinimalTLSVersion: tlsMin,
SslEnforcement: ssl,
Version: version,
}
}
server := postgresql.ServerForCreate{
Identity: expandServerIdentity(d.Get("identity").([]interface{})),
Location: &location,
Properties: props,
Sku: sku,
Tags: tags.Expand(d.Get("tags").(map[string]interface{})),
}
future, err := client.Create(ctx, resourceGroup, name, server)
if err != nil {
return fmt.Errorf("creating PostgreSQL Server %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for creation of PostgreSQL Server %q (Resource Group %q): %+v", name, resourceGroup, err)
}
log.Printf("[DEBUG] Waiting for PostgreSQL Server %q (Resource Group %q) to become available", name, resourceGroup)
stateConf := &pluginsdk.StateChangeConf{
Pending: []string{string(postgresql.ServerStateInaccessible)},
Target: []string{string(postgresql.ServerStateReady)},
Refresh: postgreSqlStateRefreshFunc(ctx, client, resourceGroup, name),
MinTimeout: 15 * time.Second,
Timeout: d.Timeout(pluginsdk.TimeoutCreate),
}
if _, err = stateConf.WaitForStateContext(ctx); err != nil {
return fmt.Errorf("waiting for PostgreSQL Server %q (Resource Group %q)to become available: %+v", name, resourceGroup, err)
}
read, err := client.Get(ctx, resourceGroup, name)
if err != nil {
return fmt.Errorf("retrieving PostgreSQL Server %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if read.ID == nil {
return fmt.Errorf("Cannot read PostgreSQL Server %q (Resource Group %q) ID", name, resourceGroup)
}
d.SetId(*read.ID)
if v, ok := d.GetOk("threat_detection_policy"); ok {
alert := expandSecurityAlertPolicy(v)
if alert != nil {
future, err := securityClient.CreateOrUpdate(ctx, resourceGroup, name, *alert)
if err != nil {
return fmt.Errorf("updataing postgres server security alert policy: %v", err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for creation/update of postgrest server security alert policy (server %q, resource group %q): %+v", name, resourceGroup, err)
}
}
}
// Issue tracking the REST API update failure: https://github.com/Azure/azure-rest-api-specs/issues/14117
if mode == postgresql.CreateModeReplica {
log.Printf("[INFO] changing `public_network_access_enabled` for AzureRM PostgreSQL Server %q (Resource Group %q)", name, resourceGroup)
properties := postgresql.ServerUpdateParameters{
ServerUpdateParametersProperties: &postgresql.ServerUpdateParametersProperties{
PublicNetworkAccess: publicAccess,
},
}
future, err := client.Update(ctx, resourceGroup, name, properties)
if err != nil {
return fmt.Errorf("updating PostgreSQL Server %q (Resource Group %q): %+v", name, resourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for update of PostgreSQL Server %q (Resource Group %q): %+v", name, resourceGroup, err)
}
}
return resourcePostgreSQLServerRead(d, meta)
}
func resourcePostgreSQLServerUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Postgres.ServersClient
securityClient := meta.(*clients.Client).Postgres.ServerSecurityAlertPoliciesClient
replicasClient := meta.(*clients.Client).Postgres.ReplicasClient
ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
// TODO: support for Delta updates
log.Printf("[INFO] preparing arguments for AzureRM PostgreSQL Server update.")
id, err := parse.ServerID(d.Id())
if err != nil {
return fmt.Errorf("parsing Postgres Server ID : %v", err)
}
// Locks for upscaling of replicas
mode := postgresql.CreateMode(d.Get("create_mode").(string))
primaryID := id.String()
if mode == postgresql.CreateModeReplica {
primaryID = d.Get("creation_source_server_id").(string)
// Wait for possible restarts triggered by scaling primary (and its replicas)
log.Printf("[DEBUG] Waiting for PostgreSQL Server %q (Resource Group %q) to become available", id.Name, id.ResourceGroup)
stateConf := &pluginsdk.StateChangeConf{
Pending: []string{string(postgresql.ServerStateInaccessible), "Restarting"},
Target: []string{string(postgresql.ServerStateReady)},
Refresh: postgreSqlStateRefreshFunc(ctx, client, id.ResourceGroup, id.Name),
MinTimeout: 15 * time.Second,
Timeout: d.Timeout(pluginsdk.TimeoutCreate),
}
if _, err = stateConf.WaitForStateContext(ctx); err != nil {
return fmt.Errorf("waiting for PostgreSQL Server %q (Resource Group %q)to become available: %+v", id.Name, id.ResourceGroup, err)
}
}
locks.ByID(primaryID)
defer locks.UnlockByID(primaryID)
sku, err := expandServerSkuName(d.Get("sku_name").(string))
if err != nil {
return fmt.Errorf("expanding `sku_name` for PostgreSQL Server %s (Resource Group %q): %v", id.Name, id.ResourceGroup, err)
}
if d.HasChange("sku_name") && mode != postgresql.CreateModeReplica {
oldRaw, newRaw := d.GetChange("sku_name")
old := oldRaw.(string)
new := newRaw.(string)
if indexOfSku(old) < indexOfSku(new) {
listReplicas, err := replicasClient.ListByServer(ctx, id.ResourceGroup, id.Name)
if err != nil {
return fmt.Errorf("listing replicas for PostgreSQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
propertiesReplica := postgresql.ServerUpdateParameters{
Sku: sku,
}
for _, replica := range *listReplicas.Value {
replicaId, err := parse.ServerID(*replica.ID)
if err != nil {
return fmt.Errorf("parsing Postgres Server Replica ID : %v", err)
}
future, err := client.Update(ctx, replicaId.ResourceGroup, replicaId.Name, propertiesReplica)
if err != nil {
return fmt.Errorf("upscaling PostgreSQL Server Replica %q (Resource Group %q): %+v", replicaId.Name, replicaId.ResourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for update of PostgreSQL Server Replica %q (Resource Group %q): %+v", replicaId.Name, replicaId.ResourceGroup, err)
}
}
}
}
publicAccess := postgresql.PublicNetworkAccessEnumEnabled
if v := d.Get("public_network_access_enabled"); !v.(bool) {
publicAccess = postgresql.PublicNetworkAccessEnumDisabled
}
ssl := postgresql.SslEnforcementEnumEnabled
if v := d.Get("ssl_enforcement_enabled"); !v.(bool) {
ssl = postgresql.SslEnforcementEnumDisabled
}
tlsMin := postgresql.MinimalTLSVersionEnum(d.Get("ssl_minimal_tls_version_enforced").(string))
properties := postgresql.ServerUpdateParameters{
Identity: expandServerIdentity(d.Get("identity").([]interface{})),
ServerUpdateParametersProperties: &postgresql.ServerUpdateParametersProperties{
PublicNetworkAccess: publicAccess,
SslEnforcement: ssl,
MinimalTLSVersion: tlsMin,
StorageProfile: expandPostgreSQLStorageProfile(d),
Version: postgresql.ServerVersion(d.Get("version").(string)),
},
Sku: sku,
Tags: tags.Expand(d.Get("tags").(map[string]interface{})),
}
if d.HasChange("administrator_login_password") {
properties.ServerUpdateParametersProperties.AdministratorLoginPassword = utils.String(d.Get("administrator_login_password").(string))
}
if old, new := d.GetChange("create_mode"); postgresql.CreateMode(old.(string)) == postgresql.CreateModeReplica && postgresql.CreateMode(new.(string)) == postgresql.CreateModeDefault {
properties.ServerUpdateParametersProperties.ReplicationRole = utils.String("None")
}
future, err := client.Update(ctx, id.ResourceGroup, id.Name, properties)
if err != nil {
return fmt.Errorf("updating PostgreSQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for update of PostgreSQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
if v, ok := d.GetOk("threat_detection_policy"); ok {
alert := expandSecurityAlertPolicy(v)
if alert != nil {
future, err := securityClient.CreateOrUpdate(ctx, id.ResourceGroup, id.Name, *alert)
if err != nil {
return fmt.Errorf("updataing mssql server security alert policy: %v", err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for creation/update of postgrest server security alert policy (server %q, resource group %q): %+v", id.Name, id.ResourceGroup, err)
}
}
}
return resourcePostgreSQLServerRead(d, meta)
}
func resourcePostgreSQLServerRead(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Postgres.ServersClient
securityClient := meta.(*clients.Client).Postgres.ServerSecurityAlertPoliciesClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.ServerID(d.Id())
if err != nil {
return fmt.Errorf("parsing Postgres Server ID : %v", err)
}
resp, err := client.Get(ctx, id.ResourceGroup, id.Name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[WARN] PostgreSQL Server %q was not found (resource group %q)", id.Name, id.ResourceGroup)
d.SetId("")
return nil
}
return fmt.Errorf("making Read request on Azure PostgreSQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
d.Set("name", resp.Name)
d.Set("resource_group_name", id.ResourceGroup)
if location := resp.Location; location != nil {
d.Set("location", azure.NormalizeLocation(*location))
}
tier := postgresql.Basic
if sku := resp.Sku; sku != nil {
d.Set("sku_name", sku.Name)
tier = sku.Tier
}
if err := d.Set("identity", flattenServerIdentity(resp.Identity)); err != nil {
return fmt.Errorf("setting `identity`: %+v", err)
}
if props := resp.ServerProperties; props != nil {
d.Set("administrator_login", props.AdministratorLogin)
d.Set("ssl_enforcement", string(props.SslEnforcement))
d.Set("ssl_minimal_tls_version_enforced", props.MinimalTLSVersion)
d.Set("version", string(props.Version))
d.Set("infrastructure_encryption_enabled", props.InfrastructureEncryption == postgresql.InfrastructureEncryptionEnabled)
d.Set("public_network_access_enabled", props.PublicNetworkAccess == postgresql.PublicNetworkAccessEnumEnabled)
d.Set("ssl_enforcement_enabled", props.SslEnforcement == postgresql.SslEnforcementEnumEnabled)
if err := d.Set("storage_profile", flattenPostgreSQLStorageProfile(props.StorageProfile)); err != nil {
return fmt.Errorf("setting `storage_profile`: %+v", err)
}
if storage := props.StorageProfile; storage != nil {
d.Set("storage_mb", storage.StorageMB)
d.Set("backup_retention_days", storage.BackupRetentionDays)
d.Set("auto_grow_enabled", storage.StorageAutogrow == postgresql.StorageAutogrowEnabled)
d.Set("geo_redundant_backup_enabled", storage.GeoRedundantBackup == postgresql.Enabled)
}
// Computed
d.Set("fqdn", props.FullyQualifiedDomainName)
}
// the basic does not support threat detection policies
if tier == postgresql.GeneralPurpose || tier == postgresql.MemoryOptimized {
secResp, err := securityClient.Get(ctx, id.ResourceGroup, id.Name)
if err != nil && !utils.ResponseWasNotFound(secResp.Response) {
return fmt.Errorf("making read request to postgres server security alert policy: %+v", err)
}
if !utils.ResponseWasNotFound(secResp.Response) {
block := flattenSecurityAlertPolicy(secResp.SecurityAlertPolicyProperties, d.Get("threat_detection_policy.0.storage_account_access_key").(string))
if err := d.Set("threat_detection_policy", block); err != nil {
return fmt.Errorf("setting `threat_detection_policy`: %+v", err)
}
}
}
return tags.FlattenAndSet(d, resp.Tags)
}
func resourcePostgreSQLServerDelete(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Postgres.ServersClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := parse.ServerID(d.Id())
if err != nil {
return fmt.Errorf("parsing Postgres Server ID : %v", err)
}
future, err := client.Delete(ctx, id.ResourceGroup, id.Name)
if err != nil {
return fmt.Errorf("deleting PostgreSQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for deletion of PostgreSQL Server %q (Resource Group %q): %+v", id.Name, id.ResourceGroup, err)
}
return nil
}
func indexOfSku(skuName string) int {
for k, v := range skuList {
if skuName == v {
return k
}
}
return -1 // not found.
}
func expandServerSkuName(skuName string) (*postgresql.Sku, error) {
parts := strings.Split(skuName, "_")
if len(parts) != 3 {
return nil, fmt.Errorf("sku_name (%s) has the wrong number of parts (%d) after splitting on _", skuName, len(parts))
}
var tier postgresql.SkuTier
switch parts[0] {
case "B":
tier = postgresql.Basic
case "GP":
tier = postgresql.GeneralPurpose
case "MO":
tier = postgresql.MemoryOptimized
default:
return nil, fmt.Errorf("sku_name %s has unknown sku tier %s", skuName, parts[0])
}
capacity, err := strconv.Atoi(parts[2])
if err != nil {
return nil, fmt.Errorf("cannot convert skuname %s capcity %s to int", skuName, parts[2])
}
return &postgresql.Sku{
Name: utils.String(skuName),
Tier: tier,
Capacity: utils.Int32(int32(capacity)),
Family: utils.String(parts[1]),
}, nil
}
func expandPostgreSQLStorageProfile(d *pluginsdk.ResourceData) *postgresql.StorageProfile {
storage := postgresql.StorageProfile{}
if v, ok := d.GetOk("storage_profile"); ok {
storageprofile := v.([]interface{})[0].(map[string]interface{})
storage.BackupRetentionDays = utils.Int32(int32(storageprofile["backup_retention_days"].(int)))
storage.StorageMB = utils.Int32(int32(storageprofile["storage_mb"].(int)))
storage.StorageAutogrow = postgresql.StorageAutogrow(storageprofile["auto_grow"].(string))
storage.GeoRedundantBackup = postgresql.GeoRedundantBackup(storageprofile["geo_redundant_backup"].(string))
}
// now override whatever we may have from the block with the top level properties
if v, ok := d.GetOk("auto_grow_enabled"); ok {
storage.StorageAutogrow = postgresql.StorageAutogrowDisabled
if v.(bool) {
storage.StorageAutogrow = postgresql.StorageAutogrowEnabled
}
}
if v, ok := d.GetOk("backup_retention_days"); ok {
storage.BackupRetentionDays = utils.Int32(int32(v.(int)))
}
if v, ok := d.GetOk("geo_redundant_backup_enabled"); ok {
storage.GeoRedundantBackup = postgresql.Disabled
if v.(bool) {
storage.GeoRedundantBackup = postgresql.Enabled
}
}
if v, ok := d.GetOk("storage_mb"); ok {
storage.StorageMB = utils.Int32(int32(v.(int)))
}
return &storage
}
func flattenPostgreSQLStorageProfile(resp *postgresql.StorageProfile) []interface{} {
values := map[string]interface{}{}
values["storage_mb"] = nil
if storageMB := resp.StorageMB; storageMB != nil {
values["storage_mb"] = *storageMB
}
values["backup_retention_days"] = nil
if backupRetentionDays := resp.BackupRetentionDays; backupRetentionDays != nil {
values["backup_retention_days"] = *backupRetentionDays
}
values["auto_grow"] = string(resp.StorageAutogrow)
values["geo_redundant_backup"] = string(resp.GeoRedundantBackup)
return []interface{}{values}
}
func expandSecurityAlertPolicy(i interface{}) *postgresql.ServerSecurityAlertPolicy {
slice := i.([]interface{})
if len(slice) == 0 {
return nil
}
block := slice[0].(map[string]interface{})
state := postgresql.ServerSecurityAlertPolicyStateEnabled
if !block["enabled"].(bool) {
state = postgresql.ServerSecurityAlertPolicyStateDisabled
}
props := &postgresql.SecurityAlertPolicyProperties{
State: state,
}
if v, ok := block["disabled_alerts"]; ok {
props.DisabledAlerts = utils.ExpandStringSlice(v.(*pluginsdk.Set).List())
}
if v, ok := block["email_addresses"]; ok {