forked from hashicorp/terraform-provider-azurerm
-
Notifications
You must be signed in to change notification settings - Fork 1
/
postgresql_flexible_server_resource.go
1080 lines (905 loc) · 34.7 KB
/
postgresql_flexible_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/hashicorp/go-azure-helpers/lang/pointer"
"github.com/hashicorp/go-azure-helpers/lang/response"
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonids"
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonschema"
"github.com/hashicorp/go-azure-helpers/resourcemanager/identity"
"github.com/hashicorp/go-azure-helpers/resourcemanager/location"
"github.com/hashicorp/go-azure-helpers/resourcemanager/tags"
"github.com/hashicorp/go-azure-sdk/resource-manager/postgresql/2021-06-01/serverrestart"
"github.com/hashicorp/go-azure-sdk/resource-manager/postgresql/2022-12-01/servers"
"github.com/hashicorp/go-azure-sdk/resource-manager/privatedns/2018-09-01/privatezones"
"github.com/hashicorp/terraform-provider-azurerm/helpers/tf"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
keyVaultValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/keyvault/validate"
networkValidate "github.com/hashicorp/terraform-provider-azurerm/internal/services/network/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/postgres/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation"
"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
"github.com/hashicorp/terraform-provider-azurerm/utils"
)
const (
ServerMaintenanceWindowEnabled = "Enabled"
ServerMaintenanceWindowDisabled = "Disabled"
)
var postgresqlFlexibleServerResourceName = "azurerm_postgresql_flexible_server"
func resourcePostgresqlFlexibleServer() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourcePostgresqlFlexibleServerCreate,
Read: resourcePostgresqlFlexibleServerRead,
Update: resourcePostgresqlFlexibleServerUpdate,
Delete: resourcePostgresqlFlexibleServerDelete,
Timeouts: &pluginsdk.ResourceTimeout{
Create: pluginsdk.DefaultTimeout(1 * time.Hour),
Read: pluginsdk.DefaultTimeout(5 * time.Minute),
Update: pluginsdk.DefaultTimeout(1 * time.Hour),
Delete: pluginsdk.DefaultTimeout(1 * time.Hour),
},
Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
_, err := servers.ParseFlexibleServerID(id)
return err
}),
Schema: map[string]*pluginsdk.Schema{
"name": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.FlexibleServerName,
},
"resource_group_name": commonschema.ResourceGroupName(),
"location": commonschema.Location(),
"administrator_login": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.All(validation.StringIsNotWhiteSpace, validate.AdminUsernames),
},
"administrator_password": {
Type: pluginsdk.TypeString,
Optional: true,
Sensitive: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"authentication": {
Type: pluginsdk.TypeList,
MaxItems: 1,
Optional: true,
Computed: true,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"active_directory_auth_enabled": {
Type: pluginsdk.TypeBool,
Optional: true,
Default: false,
},
"password_auth_enabled": {
Type: pluginsdk.TypeBool,
Optional: true,
Default: true,
},
"tenant_id": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: validation.IsUUID,
RequiredWith: []string{
"authentication.0.active_directory_auth_enabled",
},
},
},
},
},
"sku_name": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validate.FlexibleServerSkuName,
},
"storage_mb": {
Type: pluginsdk.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntInSlice([]int{32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216}),
},
"version": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true,
// TODO: Remove "15" after this issue has been resolved:
// https://github.com/Azure/azure-rest-api-specs/issues/24186
ValidateFunc: validation.StringInSlice(append(servers.PossibleValuesForServerVersion(), "15"), false),
},
"zone": commonschema.ZoneSingleOptional(),
"create_mode": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
string(servers.CreateModeDefault),
string(servers.CreateModePointInTimeRestore),
string(servers.CreateModeReplica),
string(servers.CreateModeUpdate),
}, false),
},
"delegated_subnet_id": {
Type: pluginsdk.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: networkValidate.SubnetID,
},
"private_dns_zone_id": {
Type: pluginsdk.TypeString,
Optional: true,
Computed: true,
// This is `computed`, because there is a breaking change to require this field when setting vnet.
// For existing fs who don't want to be recreated, they could contact service team to manually migrate to the private dns zone
// We need to ignore the diff when remote is set private dns zone
ForceNew: true,
ValidateFunc: privatezones.ValidatePrivateDnsZoneID,
},
"point_in_time_restore_time_in_utc": {
Type: pluginsdk.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IsRFC3339Time,
},
"source_server_id": {
Type: pluginsdk.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: servers.ValidateFlexibleServerID,
},
"maintenance_window": {
Type: pluginsdk.TypeList,
Optional: true,
MaxItems: 1,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"day_of_week": {
Type: pluginsdk.TypeInt,
Optional: true,
Default: 0,
ValidateFunc: validation.IntBetween(0, 6),
},
"start_hour": {
Type: pluginsdk.TypeInt,
Optional: true,
Default: 0,
ValidateFunc: validation.IntBetween(0, 23),
},
"start_minute": {
Type: pluginsdk.TypeInt,
Optional: true,
Default: 0,
ValidateFunc: validation.IntBetween(0, 59),
},
},
},
},
"backup_retention_days": {
Type: pluginsdk.TypeInt,
Optional: true,
Computed: true,
ValidateFunc: validation.IntBetween(7, 35),
},
"geo_redundant_backup_enabled": {
Type: pluginsdk.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
},
"high_availability": {
Type: pluginsdk.TypeList,
Optional: true,
MaxItems: 1,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"mode": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{
string(servers.HighAvailabilityModeZoneRedundant),
string(servers.HighAvailabilityModeSameZone),
}, false),
},
"standby_availability_zone": commonschema.ZoneSingleOptional(),
},
},
},
"fqdn": {
Type: pluginsdk.TypeString,
Computed: true,
},
"public_network_access_enabled": {
Type: pluginsdk.TypeBool,
Computed: true,
},
"replication_role": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
string(servers.ReplicationRoleNone),
}, false),
},
"identity": commonschema.SystemAssignedUserAssignedIdentityOptional(),
"customer_managed_key": {
Type: pluginsdk.TypeList,
Optional: true,
MaxItems: 1,
ForceNew: true,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"key_vault_key_id": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: keyVaultValidate.NestedItemIdWithOptionalVersion,
RequiredWith: []string{
"identity",
"customer_managed_key.0.primary_user_assigned_identity_id",
},
},
"primary_user_assigned_identity_id": {
Type: pluginsdk.TypeString,
Optional: true,
ValidateFunc: commonids.ValidateUserAssignedIdentityID,
},
},
},
},
"tags": commonschema.Tags(),
},
CustomizeDiff: pluginsdk.CustomDiffWithAll(func(ctx context.Context, d *pluginsdk.ResourceDiff, v interface{}) error {
createModeVal := d.Get("create_mode").(string)
if createModeVal == string(servers.CreateModeUpdate) {
oldVersionVal, newVersionVal := d.GetChange("version")
if oldVersionVal != "" && newVersionVal != "" {
oldVersion, err := strconv.ParseInt(oldVersionVal.(string), 10, 32)
if err != nil {
return err
}
newVersion, err := strconv.ParseInt(newVersionVal.(string), 10, 32)
if err != nil {
return err
}
if oldVersion < newVersion {
return nil
}
}
}
d.ForceNew("create_mode")
d.ForceNew("version")
return nil
}, func(ctx context.Context, diff *pluginsdk.ResourceDiff, v interface{}) error {
oldLoginName, _ := diff.GetChange("administrator_login")
if oldLoginName != "" {
diff.ForceNew("administrator_login")
}
return nil
},
),
}
}
func resourcePostgresqlFlexibleServerCreate(d *pluginsdk.ResourceData, meta interface{}) error {
subscriptionId := meta.(*clients.Client).Account.SubscriptionId
client := meta.(*clients.Client).Postgres.FlexibleServersClient
ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d)
defer cancel()
name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)
id := servers.NewFlexibleServerID(subscriptionId, resourceGroup, name)
existing, err := client.Get(ctx, id)
if err != nil {
if !response.WasNotFound(existing.HttpResponse) {
return fmt.Errorf("checking for presence of %s: %+v", id, err)
}
}
if !response.WasNotFound(existing.HttpResponse) {
return tf.ImportAsExistsError("azurerm_postgresql_flexible_server", id.ID())
}
createMode := d.Get("create_mode").(string)
if _, ok := d.GetOk("replication_role"); ok {
return fmt.Errorf("`replication_role` cannot be set while creating")
}
if servers.CreateMode(createMode) == servers.CreateModePointInTimeRestore {
if _, ok := d.GetOk("source_server_id"); !ok {
return fmt.Errorf("`source_server_id` is required when `create_mode` is `PointInTimeRestore`")
}
if _, ok := d.GetOk("point_in_time_restore_time_in_utc"); !ok {
return fmt.Errorf("`point_in_time_restore_time_in_utc` is required when `create_mode` is `PointInTimeRestore`")
}
}
if servers.CreateMode(createMode) == servers.CreateModeReplica {
if _, ok := d.GetOk("source_server_id"); !ok {
return fmt.Errorf("`source_server_id` is required when `create_mode` is `Replica`")
}
}
if createMode == "" || servers.CreateMode(createMode) == servers.CreateModeDefault {
_, adminLoginSet := d.GetOk("administrator_login")
_, adminPwdSet := d.GetOk("administrator_password")
pwdEnabled := true // it defaults to true
if authRaw, authExist := d.GetOk("authentication"); authExist {
authConfig := expandFlexibleServerAuthConfig(authRaw.([]interface{}))
if authConfig.PasswordAuth != nil {
pwdEnabled = *authConfig.PasswordAuth == servers.PasswordAuthEnumEnabled
}
}
if pwdEnabled {
if !adminLoginSet {
return fmt.Errorf("`administrator_login` is required when `create_mode` is `Default` and `authentication.password_auth_enabled` is set to `true`")
}
if !adminPwdSet {
return fmt.Errorf("`administrator_password` is required when `create_mode` is `Default` and `authentication.password_auth_enabled` is set to `true`")
}
} else if adminLoginSet || adminPwdSet {
return fmt.Errorf("`administrator_login` and `administrator_password` cannot be set during creation when `authentication.password_auth_enabled` is set to `false`")
}
if _, ok := d.GetOk("sku_name"); !ok {
return fmt.Errorf("`sku_name` is required when `create_mode` is `Default`")
}
if _, ok := d.GetOk("version"); !ok {
return fmt.Errorf("`version` is required when `create_mode` is `Default`")
}
if _, ok := d.GetOk("storage_mb"); !ok {
return fmt.Errorf("`storage_mb` is required when `create_mode` is `Default`")
}
}
sku, err := expandFlexibleServerSku(d.Get("sku_name").(string))
if err != nil {
return fmt.Errorf("expanding `sku_name` for %s: %v", id, err)
}
parameters := servers.Server{
Location: location.Normalize(d.Get("location").(string)),
Properties: &servers.ServerProperties{
Network: expandArmServerNetwork(d),
Storage: expandArmServerStorage(d),
HighAvailability: expandFlexibleServerHighAvailability(d.Get("high_availability").([]interface{}), true),
Backup: expandArmServerBackup(d),
DataEncryption: expandFlexibleServerDataEncryption(d.Get("customer_managed_key").([]interface{})),
},
Sku: sku,
Tags: tags.Expand(d.Get("tags").(map[string]interface{})),
}
if v, ok := d.GetOk("administrator_login"); ok && v.(string) != "" {
parameters.Properties.AdministratorLogin = utils.String(v.(string))
}
if v, ok := d.GetOk("administrator_password"); ok && v.(string) != "" {
parameters.Properties.AdministratorLoginPassword = utils.String(v.(string))
}
if createMode != "" {
createModeAttr := servers.CreateMode(createMode)
parameters.Properties.CreateMode = &createModeAttr
}
if v, ok := d.GetOk("version"); ok && v.(string) != "" {
version := servers.ServerVersion(v.(string))
parameters.Properties.Version = &version
}
if v, ok := d.GetOk("zone"); ok && v.(string) != "" {
parameters.Properties.AvailabilityZone = utils.String(v.(string))
}
if v, ok := d.GetOk("source_server_id"); ok && v.(string) != "" {
parameters.Properties.SourceServerResourceId = utils.String(v.(string))
}
pointInTimeUTC := d.Get("point_in_time_restore_time_in_utc").(string)
if pointInTimeUTC != "" {
v, err := time.Parse(time.RFC3339, pointInTimeUTC)
if err != nil {
return fmt.Errorf("unable to parse `point_in_time_restore_time_in_utc` value")
}
parameters.Properties.SetPointInTimeUTCAsTime(v)
}
if authRaw, ok := d.GetOk("authentication"); ok {
authConfig := expandFlexibleServerAuthConfig(authRaw.([]interface{}))
parameters.Properties.AuthConfig = authConfig
}
identity, err := identity.ExpandUserAssignedMap(d.Get("identity").([]interface{}))
if err != nil {
return fmt.Errorf("expanding `identity`")
}
parameters.Identity = identity
if err = client.CreateThenPoll(ctx, id, parameters); err != nil {
return fmt.Errorf("creating %s: %+v", id, err)
}
requireAdditionalUpdate := false
updateProperties := servers.ServerPropertiesForUpdate{}
// `maintenance_window` could only be updated with, could not be created with
if v, ok := d.GetOk("maintenance_window"); ok {
requireAdditionalUpdate = true
updateProperties.MaintenanceWindow = expandArmServerMaintenanceWindow(v.([]interface{}))
}
if requireAdditionalUpdate {
update := servers.ServerForUpdate{
Properties: &updateProperties,
}
if err = client.UpdateThenPoll(ctx, id, update); err != nil {
return fmt.Errorf("updating %s: %+v", id, err)
}
}
d.SetId(id.ID())
return resourcePostgresqlFlexibleServerRead(d, meta)
}
func resourcePostgresqlFlexibleServerRead(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Postgres.FlexibleServersClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := servers.ParseFlexibleServerID(d.Id())
if err != nil {
return err
}
resp, err := client.Get(ctx, *id)
if err != nil {
if response.WasNotFound(resp.HttpResponse) {
log.Printf("[INFO] Postgresql Flexibleserver %q does not exist - removing from state", d.Id())
d.SetId("")
return nil
}
return fmt.Errorf("retrieving %s: %+v", id, err)
}
d.Set("name", id.FlexibleServerName)
d.Set("resource_group_name", id.ResourceGroupName)
if model := resp.Model; model != nil {
d.Set("location", location.NormalizeNilable(&model.Location))
if props := model.Properties; props != nil {
d.Set("administrator_login", props.AdministratorLogin) // if pwdEnabled is set to false, then the service does not return the value of AdministratorLogin
d.Set("zone", props.AvailabilityZone)
d.Set("version", pointer.From(props.Version))
d.Set("fqdn", props.FullyQualifiedDomainName)
// Currently, `replicationRole` is set to `Primary` when `createMode` is `Replica` and `replicationRole` is updated to `None`. Service team confirmed it should be set to `None` for this scenario. See more details from https://github.com/Azure/azure-rest-api-specs/issues/22499
d.Set("replication_role", d.Get("replication_role").(string))
if network := props.Network; network != nil {
publicNetworkAccess := false
if network.PublicNetworkAccess != nil {
publicNetworkAccess = *network.PublicNetworkAccess == servers.ServerPublicNetworkAccessStateEnabled
}
d.Set("public_network_access_enabled", publicNetworkAccess)
d.Set("delegated_subnet_id", network.DelegatedSubnetResourceId)
d.Set("private_dns_zone_id", network.PrivateDnsZoneArmResourceId)
}
if err := d.Set("maintenance_window", flattenArmServerMaintenanceWindow(props.MaintenanceWindow)); err != nil {
return fmt.Errorf("setting `maintenance_window`: %+v", err)
}
if storage := props.Storage; storage != nil && storage.StorageSizeGB != nil {
d.Set("storage_mb", (*storage.StorageSizeGB * 1024))
}
if backup := props.Backup; backup != nil {
d.Set("backup_retention_days", backup.BackupRetentionDays)
geoRedundantBackup := false
if backup.GeoRedundantBackup != nil {
geoRedundantBackup = *backup.GeoRedundantBackup == servers.GeoRedundantBackupEnumEnabled
}
d.Set("geo_redundant_backup_enabled", geoRedundantBackup)
}
if err := d.Set("high_availability", flattenFlexibleServerHighAvailability(props.HighAvailability)); err != nil {
return fmt.Errorf("setting `high_availability`: %+v", err)
}
if props.AuthConfig != nil {
d.Set("authentication", flattenFlexibleServerAuthConfig(props.AuthConfig))
}
cmk, err := flattenFlexibleServerDataEncryption(props.DataEncryption)
if err != nil {
return fmt.Errorf("flattening `customer_managed_key`: %+v", err)
}
if err := d.Set("customer_managed_key", cmk); err != nil {
return fmt.Errorf("setting `customer_managed_key`: %+v", err)
}
identity, err := identity.FlattenUserAssignedMap(model.Identity)
if err != nil {
return fmt.Errorf("flattening `identity`: %+v", err)
}
if err := d.Set("identity", identity); err != nil {
return fmt.Errorf("setting `identity`: %+v", err)
}
}
sku, err := flattenFlexibleServerSku(model.Sku)
if err != nil {
return fmt.Errorf("flattening `sku_name` for %s: %v", id, err)
}
d.Set("sku_name", sku)
return tags.FlattenAndSet(d, model.Tags)
}
return nil
}
func resourcePostgresqlFlexibleServerUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Postgres.FlexibleServersClient
ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := servers.ParseFlexibleServerID(d.Id())
if err != nil {
return err
}
parameters := servers.ServerForUpdate{
Properties: &servers.ServerPropertiesForUpdate{},
}
requireUpdateOnLogin := false // it's required to call Create with `createMode` set to `Update` to update login name.
createMode := d.Get("create_mode").(string)
if createMode == "" || servers.CreateMode(createMode) == servers.CreateModeDefault {
_, adminLoginSet := d.GetOk("administrator_login")
_, adminPwdSet := d.GetOk("administrator_password")
pwdEnabled := true // it defaults to true
if authRaw, authExist := d.GetOk("authentication"); authExist {
authConfig := expandFlexibleServerAuthConfig(authRaw.([]interface{}))
if authConfig.PasswordAuth != nil {
pwdEnabled = *authConfig.PasswordAuth == servers.PasswordAuthEnumEnabled
}
}
if pwdEnabled {
if !adminLoginSet {
return fmt.Errorf("`administrator_login` is required when `authentication.password_auth_enabled` is set to `true`")
}
if !adminPwdSet {
return fmt.Errorf("`administrator_password` is required when `authentication.password_auth_enabled` is set to `true`")
}
}
if d.HasChange("administrator_login") {
requireUpdateOnLogin = true
if adminLoginSet && !pwdEnabled {
return fmt.Errorf("when `administrator_login` is first set, `authentication.password_auth_enabled` must be set to `true`")
}
}
}
var requireFailover bool
// failover is only supported when `zone` and `high_availability.0.standby_availability_zone` are exchanged with each other
if d.HasChanges("zone", "high_availability") {
resp, err := client.Get(ctx, *id)
if err != nil || resp.Model == nil {
return err
}
props := resp.Model.Properties
if d.HasChange("zone") {
if !d.HasChange("high_availability.0.standby_availability_zone") {
return fmt.Errorf("`zone` can only be changed when exchanged with the zone specified in `high_availability.0.standby_availability_zone`")
} else {
// zone can only be changed when it is swapped for an existing high_availability.0.standby_availability_zone - a failover is triggered to make it the new primary availability zone
// compare current values of zone and high_availability.0.standby_availability_zone with new values and only allow update/failover if the values of zone and an existing high_availability.0.standby_availability_zone have been swapped
var newZone, newHAStandbyZone string
newZone = d.Get("zone").(string)
newHAStandbyZone = d.Get("high_availability.0.standby_availability_zone").(string)
if props != nil && props.AvailabilityZone != nil && props.HighAvailability != nil && props.HighAvailability.StandbyAvailabilityZone != nil {
if newZone == *props.HighAvailability.StandbyAvailabilityZone && newHAStandbyZone == *props.AvailabilityZone {
requireFailover = true
} else {
return fmt.Errorf("`zone` can only be changed when exchanged with the zone specified in `high_availability.0.standby_availability_zone`")
}
}
}
// changes can occur in high_availability.0.standby_availability_zone when zone has not changed in the case where a high_availability block has been newly added or a high_availability block is removed, meaning HA is now disabled
} else if d.HasChange("high_availability.0.standby_availability_zone") {
if props != nil && props.HighAvailability != nil && props.HighAvailability.Mode != nil {
// if HA Mode is currently "ZoneRedundant" and is still set to "ZoneRedundant", high_availability.0.standby_availability_zone cannot be changed
if *props.HighAvailability.Mode == servers.HighAvailabilityModeZoneRedundant && !d.HasChange("high_availability.0.mode") {
return fmt.Errorf("an existing `high_availability.0.standby_availability_zone` can only be changed when exchanged with the zone specified in `zone`")
}
// if high_availability.0.mode changes from "ZoneRedundant", an existing high_availability block has been removed as this is a required field
// if high_availability.0.mode is not currently "ZoneRedundant", this must be a newly added block
}
}
}
if d.HasChange("replication_role") {
createMode := d.Get("create_mode").(string)
replicationRole := d.Get("replication_role").(string)
if createMode == string(servers.CreateModeReplica) && replicationRole == string(servers.ReplicationRoleNone) {
replicationRole := servers.ReplicationRoleNone
parameters := servers.ServerForUpdate{
Properties: &servers.ServerPropertiesForUpdate{
ReplicationRole: &replicationRole,
},
}
if err := client.UpdateThenPoll(ctx, *id, parameters); err != nil {
return fmt.Errorf("updating `replication_role` for %s: %+v", *id, err)
}
} else {
return fmt.Errorf("`replication_role` only can be updated to `None` for replica server")
}
}
if d.HasChange("administrator_password") {
parameters.Properties.AdministratorLoginPassword = utils.String(d.Get("administrator_password").(string))
}
if d.HasChange("authentication") {
parameters.Properties.AuthConfig = expandFlexibleServerAuthConfig(d.Get("authentication").([]interface{}))
}
if d.HasChange("storage_mb") {
parameters.Properties.Storage = expandArmServerStorage(d)
}
if d.HasChange("backup_retention_days") {
parameters.Properties.Backup = expandArmServerBackup(d)
}
if d.HasChange("maintenance_window") {
parameters.Properties.MaintenanceWindow = expandArmServerMaintenanceWindow(d.Get("maintenance_window").([]interface{}))
}
if d.HasChange("sku_name") {
sku, err := expandFlexibleServerSku(d.Get("sku_name").(string))
if err != nil {
return fmt.Errorf("expanding `sku_name` for %s: %v", id, err)
}
parameters.Sku = sku
}
if d.HasChange("tags") {
parameters.Tags = tags.Expand(d.Get("tags").(map[string]interface{}))
}
if d.HasChange("high_availability") {
parameters.Properties.HighAvailability = expandFlexibleServerHighAvailability(d.Get("high_availability").([]interface{}), false)
}
if d.HasChange("customer_managed_key") {
parameters.Properties.DataEncryption = expandFlexibleServerDataEncryption(d.Get("customer_managed_key").([]interface{}))
}
if d.HasChange("identity") {
identity, err := identity.ExpandUserAssignedMap(d.Get("identity").([]interface{}))
if err != nil {
return fmt.Errorf("expanding `identity` for %s: %+v", *id, err)
}
parameters.Identity = identity
}
if d.HasChange("create_mode") {
createMode := servers.CreateModeForUpdate(d.Get("create_mode").(string))
parameters.Properties.CreateMode = &createMode
}
if d.HasChange("version") {
version := servers.ServerVersion(d.Get("version").(string))
parameters.Properties.Version = &version
}
if requireUpdateOnLogin {
updateMode := servers.CreateModeUpdate
loginParameters := servers.Server{
Location: location.Normalize(d.Get("location").(string)),
Properties: &servers.ServerProperties{
CreateMode: &updateMode,
AuthConfig: expandFlexibleServerAuthConfig(d.Get("authentication").([]interface{})),
AdministratorLogin: utils.String(d.Get("administrator_login").(string)),
AdministratorLoginPassword: utils.String(d.Get("administrator_password").(string)),
Network: expandArmServerNetwork(d),
},
}
if err = client.CreateThenPoll(ctx, *id, loginParameters); err != nil {
return fmt.Errorf("updating %s: %+v", id, err)
}
}
if err = client.UpdateThenPoll(ctx, *id, parameters); err != nil {
return fmt.Errorf("updating %s: %+v", id, err)
}
if requireFailover {
restartClient := meta.(*clients.Client).Postgres.ServerRestartClient
restartServerId := serverrestart.NewFlexibleServerID(id.SubscriptionId, id.ResourceGroupName, id.FlexibleServerName)
failoverMode := serverrestart.FailoverModePlannedFailover
restartParameters := serverrestart.RestartParameter{
RestartWithFailover: utils.Bool(true),
FailoverMode: &failoverMode,
}
if err = restartClient.ServersRestartThenPoll(ctx, restartServerId, restartParameters); err != nil {
return fmt.Errorf("failing over %s: %+v", *id, err)
}
}
return resourcePostgresqlFlexibleServerRead(d, meta)
}
func resourcePostgresqlFlexibleServerDelete(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).Postgres.FlexibleServersClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()
id, err := servers.ParseFlexibleServerID(d.Id())
if err != nil {
return err
}
if err = client.DeleteThenPoll(ctx, *id); err != nil {
return fmt.Errorf("deleting %s: %+v", id, err)
}
return nil
}
func expandArmServerNetwork(d *pluginsdk.ResourceData) *servers.Network {
network := servers.Network{}
if v, ok := d.GetOk("delegated_subnet_id"); ok {
network.DelegatedSubnetResourceId = utils.String(v.(string))
}
if v, ok := d.GetOk("private_dns_zone_id"); ok {
network.PrivateDnsZoneArmResourceId = utils.String(v.(string))
}
return &network
}
func expandArmServerMaintenanceWindow(input []interface{}) *servers.MaintenanceWindow {
if len(input) == 0 {
return &servers.MaintenanceWindow{
CustomWindow: utils.String(ServerMaintenanceWindowDisabled),
}
}
v := input[0].(map[string]interface{})
maintenanceWindow := servers.MaintenanceWindow{
CustomWindow: utils.String(ServerMaintenanceWindowEnabled),
StartHour: utils.Int64(int64(v["start_hour"].(int))),
StartMinute: utils.Int64(int64(v["start_minute"].(int))),
DayOfWeek: utils.Int64(int64(v["day_of_week"].(int))),
}
return &maintenanceWindow
}
func expandArmServerStorage(d *pluginsdk.ResourceData) *servers.Storage {
storage := servers.Storage{}
if v, ok := d.GetOk("storage_mb"); ok {
storage.StorageSizeGB = utils.Int64(int64(v.(int) / 1024))
}
return &storage
}
func expandArmServerBackup(d *pluginsdk.ResourceData) *servers.Backup {
backup := servers.Backup{}
if v, ok := d.GetOk("backup_retention_days"); ok {
backup.BackupRetentionDays = utils.Int64(int64(v.(int)))
}
geoRedundantEnabled := servers.GeoRedundantBackupEnumDisabled
if geoRedundantBackupEnabled := d.Get("geo_redundant_backup_enabled").(bool); geoRedundantBackupEnabled {
geoRedundantEnabled = servers.GeoRedundantBackupEnumEnabled
}
backup.GeoRedundantBackup = &geoRedundantEnabled
return &backup
}
func expandFlexibleServerSku(name string) (*servers.Sku, error) {
if name == "" {
return nil, nil
}
parts := strings.SplitAfterN(name, "_", 2)
var tier servers.SkuTier
switch strings.TrimSuffix(parts[0], "_") {
case "B":
tier = servers.SkuTierBurstable
case "GP":
tier = servers.SkuTierGeneralPurpose
case "MO":
tier = servers.SkuTierMemoryOptimized
default:
return nil, fmt.Errorf("sku_name %s has unknown sku tier %s", name, parts[0])
}
return &servers.Sku{
Name: parts[1],
Tier: tier,
}, nil
}
func flattenFlexibleServerSku(sku *servers.Sku) (string, error) {
if sku == nil || sku.Tier == "" {
return "", nil
}
var tier string
switch sku.Tier {
case servers.SkuTierBurstable:
tier = "B"
case servers.SkuTierGeneralPurpose:
tier = "GP"
case servers.SkuTierMemoryOptimized:
tier = "MO"
default:
return "", fmt.Errorf("sku_name has unknown sku tier %s", sku.Tier)
}
return strings.Join([]string{tier, sku.Name}, "_"), nil
}
func flattenArmServerMaintenanceWindow(input *servers.MaintenanceWindow) []interface{} {
if input == nil || input.CustomWindow == nil || *input.CustomWindow == ServerMaintenanceWindowDisabled {
return make([]interface{}, 0)
}
var dayOfWeek int64
if input.DayOfWeek != nil {
dayOfWeek = *input.DayOfWeek
}
var startHour int64
if input.StartHour != nil {
startHour = *input.StartHour
}
var startMinute int64
if input.StartMinute != nil {
startMinute = *input.StartMinute
}
return []interface{}{
map[string]interface{}{
"day_of_week": dayOfWeek,
"start_hour": startHour,
"start_minute": startMinute,
},
}
}
func expandFlexibleServerHighAvailability(inputs []interface{}, isCreate bool) *servers.HighAvailability {
if len(inputs) == 0 || inputs[0] == nil {
highAvailability := servers.HighAvailabilityModeDisabled
return &servers.HighAvailability{
Mode: &highAvailability,
}
}
input := inputs[0].(map[string]interface{})
mode := servers.HighAvailabilityMode(input["mode"].(string))
result := servers.HighAvailability{
Mode: &mode,
}
// service team confirmed it doesn't support to update `high_availability.0.standby_availability_zone` after the PostgreSQL Flexible Server resource is created
if isCreate {
if v, ok := input["standby_availability_zone"]; ok && v.(string) != "" {
result.StandbyAvailabilityZone = utils.String(v.(string))
}
}
return &result
}
func flattenFlexibleServerHighAvailability(ha *servers.HighAvailability) []interface{} {
if ha == nil || ha.Mode == nil || *ha.Mode == servers.HighAvailabilityModeDisabled {
return []interface{}{}
}
var zone string
if ha.StandbyAvailabilityZone != nil {
zone = *ha.StandbyAvailabilityZone
}
return []interface{}{
map[string]interface{}{
"mode": string(*ha.Mode),
"standby_availability_zone": zone,
},
}
}
func expandFlexibleServerAuthConfig(authRaw []interface{}) *servers.AuthConfig {
if len(authRaw) == 0 || authRaw[0] == nil {
return nil
}
authConfigs := authRaw[0].(map[string]interface{})
out := servers.AuthConfig{}
activeDirectoryAuthEnabled := servers.ActiveDirectoryAuthEnumDisabled
if authConfigs["active_directory_auth_enabled"].(bool) {
activeDirectoryAuthEnabled = servers.ActiveDirectoryAuthEnumEnabled