/
resource_vcd_org_vdc.go
1474 lines (1287 loc) · 54.8 KB
/
resource_vcd_org_vdc.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 vcd
//lint:file-ignore SA1019 ignore deprecated functions
import (
"context"
"errors"
"fmt"
"log"
"net/url"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/vmware/go-vcloud-director/v2/govcd"
"github.com/vmware/go-vcloud-director/v2/types/v56"
"github.com/vmware/go-vcloud-director/v2/util"
)
func resourceVcdOrgVdc() *schema.Resource {
capacityWithUsage := schema.Schema{
Type: schema.TypeList,
Required: true,
MinItems: 1,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"allocated": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Capacity that is committed to be available. Value in MB or MHz. Used with AllocationPool (Allocation pool) and ReservationPool (Reservation pool).",
},
"limit": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Capacity limit relative to the value specified for Allocation. It must not be less than that value. If it is greater than that value, it implies over provisioning. A value of 0 specifies unlimited units. Value in MB or MHz. Used with AllocationVApp (Pay as you go).",
},
"reserved": {
Type: schema.TypeInt,
Computed: true,
},
"used": {
Type: schema.TypeInt,
Computed: true,
},
},
},
}
return &schema.Resource{
CreateContext: resourceVcdVdcCreate,
DeleteContext: resourceVcdVdcDelete,
ReadContext: resourceVcdVdcRead,
UpdateContext: resourceVcdVdcUpdate,
Importer: &schema.ResourceImporter{
StateContext: resourceVcdOrgVdcImport,
},
Schema: map[string]*schema.Schema{
"org": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "The name of organization to use, optional if defined at provider " +
"level. Useful when connected as sysadmin working across different organizations",
},
"name": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"allocation_model": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"AllocationVApp", "AllocationPool", "ReservationPool", "Flex"}, false),
Description: "The allocation model used by this VDC; must be one of {AllocationVApp, AllocationPool, ReservationPool, Flex}",
},
"compute_capacity": {
Required: true,
MinItems: 1,
MaxItems: 1,
Type: schema.TypeList,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"cpu": &capacityWithUsage,
"memory": &capacityWithUsage,
},
},
Description: "The compute capacity allocated to this VDC.",
},
"nic_quota": {
Type: schema.TypeInt,
Optional: true,
Description: "Maximum number of virtual NICs allowed in this VDC. Defaults to 0, which specifies an unlimited number.",
},
"network_quota": {
Type: schema.TypeInt,
Optional: true,
Description: "Maximum number of network objects that can be deployed in this VDC. Defaults to 0, which means no networks can be deployed.",
},
"vm_quota": {
Type: schema.TypeInt,
Optional: true,
Description: "The maximum number of VMs that can be created in this VDC. Includes deployed and undeployed VMs in vApps and vApp templates. Defaults to 0, which specifies an unlimited number.",
},
"enabled": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "True if this VDC is enabled for use by the organization VDCs. Default is true.",
},
"storage_profile": {
Type: schema.TypeSet,
Required: true,
ForceNew: false,
MinItems: 1,
Description: "Storage profiles supported by this VDC.",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
Description: "Name of Provider VDC storage profile.",
},
"enabled": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "True if this storage profile is enabled for use in the VDC.",
},
"limit": {
Type: schema.TypeInt,
Required: true,
Description: "Maximum number of MB allocated for this storage profile. A value of 0 specifies unlimited MB.",
},
"default": {
Type: schema.TypeBool,
Required: true,
Description: "True if this is default storage profile for this VDC. The default storage profile is used when an object that can specify a storage profile is created with no storage profile specified.",
},
"storage_used_in_mb": {
Type: schema.TypeInt,
Computed: true,
Description: "Storage used in MB",
},
},
},
},
"memory_guaranteed": {
Type: schema.TypeFloat,
Computed: true,
Optional: true,
Description: "Percentage of allocated memory resources guaranteed to vApps deployed in this VDC. " +
"For example, if this value is 0.75, then 75% of allocated resources are guaranteed. " +
"Required when AllocationModel is AllocationVApp or AllocationPool. When Allocation model is AllocationPool minimum value is 0.2. If the element is empty, vCD sets a value.",
},
"cpu_guaranteed": {
Type: schema.TypeFloat,
Optional: true,
Computed: true,
Description: "Percentage of allocated CPU resources guaranteed to vApps deployed in this VDC. " +
"For example, if this value is 0.75, then 75% of allocated resources are guaranteed. " +
"Required when AllocationModel is AllocationVApp or AllocationPool. If the element is empty, vCD sets a value",
},
"cpu_speed": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Specifies the clock frequency, in Megahertz, for any virtual CPU that is allocated to a VM. A VM with 2 vCPUs will consume twice as much of this value. Ignored for ReservationPool. Required when AllocationModel is AllocationVApp or AllocationPool, and may not be less than 256 MHz. Defaults to 1000 MHz if the element is empty or missing.",
},
"enable_thin_provisioning": {
Type: schema.TypeBool,
Optional: true,
Description: "Boolean to request thin provisioning. Request will be honored only if the underlying datastore supports it. Thin provisioning saves storage space by committing it on demand. This allows over-allocation of storage.",
},
"network_pool_name": {
Type: schema.TypeString,
Optional: true,
Description: "The name of a network pool in the Provider VDC. Required if this VDC will contain routed or isolated networks.",
},
"provider_vdc_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "A reference to the Provider VDC from which this organization VDC is provisioned.",
},
"enable_fast_provisioning": {
Type: schema.TypeBool,
Optional: true,
Description: "Request for fast provisioning. Request will be honored only if the underlying datas tore supports it. Fast provisioning can reduce the time it takes to create virtual machines by using vSphere linked clones. If you disable fast provisioning, all provisioning operations will result in full clones.",
},
// Always null in the response to a GET request. On update, set to false to disallow the update if the AllocationModel is AllocationPool or ReservationPool
// and the ComputeCapacity you specified is greater than what the backing Provider VDC can supply. Defaults to true if empty or missing.
"allow_over_commit": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Description: "Set to false to disallow creation of the VDC if the AllocationModel is AllocationPool or ReservationPool and the ComputeCapacity you specified is greater than what the backing Provider VDC can supply. Default is true.",
},
"enable_vm_discovery": {
Type: schema.TypeBool,
Optional: true,
Description: "True if discovery of vCenter VMs is enabled for resource pools backing this VDC. If left unspecified, the actual behaviour depends on enablement at the organization level and at the system level.",
},
"elasticity": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Description: "Set to true to indicate if the Flex VDC is to be elastic.",
},
"include_vm_memory_overhead": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Description: "Set to true to indicate if the Flex VDC is to include memory overhead into its accounting for admission control.",
},
"delete_force": {
Type: schema.TypeBool,
Optional: true,
Description: "When destroying use delete_force=True to remove a VDC and any objects it contains, regardless of their state.",
},
"delete_recursive": {
Type: schema.TypeBool,
Optional: true,
Description: "When destroying use delete_recursive=True to remove the VDC and any objects it contains that are in a state that normally allows removal.",
},
"metadata": {
Type: schema.TypeMap,
Optional: true,
Computed: true, // To be compatible with `metadata_entry`
Description: "Key and value pairs for Org VDC metadata",
Deprecated: "Use metadata_entry instead",
ConflictsWith: []string{"metadata_entry"},
},
"metadata_entry": metadataEntryResourceSchemaDeprecated("VDC"),
"vm_sizing_policy_ids": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Description: "Set of VM Sizing Policy IDs",
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"vm_placement_policy_ids": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Description: "Set of VM Placement Policy IDs",
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"vm_vgpu_policy_ids": {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Description: "Set of VM vGPU Policy IDs",
Elem: &schema.Schema{
Type: schema.TypeString,
},
},
"default_vm_sizing_policy_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "ID of default VM Compute policy, which can be a VM Sizing Policy, VM Placement Policy or vGPU Policy",
ConflictsWith: []string{"default_compute_policy_id"},
Deprecated: "Use `default_compute_policy_id` attribute instead, which can support VM Sizing Policies, VM Placement Policies and vGPU Policies",
},
"default_compute_policy_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "ID of default Compute policy for this VDC, which can be a VM Sizing Policy, VM Placement Policy or vGPU Policy",
ConflictsWith: []string{"default_vm_sizing_policy_id"},
},
"edge_cluster_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "ID of NSX-T Edge Cluster (provider vApp networking services and DHCP capability for Isolated networks)",
Deprecated: "Please use 'vcd_org_vdc_nsxt_network_profile' resource to manage Edge Cluster and Segment Profile Templates",
},
"enable_nsxv_distributed_firewall": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Description: "Set to true to enable distributed firewall - Only applies to NSX-V VDCs",
},
},
}
}
// Creates a new VDC from a resource definition
func resourceVcdVdcCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
orgVdcName := d.Get("name").(string)
log.Printf("[TRACE] VDC creation initiated: %s", orgVdcName)
vcdClient := meta.(*VCDClient)
if !vcdClient.Client.IsSysAdmin {
return diag.Errorf("functionality requires System administrator privileges")
}
// check that elasticity and include_vm_memory_overhead are used only for Flex
_, elasticityConfigured := d.GetOkExists("elasticity")
_, vmMemoryOverheadConfigured := d.GetOkExists("include_vm_memory_overhead")
if d.Get("allocation_model").(string) != "Flex" && (elasticityConfigured || vmMemoryOverheadConfigured) {
return diag.Errorf("`elasticity` and `include_vm_memory_overhead` can be used only with Flex allocation model (vCD 9.7+)")
}
// VDC creation is accessible only in administrator API part
adminOrg, err := vcdClient.GetAdminOrgFromResource(d)
if err != nil {
return diag.Errorf(errorRetrievingOrg, err)
}
orgVdc, err := adminOrg.GetVDCByName(orgVdcName, false)
if orgVdc != nil || err == nil {
return diag.Errorf("org VDC with such name already exists: %s", orgVdcName)
}
params, err := getVcdVdcInput(d, vcdClient)
if err != nil {
return diag.FromErr(err)
}
log.Printf("[DEBUG] Creating VDC: %#v", params)
vdc, err := adminOrg.CreateOrgVdc(params)
if err != nil {
log.Printf("[DEBUG] Error creating VDC: %s", err)
return diag.Errorf("error creating VDC: %s", err)
}
d.SetId(vdc.Vdc.ID)
log.Printf("[TRACE] VDC created: %#v", vdc)
err = createOrUpdateOrgMetadata(d, meta)
if err != nil {
return diag.Errorf("error adding metadata to VDC: %s", err)
}
err = addAssignedComputePolicies(d, meta)
if err != nil {
return diag.Errorf("error assigning VM Compute Policies to VDC: %s", err)
}
// Edge Cluster ID uses different endpoint (VDC Network Profiles endpoint) and it shouldn't be
// set on create if it is not present
edgeClusterId := d.Get("edge_cluster_id").(string)
if edgeClusterId != "" {
err = setVdcEdgeCluster(d, vdc)
if err != nil {
return diag.Errorf("error setting Edge Cluster: %s", err)
}
}
if d.Get("enable_nsxv_distributed_firewall").(bool) {
if !vdc.IsNsxv() {
return diag.Errorf("VDC '%s' is not a NSX-V VDC and the property 'enable_nsxv_distributed_firewall' can't be used", orgVdcName)
}
dfw := govcd.NewNsxvDistributedFirewall(&vcdClient.Client, vdc.Vdc.ID)
err = dfw.Enable()
if err != nil {
return diag.Errorf("error enabling NSX-V distributed firewall for VDC '%s': %s", orgVdcName, err)
}
dSet(d, "enable_nsxv_distributed_firewall", true)
}
return resourceVcdVdcRead(ctx, d, meta)
}
func resourceVcdVdcRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var diags diag.Diagnostics
vdcName := d.Get("name").(string)
log.Printf("[TRACE] VDC read initiated: %s", vdcName)
vcdClient := meta.(*VCDClient)
adminOrg, err := vcdClient.GetAdminOrgFromResource(d)
if err != nil {
return diag.Errorf(errorRetrievingOrg, err)
}
adminVdc, err := adminOrg.GetAdminVDCByName(vdcName, false)
if err != nil {
if govcd.ContainsNotFound(err) {
d.SetId("")
return nil
}
log.Printf("[DEBUG] Unable to find VDC %s", vdcName)
return diag.Errorf("unable to find VDC %s, err: %s", vdcName, err)
}
diags = append(diags, setOrgVdcData(d, vcdClient, adminVdc)...)
if diags != nil && diags.HasError() {
return diags
}
err = setEdgeClusterData(d, adminVdc, "vdc_org_vdc")
if err != nil {
return append(diags, diag.FromErr(err)...)
}
dSet(d, "enable_nsxv_distributed_firewall", false)
if adminVdc.IsNsxv() {
dfw := govcd.NewNsxvDistributedFirewall(&vcdClient.Client, adminVdc.AdminVdc.ID)
enabled, err := dfw.IsEnabled()
if err != nil {
return append(diags, diag.Errorf("error retrieving NSX-V distributed firewall state for VDC '%s': %s", vdcName, err)...)
}
dSet(d, "enable_nsxv_distributed_firewall", enabled)
}
// This must be checked at the end as setOrgVdcData can throw Warning diagnostics
if len(diags) > 0 {
return diags
}
return nil
}
// setOrgVdcData sets object state from *govcd.AdminVdc
func setOrgVdcData(d *schema.ResourceData, vcdClient *VCDClient, adminVdc *govcd.AdminVdc) diag.Diagnostics {
var diags diag.Diagnostics
dSet(d, "allocation_model", adminVdc.AdminVdc.AllocationModel)
if adminVdc.AdminVdc.ResourceGuaranteedCpu != nil {
dSet(d, "cpu_guaranteed", *adminVdc.AdminVdc.ResourceGuaranteedCpu)
}
if adminVdc.AdminVdc.VCpuInMhz != nil {
dSet(d, "cpu_speed", int(*adminVdc.AdminVdc.VCpuInMhz))
}
dSet(d, "description", adminVdc.AdminVdc.Description)
if adminVdc.AdminVdc.UsesFastProvisioning != nil {
dSet(d, "enable_fast_provisioning", *adminVdc.AdminVdc.UsesFastProvisioning)
}
if adminVdc.AdminVdc.IsThinProvision != nil {
dSet(d, "enable_thin_provisioning", *adminVdc.AdminVdc.IsThinProvision)
}
dSet(d, "enable_vm_discovery", adminVdc.AdminVdc.VmDiscoveryEnabled)
dSet(d, "enabled", adminVdc.AdminVdc.IsEnabled)
if adminVdc.AdminVdc.ResourceGuaranteedMemory != nil {
dSet(d, "memory_guaranteed", *adminVdc.AdminVdc.ResourceGuaranteedMemory)
}
dSet(d, "name", adminVdc.AdminVdc.Name)
if adminVdc.AdminVdc.NetworkPoolReference != nil {
networkPool, err := govcd.GetNetworkPoolByHREF(vcdClient.VCDClient, adminVdc.AdminVdc.NetworkPoolReference.HREF)
if err != nil {
return diag.Errorf("error retrieving network pool: %s", err)
}
dSet(d, "network_pool_name", networkPool.Name)
}
dSet(d, "network_quota", adminVdc.AdminVdc.NetworkQuota)
dSet(d, "nic_quota", adminVdc.AdminVdc.Vdc.NicQuota)
if adminVdc.AdminVdc.ProviderVdcReference != nil {
dSet(d, "provider_vdc_name", adminVdc.AdminVdc.ProviderVdcReference.Name)
}
dSet(d, "vm_quota", adminVdc.AdminVdc.Vdc.VMQuota)
if err := d.Set("compute_capacity", getComputeCapacities(adminVdc.AdminVdc.ComputeCapacity)); err != nil {
return diag.Errorf("error setting compute_capacity: %s", err)
}
if adminVdc.AdminVdc.VdcStorageProfiles != nil {
storageProfileStateData, err := getComputeStorageProfiles(vcdClient, adminVdc.AdminVdc.VdcStorageProfiles)
if err != nil {
return diag.Errorf("error preparing storage profile data: %s", err)
}
if err := d.Set("storage_profile", storageProfileStateData); err != nil {
return diag.Errorf("error setting compute_capacity: %s", err)
}
}
if adminVdc.AdminVdc.IsElastic != nil {
dSet(d, "elasticity", *adminVdc.AdminVdc.IsElastic)
}
if adminVdc.AdminVdc.IncludeMemoryOverhead != nil {
dSet(d, "include_vm_memory_overhead", *adminVdc.AdminVdc.IncludeMemoryOverhead)
}
dSet(d, "default_vm_sizing_policy_id", adminVdc.AdminVdc.DefaultComputePolicy.ID) // Deprecated, populating for compatibility
dSet(d, "default_compute_policy_id", adminVdc.AdminVdc.DefaultComputePolicy.ID)
assignedVmComputePolicies, err := adminVdc.GetAllAssignedVdcComputePoliciesV2(nil)
if err != nil {
log.Printf("[DEBUG] Unable to get assigned VM Compute policies")
return diag.Errorf("unable to get assigned VM Compute policies %s", err)
}
var sizingPolicyIds []string
var placementPolicyIds []string
var vgpuPolicyIds []string
for _, policy := range assignedVmComputePolicies {
if policy.VdcComputePolicyV2.IsSizingOnly {
sizingPolicyIds = append(sizingPolicyIds, policy.VdcComputePolicyV2.ID)
} else if policy.VdcComputePolicyV2.IsVgpuPolicy {
vgpuPolicyIds = append(vgpuPolicyIds, policy.VdcComputePolicyV2.ID)
} else {
placementPolicyIds = append(placementPolicyIds, policy.VdcComputePolicyV2.ID)
}
}
vmSizingPoliciesSet := convertStringsToTypeSet(sizingPolicyIds)
vmPlacementPoliciesSet := convertStringsToTypeSet(placementPolicyIds)
vmVgpuPoliciesSet := convertStringsToTypeSet(vgpuPolicyIds)
err = d.Set("vm_sizing_policy_ids", vmSizingPoliciesSet)
if err != nil {
return diag.FromErr(err)
}
err = d.Set("vm_placement_policy_ids", vmPlacementPoliciesSet)
if err != nil {
return diag.FromErr(err)
}
err = d.Set("vm_vgpu_policy_ids", vmVgpuPoliciesSet)
if err != nil {
return diag.FromErr(err)
}
diags = append(diags, updateMetadataInStateDeprecated(d, vcdClient, "vcd_org_vdc", adminVdc)...)
if diags != nil && diags.HasError() {
log.Printf("[DEBUG] Unable to set VDC metadata")
return diags
}
log.Printf("[TRACE] vdc read completed: %#v", adminVdc.AdminVdc)
// This must be checked at the end as updateMetadataInStateDeprecated can throw Warning diagnostics
if len(diags) > 0 {
return diags
}
return nil
}
// getComputeStorageProfiles constructs specific struct to be saved in Terraform state file.
// Expected E.g.
func getComputeStorageProfiles(vcdClient *VCDClient, profile *types.VdcStorageProfiles) ([]map[string]interface{}, error) {
root := make([]map[string]interface{}, 0)
for _, vdcStorageProfile := range profile.VdcStorageProfile {
vdcStorageProfileDetails, err := vcdClient.GetStorageProfileByHref(vdcStorageProfile.HREF)
if err != nil {
return nil, err
}
storageProfileData := make(map[string]interface{})
storageProfileData["limit"] = vdcStorageProfileDetails.Limit
storageProfileData["default"] = vdcStorageProfileDetails.Default
storageProfileData["enabled"] = vdcStorageProfileDetails.Enabled
storageProfileData["name"] = vdcStorageProfileDetails.Name
storageProfileData["storage_used_in_mb"] = vdcStorageProfileDetails.StorageUsedMB
root = append(root, storageProfileData)
}
return root, nil
}
// getComputeCapacities constructs specific struct to be saved in Terraform state file.
// Expected E.g. &[]map[string]interface {}
// {map[string]interface {}{"cpu":(*[]map[string]interface {})
// ({"allocated":8000, "limit":8000, "overhead":0, "reserved":4000, "used":0}),
// "memory":(*[]map[string]interface {})
// ({"allocated":7168, "limit":7168, "overhead":0, "reserved":3584, "used":0})},
func getComputeCapacities(capacities []*types.ComputeCapacity) *[]map[string]interface{} {
rootInternal := map[string]interface{}{}
var root []map[string]interface{}
for _, capacity := range capacities {
cpuValueMap := map[string]interface{}{}
cpuValueMap["limit"] = int(capacity.CPU.Limit)
cpuValueMap["allocated"] = int(capacity.CPU.Allocated)
cpuValueMap["reserved"] = int(capacity.CPU.Reserved)
cpuValueMap["used"] = int(capacity.CPU.Used)
memoryValueMap := map[string]interface{}{}
memoryValueMap["limit"] = int(capacity.Memory.Limit)
memoryValueMap["allocated"] = int(capacity.Memory.Allocated)
memoryValueMap["reserved"] = int(capacity.Memory.Reserved)
memoryValueMap["used"] = int(capacity.Memory.Used)
var memoryCapacityArray []map[string]interface{}
memoryCapacityArray = append(memoryCapacityArray, memoryValueMap)
var cpuCapacityArray []map[string]interface{}
cpuCapacityArray = append(cpuCapacityArray, cpuValueMap)
rootInternal["cpu"] = &cpuCapacityArray
rootInternal["memory"] = &memoryCapacityArray
root = append(root, rootInternal)
}
return &root
}
// Converts to terraform understandable structure
func getMetadataStruct(metadata []*types.MetadataEntry) StringMap {
metadataMap := make(StringMap, len(metadata))
for _, metadataEntry := range metadata {
metadataMap[metadataEntry.Key] = metadataEntry.TypedValue.Value
}
return metadataMap
}
// resourceVcdVdcUpdate function updates resource with found configurations changes
func resourceVcdVdcUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
vdcName := d.Get("name").(string)
log.Printf("[TRACE] VDC update initiated: %s", vdcName)
vcdClient := meta.(*VCDClient)
adminOrg, err := vcdClient.GetAdminOrgFromResource(d)
if err != nil {
return diag.Errorf(errorRetrievingOrg, err)
}
if d.HasChange("name") {
oldValue, _ := d.GetChange("name")
vdcName = oldValue.(string)
}
adminVdc, err := adminOrg.GetAdminVDCByName(vdcName, false)
if err != nil {
log.Printf("[DEBUG] Unable to find VDC %s", vdcName)
return diag.Errorf("unable to find VDC %s, error: %s", vdcName, err)
}
changedAdminVdc, err := getUpdatedVdcInput(d, vcdClient, adminVdc)
if err != nil {
log.Printf("[DEBUG] Error updating VDC %s with error %s", vdcName, err)
return diag.Errorf("error updating VDC %s, err: %s", vdcName, err)
}
updatedAdminVdc, err := changedAdminVdc.Update()
if err != nil {
log.Printf("[DEBUG] Error updating VDC %s with error %s", vdcName, err)
return diag.Errorf("error updating VDC %s, err: %s", vdcName, err)
}
err = createOrUpdateOrgMetadata(d, meta)
if err != nil {
return diag.Errorf("error updating VDC metadata: %s", err)
}
err = updateAssignedVmComputePolicies(d, meta, changedAdminVdc)
if err != nil {
return diag.Errorf("error assigning VM sizing policies to VDC: %s", err)
}
if d.HasChange("storage_profile") {
vdcStorageProfilesConfigurations := d.Get("storage_profile").(*schema.Set)
err = updateStorageProfiles(vdcStorageProfilesConfigurations, vcdClient, adminVdc, d.Get("provider_vdc_name").(string))
if err != nil {
return diag.Errorf("[VDC update] error updating storage profiles: %s", err)
}
}
if d.HasChange("edge_cluster_id") {
orgVdc, err := adminOrg.GetVDCByName(updatedAdminVdc.AdminVdc.Name, false)
if orgVdc == nil || err != nil {
return diag.Errorf("error retrieving Org VDC from Admin VDC '%s': %s", updatedAdminVdc.AdminVdc.Name, err)
}
err = setVdcEdgeCluster(d, orgVdc)
if err != nil {
return diag.Errorf("error updating 'edge_cluster_id': %s", err)
}
}
if adminVdc.IsNsxv() && d.HasChange("enable_nsxv_distributed_firewall") {
dfw := govcd.NewNsxvDistributedFirewall(&vcdClient.Client, adminVdc.AdminVdc.ID)
enablementState := d.Get("enable_nsxv_distributed_firewall").(bool)
if enablementState {
err = dfw.Enable()
} else {
err = dfw.Disable()
}
if err != nil {
return diag.Errorf("error setting NSX-V distributed firewall state for VDC '%s': %s", vdcName, err)
}
dSet(d, "enable_nsxv_distributed_firewall", enablementState)
}
log.Printf("[TRACE] VDC update completed: %s", adminVdc.AdminVdc.Name)
return resourceVcdVdcRead(ctx, d, meta)
}
func updateStorageProfileDetails(vcdClient *VCDClient, adminVdc *govcd.AdminVdc, storageProfile *types.Reference, storageConfiguration map[string]interface{}) error {
util.Logger.Printf("updating storage profile %#v", storageProfile)
uuid, err := govcd.GetUuidFromHref(storageProfile.HREF, true)
if err != nil {
return fmt.Errorf("error parsing VDC storage profile ID : %s", err)
}
vdcStorageProfileDetails, err := vcdClient.GetStorageProfileByHref(storageProfile.HREF)
if err != nil {
return fmt.Errorf("error getting VDC storage profile: %s", err)
}
_, err = adminVdc.UpdateStorageProfile(uuid, &types.AdminVdcStorageProfile{
Name: storageConfiguration["name"].(string),
IopsSettings: nil,
Units: "MB", // only this value is supported
Limit: int64(storageConfiguration["limit"].(int)),
Default: storageConfiguration["default"].(bool),
Enabled: addrOf(storageConfiguration["enabled"].(bool)),
ProviderVdcStorageProfile: &types.Reference{
HREF: vdcStorageProfileDetails.ProviderVdcStorageProfile.HREF,
},
})
if err != nil {
return fmt.Errorf("error updating VDC storage profile '%s': %s", storageConfiguration["name"].(string), err)
}
return nil
}
func updateStorageProfiles(set *schema.Set, client *VCDClient, adminVdc *govcd.AdminVdc, providerVdcName string) error {
type storageProfileCombo struct {
configuration map[string]interface{}
reference *types.Reference
}
var (
existingStorageProfiles []storageProfileCombo
newStorageProfiles []storageProfileCombo
removeStorageProfiles []storageProfileCombo
defaultSp = make(map[string]bool)
)
var isDefaultStorageProfileNew = false
// 1. find existing storage profiles: SP are both in the definition and in the VDC
for _, storageConfigurationValues := range set.List() {
storageConfiguration := storageConfigurationValues.(map[string]interface{})
for _, vdcStorageProfile := range adminVdc.AdminVdc.VdcStorageProfiles.VdcStorageProfile {
if storageConfiguration["name"].(string) == vdcStorageProfile.Name {
if storageConfiguration["default"].(bool) {
defaultSp[storageConfiguration["name"].(string)] = true
}
existingStorageProfiles = append(existingStorageProfiles, storageProfileCombo{
configuration: storageConfiguration,
reference: vdcStorageProfile,
})
}
}
}
// 2. find new storage profiles: SP are in the definition, but not in the VDC
for _, storageConfigurationValues := range set.List() {
storageConfiguration := storageConfigurationValues.(map[string]interface{})
found := false
for _, vdcStorageProfile := range adminVdc.AdminVdc.VdcStorageProfiles.VdcStorageProfile {
if storageConfiguration["name"].(string) == vdcStorageProfile.Name {
found = true
}
}
if !found {
if storageConfiguration["default"].(bool) {
defaultSp[storageConfiguration["name"].(string)] = true
isDefaultStorageProfileNew = true
}
newStorageProfiles = append(newStorageProfiles, storageProfileCombo{
configuration: storageConfiguration,
reference: nil,
})
}
}
// 3 find removed storage profiles: SP are in the VDC, but not in the definition
for _, vdcStorageProfile := range adminVdc.AdminVdc.VdcStorageProfiles.VdcStorageProfile {
found := false
for _, storageConfigurationValues := range set.List() {
storageConfiguration := storageConfigurationValues.(map[string]interface{})
if storageConfiguration["name"].(string) == vdcStorageProfile.Name {
found = true
}
}
if !found {
_, isDefault := defaultSp[vdcStorageProfile.Name]
if isDefault {
delete(defaultSp, vdcStorageProfile.Name)
}
removeStorageProfiles = append(removeStorageProfiles, storageProfileCombo{
configuration: nil,
reference: vdcStorageProfile,
})
}
}
// 4. Check that there is one and only one default element
if len(defaultSp) == 0 {
return fmt.Errorf("updateStorageProfiles] no default storage profile left after update")
}
if len(defaultSp) > 1 {
defaultItems := ""
for d := range defaultSp {
defaultItems += " " + d
}
return fmt.Errorf("updateStorageProfiles] more than one default storage profile defined [%s]", defaultItems)
}
// 5. Set the default storage profile early
if !isDefaultStorageProfileNew {
defaultSpName := ""
for name := range defaultSp {
defaultSpName = name
break
}
err := adminVdc.SetDefaultStorageProfile(defaultSpName)
if err != nil {
return fmt.Errorf("[updateStorageProfiles] error setting default storage profile '%s': %s", defaultSpName, err)
}
}
// 6. Add new storage profiles
for _, spCombo := range newStorageProfiles {
storageProfile, err := client.QueryProviderVdcStorageProfileByName(spCombo.configuration["name"].(string), adminVdc.AdminVdc.ProviderVdcReference.HREF)
if err != nil {
return fmt.Errorf("[updateStorageProfiles] error retrieving storage profile '%s' from provider VDC '%s': %s", spCombo.configuration["name"].(string), providerVdcName, err)
}
err = adminVdc.AddStorageProfileWait(&types.VdcStorageProfileConfiguration{
Enabled: addrOf(spCombo.configuration["enabled"].(bool)),
Units: "MB",
Limit: int64(spCombo.configuration["limit"].(int)),
Default: spCombo.configuration["default"].(bool),
ProviderVdcStorageProfile: &types.Reference{
HREF: storageProfile.HREF,
Name: storageProfile.Name,
},
}, "")
if err != nil {
return fmt.Errorf("[updateStorageProfiles] error adding new storage profile: %s", err)
}
}
// 7. Update existing storage profiles
for _, spCombo := range existingStorageProfiles {
err := updateStorageProfileDetails(client, adminVdc, spCombo.reference, spCombo.configuration)
if err != nil {
return fmt.Errorf("[updateStorageProfiles] error updating storage profile '%s': %s", spCombo.reference.Name, err)
}
}
// 8. Delete unwanted storage profiles
for _, spCombo := range removeStorageProfiles {
err := adminVdc.RemoveStorageProfileWait(spCombo.reference.Name)
if err != nil {
return fmt.Errorf("[updateStorageProfiles] error removing storage profile %s: %s", spCombo.reference.Name, err)
}
}
return nil
}
// Deletes a VDC, optionally removing all objects in it as well
func resourceVcdVdcDelete(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
vdcName := d.Get("name").(string)
log.Printf("[TRACE] VDC delete started: %s", vdcName)
vcdClient := meta.(*VCDClient)
if !vcdClient.Client.IsSysAdmin {
return diag.Errorf("functionality requires System administrator privileges")
}
adminOrg, err := vcdClient.GetAdminOrgFromResource(d)
if err != nil {
return diag.Errorf(errorRetrievingOrg, err)
}
vdc, err := adminOrg.GetVDCByName(vdcName, false)
if err != nil {
log.Printf("[DEBUG] Unable to find VDC %s. Removing from tfstate", vdcName)
d.SetId("")
return nil
}
err = vdc.DeleteWait(d.Get("delete_force").(bool), d.Get("delete_recursive").(bool))
if err != nil {
log.Printf("[DEBUG] Error removing VDC %s, err: %s", vdcName, err)
return diag.Errorf("error removing VDC %s, err: %s", vdcName, err)
}
_, err = adminOrg.GetVDCByName(vdcName, true)
if err == nil {
return diag.Errorf("vdc %s still found after deletion", vdcName)
}
log.Printf("[TRACE] VDC delete completed: %s", vdcName)
return nil
}
// updateAssignedVmComputePolicies handles VM compute policies.
func updateAssignedVmComputePolicies(d *schema.ResourceData, meta interface{}, vdc *govcd.AdminVdc) error {
vcdClient := meta.(*VCDClient)
defaultPolicyId, vcdComputePolicyHref, err := getDefaultPolicyIdAndComputePolicyHref(d, vcdClient)
if err != nil {
return err
}
if vcdComputePolicyHref == nil || defaultPolicyId == "" {
return nil
}
arePoliciesChanged := d.HasChange("vm_sizing_policy_ids") || d.HasChange("vm_placement_policy_ids") || d.HasChange("vm_vgpu_policy_ids")
isDefaultPolicyChanged := d.HasChange("default_compute_policy_id") || d.HasChange("default_vm_sizing_policy_id")
// Compatibility patch: Remove deprecated `default_vm_sizing_policy_id` from this conditional when the attribute is removed.
// We can do this as `default_compute_policy_id` contains the same value as `default_vm_sizing_policy_id`.
if isDefaultPolicyChanged && !arePoliciesChanged {
vdc.AdminVdc.DefaultComputePolicy = &types.Reference{HREF: vcdComputePolicyHref.String() + defaultPolicyId, ID: defaultPolicyId}
_, err := vdc.Update()
if err != nil {
return fmt.Errorf("error setting default VM Compute Policy. %s", err)
}
return nil
}
if !isDefaultPolicyChanged && arePoliciesChanged {
var vmComputePolicyIds []string
computePolicyAttributes := []string{"vm_sizing_policy_ids", "vm_placement_policy_ids", "vm_vgpu_policy_ids"}
for _, attribute := range computePolicyAttributes {
vmComputePolicyIds = append(vmComputePolicyIds, convertSchemaSetToSliceOfStrings(d.Get(attribute).(*schema.Set))...)
}
if !contains(vmComputePolicyIds, defaultPolicyId) {
return fmt.Errorf("`default_compute_policy_id` %s is not present in any of `%v`", defaultPolicyId, computePolicyAttributes)
}
var vdcComputePolicyReferenceList []*types.Reference
for _, policyId := range vmComputePolicyIds {
vdcComputePolicyReferenceList = append(vdcComputePolicyReferenceList, &types.Reference{HREF: vcdComputePolicyHref.String() + policyId})
}
policyReferences := types.VdcComputePolicyReferences{}
policyReferences.VdcComputePolicyReference = vdcComputePolicyReferenceList
_, err = vdc.SetAssignedComputePolicies(policyReferences)
if err != nil {
return fmt.Errorf("error setting VM Compute Policies. %s", err)
}
return nil
}
err = changeComputePoliciesAndDefaultId(d, vcdClient, vcdComputePolicyHref.String(), vdc)
if err != nil {
return err
}
return nil
}
// changeComputePoliciesAndDefaultId handles Compute policies. Created VDC generates default Compute policy which requires additional handling.
// Assigning and setting default Compute policies requires different API calls. Default policy can't be removed, as result
// we approach this with adding new policies, set new default, remove all old policies.
func changeComputePoliciesAndDefaultId(d *schema.ResourceData, vcdClient *VCDClient, vcdComputePolicyHref string, vdc *govcd.AdminVdc) error {
arePoliciesChanged := d.HasChange("vm_sizing_policy_ids") || d.HasChange("vm_placement_policy_ids") || d.HasChange("vm_vgpu_policy_ids")
isDefaultPolicyChanged := d.HasChange("default_compute_policy_id") || d.HasChange("default_vm_sizing_policy_id")
if !arePoliciesChanged && !isDefaultPolicyChanged {
return nil
}
// Deprecation compatibility: If `default_compute_policy_id` is not set, fallback to deprecated one.
// We can do this as `default_compute_policy_id` contains the same value as `default_vm_sizing_policy_id`.
defaultPolicyId, defaultPolicyIsSet := d.GetOk("default_compute_policy_id")
if !defaultPolicyIsSet {
defaultPolicyId, _ = d.GetOk("default_vm_sizing_policy_id")
}
var vmComputePolicyIds []string
computePolicyAttributes := []string{"vm_sizing_policy_ids", "vm_placement_policy_ids", "vm_vgpu_policy_ids"}
for _, attribute := range computePolicyAttributes {
vmComputePolicyIds = append(vmComputePolicyIds, convertSchemaSetToSliceOfStrings(d.Get(attribute).(*schema.Set))...)
}
if !contains(vmComputePolicyIds, defaultPolicyId.(string)) {
return fmt.Errorf("`default_compute_policy_id` %s is not present in any of `%v`", defaultPolicyId.(string), computePolicyAttributes)
}
var vdcComputePolicyReferenceList []*types.Reference
for _, policyId := range vmComputePolicyIds {
vdcComputePolicyReferenceList = append(vdcComputePolicyReferenceList, &types.Reference{HREF: vcdComputePolicyHref + policyId})
}
existingPolicies, err := vdc.GetAllAssignedVdcComputePoliciesV2(url.Values{
"filter": []string{fmt.Sprintf("%spolicyType==VdcVmPolicy", getVgpuFilterToPrepend(vcdClient, false))}, // Filtering out vGPU Policies as there's no attribute support yet.
})
if err != nil {
return fmt.Errorf("error getting Compute Policies. %s", err)
}
for _, existingPolicy := range existingPolicies {
vdcComputePolicyReferenceList = append(vdcComputePolicyReferenceList, &types.Reference{HREF: vcdComputePolicyHref + existingPolicy.VdcComputePolicyV2.ID})
}
policyReferences := types.VdcComputePolicyReferences{}
policyReferences.VdcComputePolicyReference = vdcComputePolicyReferenceList
_, err = vdc.SetAssignedComputePolicies(policyReferences)
if err != nil {
return fmt.Errorf("error setting Compute Policies. %s", err)
}