forked from hashicorp/terraform-provider-vsphere
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_vsphere_license.go
254 lines (206 loc) · 6.25 KB
/
resource_vsphere_license.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
package vsphere
import (
"errors"
"fmt"
"log"
"context"
"github.com/hashicorp/terraform/helper/schema"
"github.com/vmware/govmomi/license"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
var (
// ErrNoSuchKeyFound is an error primarily thrown by the Read method of the resource.
// The error doesn't display the key itself for security reasons.
ErrNoSuchKeyFound = errors.New("The key was not found")
// ErrKeyCannotBeDeleted is an error which occurs when a key that is used by VMs is
// being removed
ErrKeyCannotBeDeleted = errors.New("The key wasn't deleted")
)
func resourceVSphereLicense() *schema.Resource {
return &schema.Resource{
SchemaVersion: 1,
Create: resourceVSphereLicenseCreate,
Read: resourceVSphereLicenseRead,
Update: resourceVSphereLicenseUpdate,
Delete: resourceVSphereLicenseDelete,
Schema: map[string]*schema.Schema{
"license_key": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"labels": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
},
// computed properties returned by the API
"edition_key": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"total": &schema.Schema{
Type: schema.TypeInt,
Computed: true,
},
"used": &schema.Schema{
Type: schema.TypeInt,
Computed: true,
},
},
}
}
func resourceVSphereLicenseCreate(d *schema.ResourceData, meta interface{}) error {
log.Println("[INFO] Running the create method")
client := meta.(*VSphereClient).vimClient
manager := license.NewManager(client.Client)
key := d.Get("license_key").(string)
log.Println(" [INFO] Reading the key from the resource data")
var labelMap map[string]interface{}
if labels, ok := d.GetOk("labels"); ok {
labelMap = labels.(map[string]interface{})
}
var info types.LicenseManagerLicenseInfo
var err error
switch t := client.ServiceContent.About.ApiType; t {
case "HostAgent":
// Labels are not allowed in ESXi
if len(labelMap) != 0 {
return errors.New("Labels are not allowed in ESXi")
}
info, err = manager.Update(context.TODO(), key, nil)
case "VirtualCenter":
info, err = manager.Add(context.TODO(), key, nil)
if err != nil {
return err
}
err = updateLabels(manager, key, labelMap)
default:
return fmt.Errorf("unsupported ApiType: %s", t)
}
if err != nil {
return err
}
if err = DecodeError(info); err != nil {
return err
}
// This can be used in the read method to set the computed parameters
d.SetId(info.LicenseKey)
return resourceVSphereLicenseRead(d, meta)
}
func resourceVSphereLicenseRead(d *schema.ResourceData, meta interface{}) error {
log.Println("[INFO] Running the read method")
client := meta.(*VSphereClient).vimClient
manager := license.NewManager(client.Client)
if info := getLicenseInfoFromKey(d.Get("license_key").(string), manager); info != nil {
log.Println("[INFO] Setting the values")
d.Set("edition_key", info.EditionKey)
d.Set("total", info.Total)
d.Set("used", info.Used)
d.Set("name", info.Name)
d.Set("labels", keyValuesToMap(info.Labels))
} else {
return ErrNoSuchKeyFound
}
return nil
}
// resourceVSphereLicenseUpdate check for change in labels of the key and updates them.
func resourceVSphereLicenseUpdate(d *schema.ResourceData, meta interface{}) error {
log.Println("[INFO] Running the update method")
client := meta.(*VSphereClient).vimClient
manager := license.NewManager(client.Client)
if key, ok := d.GetOk("license_key"); ok {
licenseKey := key.(string)
if !isKeyPresent(licenseKey, manager) {
return ErrNoSuchKeyFound
}
if d.HasChange("labels") {
labelMap := d.Get("labels").(map[string]interface{})
err := updateLabels(manager, licenseKey, labelMap)
if err != nil {
return err
}
}
}
return resourceVSphereLicenseRead(d, meta)
}
func updateLabels(manager *license.Manager, licenseKey string, labelMap map[string]interface{}) error {
for key, value := range labelMap {
err := UpdateLabel(context.TODO(), manager, licenseKey, key, value.(string))
if err != nil {
return err
}
}
return nil
}
func resourceVSphereLicenseDelete(d *schema.ResourceData, meta interface{}) error {
log.Println("[INFO] Running the delete method")
client := meta.(*VSphereClient).vimClient
manager := license.NewManager(client.Client)
if key := d.Get("license_key").(string); isKeyPresent(key, manager) {
err := manager.Remove(context.TODO(), key)
if err != nil {
return err
}
// if the key is still present
if isKeyPresent(key, manager) {
return ErrKeyCannotBeDeleted
}
d.SetId("")
return nil
}
return ErrNoSuchKeyFound
}
func getLicenseInfoFromKey(key string, manager *license.Manager) *types.LicenseManagerLicenseInfo {
// Use of decode is not returning labels so using list instead
// Issue - https://github.com/vmware/govmomi/issues/797
infoList, _ := manager.List(context.TODO())
for _, info := range infoList {
if info.LicenseKey == key {
return &info
}
}
return nil
}
// isKeyPresent iterates over the InfoList to check if the license is present or not.
func isKeyPresent(key string, manager *license.Manager) bool {
infoList, _ := manager.List(context.TODO())
for _, info := range infoList {
if info.LicenseKey == key {
return true
}
}
return false
}
// UpdateLabel provides a wrapper around the UpdateLabel data objects
func UpdateLabel(ctx context.Context, m *license.Manager, licenseKey string, key string, val string) error {
req := types.UpdateLicenseLabel{
This: m.Reference(),
LicenseKey: licenseKey,
LabelKey: key,
LabelValue: val,
}
_, err := methods.UpdateLicenseLabel(ctx, m.Client(), &req)
return err
}
// DecodeError tries to find a specific error which occurs when an invalid key is passed
// to the server
func DecodeError(info types.LicenseManagerLicenseInfo) error {
for _, property := range info.Properties {
if property.Key == "diagnostic" {
return errors.New(property.Value.(string))
}
}
return nil
}
func keyValuesToMap(keyValues []types.KeyValue) map[string]interface{} {
KVMap := make(map[string]interface{})
for _, keyValue := range keyValues {
KVMap[keyValue.Key] = keyValue.Value
}
return KVMap
}