forked from hashicorp/terraform-provider-vsphere
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_vsphere_compute_cluster_vm_dependency_rule.go
423 lines (367 loc) · 14.6 KB
/
resource_vsphere_compute_cluster_vm_dependency_rule.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
package vsphere
import (
"encoding/json"
"errors"
"fmt"
"log"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/clustercomputeresource"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/structure"
"github.com/terraform-providers/terraform-provider-vsphere/vsphere/internal/helper/viapi"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
)
const resourceVSphereComputeClusterVMDependencyRuleName = "vsphere_compute_cluster_vm_dependency_rule"
func resourceVSphereComputeClusterVMDependencyRule() *schema.Resource {
return &schema.Resource{
Create: resourceVSphereComputeClusterVMDependencyRuleCreate,
Read: resourceVSphereComputeClusterVMDependencyRuleRead,
Update: resourceVSphereComputeClusterVMDependencyRuleUpdate,
Delete: resourceVSphereComputeClusterVMDependencyRuleDelete,
Importer: &schema.ResourceImporter{
State: resourceVSphereComputeClusterVMDependencyRuleImport,
},
Schema: map[string]*schema.Schema{
"compute_cluster_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The managed object ID of the cluster.",
},
"name": {
Type: schema.TypeString,
Required: true,
Description: "The unique name of the virtual machine group in the cluster.",
},
"dependency_vm_group_name": {
Type: schema.TypeString,
Required: true,
Description: "The name of the VM group that this rule depends on. The VMs defined in the group specified by vm_group_name will not be started until the VMs in this group are started.",
},
"vm_group_name": {
Type: schema.TypeString,
Required: true,
Description: "The name of the VM group that is the subject of this rule. The VMs defined in this group will not be started until the VMs in the group specified by dependency_vm_group_name are started.",
},
"enabled": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Enable this rule in the cluster.",
},
"mandatory": {
Type: schema.TypeBool,
Optional: true,
Description: "When true, prevents any virtual machine operations that may violate this rule.",
},
},
}
}
func resourceVSphereComputeClusterVMDependencyRuleCreate(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] %s: Beginning create", resourceVSphereComputeClusterVMDependencyRuleIDString(d))
cluster, _, err := resourceVSphereComputeClusterVMDependencyRuleObjects(d, meta)
if err != nil {
return err
}
info, err := expandClusterDependencyRuleInfo(d)
if err != nil {
return err
}
spec := &types.ClusterConfigSpecEx{
RulesSpec: []types.ClusterRuleSpec{
{
ArrayUpdateSpec: types.ArrayUpdateSpec{
Operation: types.ArrayUpdateOperationAdd,
},
Info: info,
},
},
}
if err = clustercomputeresource.Reconfigure(cluster, spec); err != nil {
return err
}
info, err = resourceVSphereComputeClusterVMDependencyRuleFindEntryByName(cluster, info.Name)
if err != nil {
return err
}
id, err := resourceVSphereComputeClusterVMDependencyRuleFlattenID(cluster, info.Key)
if err != nil {
return fmt.Errorf("cannot compute ID of created resource: %s", err)
}
d.SetId(id)
log.Printf("[DEBUG] %s: Create finished successfully", resourceVSphereComputeClusterVMDependencyRuleIDString(d))
return resourceVSphereComputeClusterVMDependencyRuleRead(d, meta)
}
func resourceVSphereComputeClusterVMDependencyRuleRead(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] %s: Beginning read", resourceVSphereComputeClusterVMDependencyRuleIDString(d))
cluster, key, err := resourceVSphereComputeClusterVMDependencyRuleObjects(d, meta)
if err != nil {
return err
}
info, err := resourceVSphereComputeClusterVMDependencyRuleFindEntry(cluster, key)
if err != nil {
return err
}
if info == nil {
// The configuration is missing, blank out the ID so it can be re-created.
d.SetId("")
return nil
}
// Save the compute_cluster_id. This is ForceNew, but we set these for
// completeness on import so that if the wrong cluster/VM combo was used, it
// will be noted.
if err = d.Set("compute_cluster_id", cluster.Reference().Value); err != nil {
return fmt.Errorf("error setting attribute \"compute_cluster_id\": %s", err)
}
if err = flattenClusterDependencyRuleInfo(d, info); err != nil {
return err
}
log.Printf("[DEBUG] %s: Read completed successfully", resourceVSphereComputeClusterVMDependencyRuleIDString(d))
return nil
}
func resourceVSphereComputeClusterVMDependencyRuleUpdate(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] %s: Beginning update", resourceVSphereComputeClusterVMDependencyRuleIDString(d))
cluster, key, err := resourceVSphereComputeClusterVMDependencyRuleObjects(d, meta)
if err != nil {
return err
}
info, err := expandClusterDependencyRuleInfo(d)
if err != nil {
return err
}
info.Key = key
spec := &types.ClusterConfigSpecEx{
RulesSpec: []types.ClusterRuleSpec{
{
ArrayUpdateSpec: types.ArrayUpdateSpec{
Operation: types.ArrayUpdateOperationEdit,
},
Info: info,
},
},
}
if err := clustercomputeresource.Reconfigure(cluster, spec); err != nil {
return err
}
log.Printf("[DEBUG] %s: Update finished successfully", resourceVSphereComputeClusterVMDependencyRuleIDString(d))
return resourceVSphereComputeClusterVMDependencyRuleRead(d, meta)
}
func resourceVSphereComputeClusterVMDependencyRuleDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[DEBUG] %s: Beginning delete", resourceVSphereComputeClusterVMDependencyRuleIDString(d))
cluster, key, err := resourceVSphereComputeClusterVMDependencyRuleObjects(d, meta)
if err != nil {
return err
}
spec := &types.ClusterConfigSpecEx{
RulesSpec: []types.ClusterRuleSpec{
{
ArrayUpdateSpec: types.ArrayUpdateSpec{
Operation: types.ArrayUpdateOperationRemove,
RemoveKey: key,
},
},
},
}
if err := clustercomputeresource.Reconfigure(cluster, spec); err != nil {
return err
}
log.Printf("[DEBUG] %s: Deleted successfully", resourceVSphereComputeClusterVMDependencyRuleIDString(d))
return nil
}
func resourceVSphereComputeClusterVMDependencyRuleImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
var data map[string]string
if err := json.Unmarshal([]byte(d.Id()), &data); err != nil {
return nil, err
}
clusterPath, ok := data["compute_cluster_path"]
if !ok {
return nil, errors.New("missing compute_cluster_path in input data")
}
name, ok := data["name"]
if !ok {
return nil, errors.New("missing name in input data")
}
client, err := resourceVSphereComputeClusterVMDependencyRuleClient(meta)
if err != nil {
return nil, err
}
cluster, err := clustercomputeresource.FromPath(client, clusterPath, nil)
if err != nil {
return nil, fmt.Errorf("cannot locate cluster %q: %s", clusterPath, err)
}
info, err := resourceVSphereComputeClusterVMDependencyRuleFindEntryByName(cluster, name)
if err != nil {
return nil, err
}
id, err := resourceVSphereComputeClusterVMDependencyRuleFlattenID(cluster, info.Key)
if err != nil {
return nil, fmt.Errorf("cannot compute ID of imported resource: %s", err)
}
d.SetId(id)
return []*schema.ResourceData{d}, nil
}
// expandClusterDependencyRuleInfo reads certain ResourceData keys and returns a
// ClusterDependencyRuleInfo.
func expandClusterDependencyRuleInfo(d *schema.ResourceData) (*types.ClusterDependencyRuleInfo, error) {
obj := &types.ClusterDependencyRuleInfo{
ClusterRuleInfo: types.ClusterRuleInfo{
Enabled: structure.GetBool(d, "enabled"),
Mandatory: structure.GetBool(d, "mandatory"),
Name: d.Get("name").(string),
UserCreated: structure.BoolPtr(true),
},
DependsOnVmGroup: d.Get("dependency_vm_group_name").(string),
VmGroup: d.Get("vm_group_name").(string),
}
return obj, nil
}
// flattenClusterDependencyRuleInfo saves a ClusterDependencyRuleInfo into the supplied ResourceData.
func flattenClusterDependencyRuleInfo(d *schema.ResourceData, obj *types.ClusterDependencyRuleInfo) error {
return structure.SetBatch(d, map[string]interface{}{
"enabled": obj.Enabled,
"mandatory": obj.Mandatory,
"name": obj.Name,
"dependency_vm_group_name": obj.DependsOnVmGroup,
"vm_group_name": obj.VmGroup,
})
}
// resourceVSphereComputeClusterVMDependencyRuleIDString prints a friendly string for the
// vsphere_compute_cluster_vm_dependency_rule resource.
func resourceVSphereComputeClusterVMDependencyRuleIDString(d structure.ResourceIDStringer) string {
return structure.ResourceIDString(d, resourceVSphereComputeClusterVMDependencyRuleName)
}
// resourceVSphereComputeClusterVMDependencyRuleFlattenID makes an ID for the
// vsphere_compute_cluster_vm_dependency_rule resource.
func resourceVSphereComputeClusterVMDependencyRuleFlattenID(cluster *object.ClusterComputeResource, key int32) (string, error) {
clusterID := cluster.Reference().Value
return strings.Join([]string{clusterID, strconv.Itoa(int(key))}, ":"), nil
}
// resourceVSphereComputeClusterVMDependencyRuleParseID parses an ID for the
// vsphere_compute_cluster_vm_dependency_rule and outputs its parts.
func resourceVSphereComputeClusterVMDependencyRuleParseID(id string) (string, int32, error) {
parts := strings.SplitN(id, ":", 3)
if len(parts) < 2 {
return "", 0, fmt.Errorf("bad ID %q", id)
}
key, err := strconv.Atoi(parts[1])
if err != nil {
return "", 0, fmt.Errorf("bad key in ID %q: %s", parts[1], err)
}
return parts[0], int32(key), nil
}
// resourceVSphereComputeClusterVMDependencyRuleFindEntry attempts to locate an
// existing VM dependency rule in a cluster's configuration by key. It's used by the
// resource's read functionality and tests. nil is returned if the entry cannot
// be found.
func resourceVSphereComputeClusterVMDependencyRuleFindEntry(
cluster *object.ClusterComputeResource,
key int32,
) (*types.ClusterDependencyRuleInfo, error) {
props, err := clustercomputeresource.Properties(cluster)
if err != nil {
return nil, fmt.Errorf("error fetching cluster properties: %s", err)
}
for _, info := range props.ConfigurationEx.(*types.ClusterConfigInfoEx).Rule {
if info.GetClusterRuleInfo().Key == key {
if vmDependencyRuleInfo, ok := info.(*types.ClusterDependencyRuleInfo); ok {
log.Printf("[DEBUG] Found VM dependency rule key %d in cluster %q", key, cluster.Name())
return vmDependencyRuleInfo, nil
}
return nil, fmt.Errorf("rule key %d in cluster %q is not a VM dependency rule", key, cluster.Name())
}
}
log.Printf("[DEBUG] No VM dependency rule key %d found in cluster %q", key, cluster.Name())
return nil, nil
}
// resourceVSphereComputeClusterVMDependencyRuleFindEntryByName attempts to locate an
// existing VM dependency rule in a cluster's configuration by name. It differs from
// the standard resourceVSphereComputeClusterVMDependencyRuleFindEntry in that we
// don't allow missing entries, as it's designed to be used in places where we
// don't want to allow for missing entries, such as during creation and import.
func resourceVSphereComputeClusterVMDependencyRuleFindEntryByName(
cluster *object.ClusterComputeResource,
name string,
) (*types.ClusterDependencyRuleInfo, error) {
props, err := clustercomputeresource.Properties(cluster)
if err != nil {
return nil, fmt.Errorf("error fetching cluster properties: %s", err)
}
for _, info := range props.ConfigurationEx.(*types.ClusterConfigInfoEx).Rule {
if info.GetClusterRuleInfo().Name == name {
if vmDependencyRuleInfo, ok := info.(*types.ClusterDependencyRuleInfo); ok {
log.Printf("[DEBUG] Found VM dependency rule %q in cluster %q", name, cluster.Name())
return vmDependencyRuleInfo, nil
}
return nil, fmt.Errorf("rule %q in cluster %q is not a VM dependency rule", name, cluster.Name())
}
}
return nil, fmt.Errorf("no VM dependency rule %q found in cluster %q", name, cluster.Name())
}
// resourceVSphereComputeClusterVMDependencyRuleObjects handles the fetching of the
// cluster and rule key depending on what attributes are available:
// * If the resource ID is available, the data is derived from the ID.
// * If not, only the cluster is retrieved from compute_cluster_id. -1 is
// returned for the key.
func resourceVSphereComputeClusterVMDependencyRuleObjects(
d *schema.ResourceData,
meta interface{},
) (*object.ClusterComputeResource, int32, error) {
if d.Id() != "" {
return resourceVSphereComputeClusterVMDependencyRuleObjectsFromID(d, meta)
}
return resourceVSphereComputeClusterVMDependencyRuleObjectsFromAttributes(d, meta)
}
func resourceVSphereComputeClusterVMDependencyRuleObjectsFromAttributes(
d *schema.ResourceData,
meta interface{},
) (*object.ClusterComputeResource, int32, error) {
return resourceVSphereComputeClusterVMDependencyRuleFetchObjects(
meta,
d.Get("compute_cluster_id").(string),
-1,
)
}
func resourceVSphereComputeClusterVMDependencyRuleObjectsFromID(
d structure.ResourceIDStringer,
meta interface{},
) (*object.ClusterComputeResource, int32, error) {
// Note that this function uses structure.ResourceIDStringer to satisfy
// interfacer. Adding exceptions in the comments does not seem to work.
// Change this back to ResourceData if it's needed in the future.
clusterID, key, err := resourceVSphereComputeClusterVMDependencyRuleParseID(d.Id())
if err != nil {
return nil, 0, err
}
return resourceVSphereComputeClusterVMDependencyRuleFetchObjects(meta, clusterID, key)
}
// resourceVSphereComputeClusterVMDependencyRuleFetchObjects fetches the "objects"
// for a cluster rule. This is currently just the cluster object as the rule
// key a static value and a pass-through - this is to keep its workflow
// consistent with other cluster-dependent resources that derive from
// ArrayUpdateSpec that have managed object as keys, such as VM and host
// overrides.
func resourceVSphereComputeClusterVMDependencyRuleFetchObjects(
meta interface{},
clusterID string,
key int32,
) (*object.ClusterComputeResource, int32, error) {
client, err := resourceVSphereComputeClusterVMDependencyRuleClient(meta)
if err != nil {
return nil, 0, err
}
cluster, err := clustercomputeresource.FromID(client, clusterID)
if err != nil {
return nil, 0, fmt.Errorf("cannot locate cluster: %s", err)
}
return cluster, key, nil
}
func resourceVSphereComputeClusterVMDependencyRuleClient(meta interface{}) (*govmomi.Client, error) {
client := meta.(*VSphereClient).vimClient
if err := viapi.ValidateVirtualCenter(client); err != nil {
return nil, err
}
return client, nil
}