-
Notifications
You must be signed in to change notification settings - Fork 16
/
resource_security_group.go
384 lines (332 loc) · 11.3 KB
/
resource_security_group.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
package main
import (
"errors"
"fmt"
"github.com/hashicorp/terraform/helper/schema"
"github.com/sky-uk/gonsx"
"github.com/sky-uk/gonsx/api/securitygroup"
"log"
)
func getSingleSecurityGroup(scopeID, name string, nsxclient *gonsx.NSXClient) (*securitygroup.SecurityGroup, error) {
getAllAPI := securitygroup.NewGetAll(scopeID)
err := nsxclient.Do(getAllAPI)
if err != nil {
return nil, err
}
if getAllAPI.StatusCode() != 200 {
return nil, fmt.Errorf("Status code: %d, Response: %s", getAllAPI.StatusCode(), getAllAPI.ResponseObject())
}
securityGroup := getAllAPI.GetResponse().FilterByName(name)
return securityGroup, nil
}
func resourceSecurityGroup() *schema.Resource {
return &schema.Resource{
Create: resourceSecurityGroupCreate,
Read: resourceSecurityGroupRead,
Update: resourceSecurityGroupUpdate,
Delete: resourceSecurityGroupDelete,
Schema: map[string]*schema.Schema{
"scopeid": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"dynamic_membership": &schema.Schema{
Type: schema.TypeList,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"set_operator": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateSecurityGroupSetOperator,
},
"rules_operator": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateSecurityGroupRulesOperator,
},
"rules": &schema.Schema{
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateSecurityGroupRuleKey,
},
"value": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"criteria": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateSecurityGroupRuleCriteria,
},
},
},
},
},
},
},
},
}
}
func validateSecurityGroupSetOperator(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if value != "OR" && value != "AND" {
errors = append(errors, fmt.Errorf("%q must be one of \"OR\" or \"AND\" ", k))
}
return
}
func validateSecurityGroupRulesOperator(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if value != "OR" && value != "AND" {
errors = append(errors, fmt.Errorf("%q must be one of \"OR\" or \"AND\" ", k))
}
return
}
func validateSecurityGroupRuleKey(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
keyTypes := map[string]bool{
"VM.SECURITY_TAG": true,
"VM.GUEST_OS_FULL_NAME": true,
"VM.GUEST_HOST_NAME": true,
"VM.NAME": true,
"ENTITY": true,
}
if !keyTypes[value] {
errors = append(errors, fmt.Errorf("%q must be a valid key, check documentation for acceptable values", k))
}
return
}
func validateSecurityGroupRuleCriteria(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
possibleCriteriaValues := map[string]bool{
"belongs_to": true,
"starts_with": true,
"ends_with": true,
"=": true,
"!=": true,
"contains": true,
"similar_to": true,
}
if !possibleCriteriaValues[value] {
errors = append(errors, fmt.Errorf("%q must be a valid criteria value, check documentation for acceptable values", k))
}
return
}
func buildDynamicMemberDefinition(m interface{}) (securitygroup.DynamicMemberDefinition, error) {
var newDynamicMemberDefinition securitygroup.DynamicMemberDefinition
dynamicSetList := make([]securitygroup.DynamicSet, len(m.([]interface{})))
for index, v := range m.([]interface{}) {
data := v.(map[string]interface{})
dynamicRulesList, err := buildDynamicRules(data["rules"], data["rules_operator"].(string))
if err != nil {
return newDynamicMemberDefinition, err
}
dynamicSetList[index].Operator = data["set_operator"].(string)
dynamicSetList[index].DynamicCriteria = dynamicRulesList
log.Printf(fmt.Sprintf("[DEBUG] DynamicSetList: %v", dynamicSetList))
}
newDynamicMemberDefinition.DynamicSet = dynamicSetList
return newDynamicMemberDefinition, nil
}
func buildDynamicRules(m interface{}, rulesOperator string) ([]securitygroup.DynamicCriteria, error) {
newDynamicCriterion := make([]securitygroup.DynamicCriteria, len(m.(*schema.Set).List()))
for index, value := range m.(*schema.Set).List() {
dynamicCriterion := value.(map[string]interface{})
newDynamicCriterion[index].Operator = rulesOperator
newDynamicCriterion[index].Key = dynamicCriterion["key"].(string)
newDynamicCriterion[index].Value = dynamicCriterion["value"].(string)
newDynamicCriterion[index].Criteria = dynamicCriterion["criteria"].(string)
}
return newDynamicCriterion, nil
}
func resourceSecurityGroupCreate(d *schema.ResourceData, m interface{}) error {
nsxclient := m.(*gonsx.NSXClient)
var scopeid, name string
var dynamicMemberDefinition securitygroup.DynamicMemberDefinition
var err error
// Gather the attributes for the resource.
if v, ok := d.GetOk("scopeid"); ok {
scopeid = v.(string)
} else {
return errors.New("scopeid argument is required")
}
if v, ok := d.GetOk("name"); ok {
name = v.(string)
} else {
return errors.New("name argument is required")
}
if v, ok := d.GetOk("dynamic_membership"); ok {
log.Printf(fmt.Sprintf("[DEBUG] dynamic_membership create : %+v", v))
dynamicMemberDefinition, err = buildDynamicMemberDefinition(v)
if err != nil {
return err
}
//dynamicMemberDefinition, err = getDynamicMemberDefinitionFromTemplate(v)
} else {
return errors.New("dynamicmembership list is required")
}
log.Printf(fmt.Sprintf("[DEBUG] securitygroup.NewCreate(%s, %s, %v", scopeid, name, dynamicMemberDefinition))
createAPI := securitygroup.NewCreate(scopeid, name, &dynamicMemberDefinition)
err = nsxclient.Do(createAPI)
if err != nil {
return fmt.Errorf("Error creating security group: %v", err)
}
if createAPI.StatusCode() != 201 {
return fmt.Errorf("%s", createAPI.ResponseObject())
}
d.SetId(createAPI.GetResponse())
return resourceSecurityGroupRead(d, m)
}
func resourceSecurityGroupRead(d *schema.ResourceData, m interface{}) error {
nsxclient := m.(*gonsx.NSXClient)
var dynamicMembership securitygroup.DynamicMemberDefinition
var scopeid, name string
var err error
if v, ok := d.GetOk("scopeid"); ok {
scopeid = v.(string)
} else {
return errors.New("scopeid argument is required")
}
if v, ok := d.GetOk("name"); ok {
name = v.(string)
} else {
return errors.New("name argument is required")
}
if v, ok := d.GetOk("dynamic_membership"); ok {
dynamicMembership, err = buildDynamicMemberDefinition(v)
if err != nil {
return err
}
} else {
return errors.New("dynamic_membership is required")
}
// See if we can find our specifically named resource within the list of
// resources associated with the scopeid.
log.Printf(fmt.Sprintf("[DEBUG] api.GetResponse().FilterByName(\"%s\").ObjectID", name))
securityGroupObject, err := getSingleSecurityGroup(scopeid, name, nsxclient)
if err != nil {
return err
}
id := securityGroupObject.ObjectID
log.Printf(fmt.Sprintf("[DEBUG] id := %s", id))
// If the resource has been removed manually, notify Terraform of this fact.
if id == "" {
d.SetId("")
return nil
}
log.Printf(fmt.Sprintf("[DEBUG] dynamicMembership := %v", securityGroupObject.DynamicMemberDefinition))
for idx, remoteDynamicSet := range securityGroupObject.DynamicMemberDefinition.DynamicSet {
dynamicMembership.DynamicSet[idx].Operator = remoteDynamicSet.Operator
readDynamicCriteria(dynamicMembership.DynamicSet[idx].DynamicCriteria,
remoteDynamicSet.DynamicCriteria)
}
d.Set("dynamic_membership", dynamicMembership)
return nil
}
func readDynamicCriteria(localCriteriaList, remoteCriteriaList []securitygroup.DynamicCriteria) {
for _, localRule := range localCriteriaList {
for _, remoteRule := range remoteCriteriaList {
if localRule.Value == remoteRule.Value {
localRule.Criteria = remoteRule.Criteria
localRule.Key = remoteRule.Key
break
}
}
}
}
func resourceSecurityGroupUpdate(d *schema.ResourceData, m interface{}) error {
var scopeid string
var dynamicMembership securitygroup.DynamicMemberDefinition
var err error
nsxclient := m.(*gonsx.NSXClient)
hasChanges := false
if v, ok := d.GetOk("scopeid"); ok {
scopeid = v.(string)
} else {
return errors.New("scopeid argument is required")
}
log.Printf(fmt.Sprintf("[DEBUG] securitygroup.NewGetAll(%s)", scopeid))
oldName, newName := d.GetChange("name")
securityGroupObject, err := getSingleSecurityGroup(scopeid, oldName.(string), nsxclient)
id := securityGroupObject.ObjectID
//TODO: change attributes other than name. Requires changes in gonsx.
if d.HasChange("name") {
hasChanges = true
securityGroupObject.Name = newName.(string)
log.Printf(fmt.Sprintf("[DEBUG] Changing name of security group from %s to %s", oldName.(string), newName.(string)))
}
if d.HasChange("dynamic_membership") {
if v, ok := d.GetOk("dynamic_membership"); ok {
dynamicMembership, err = buildDynamicMemberDefinition(v)
if err != nil {
return err
}
}
hasChanges = true
securityGroupObject.DynamicMemberDefinition = &dynamicMembership
}
if hasChanges {
updateAPI := securitygroup.NewUpdate(id, securityGroupObject)
err = nsxclient.Do(updateAPI)
if err != nil {
log.Printf(fmt.Sprintf("[DEBUG] Error updating security group: %s", err))
}
}
return resourceSecurityGroupRead(d, m)
}
func resourceSecurityGroupDelete(d *schema.ResourceData, m interface{}) error {
nsxclient := m.(*gonsx.NSXClient)
var name, scopeid string
// Gather the attributes for the resource.
if v, ok := d.GetOk("scopeid"); ok {
scopeid = v.(string)
} else {
return errors.New("scopeid argument is required")
}
if v, ok := d.GetOk("name"); ok {
name = v.(string)
} else {
return errors.New("name argument is required")
}
// Gather all the resources that are associated with the specified
// scopeid.
log.Printf(fmt.Sprintf("[DEBUG] securitygroup.NewGetAll(%s)", scopeid))
api := securitygroup.NewGetAll(scopeid)
err := nsxclient.Do(api)
if err != nil {
return err
}
// See if we can find our specifically named resource within the list of
// resources associated with the scopeid.
log.Printf(fmt.Sprintf("[DEBUG] api.GetResponse().FilterByName(\"%s\").ObjectID", name))
securityGroupObject, err := getSingleSecurityGroup(scopeid, name, nsxclient)
id := securityGroupObject.ObjectID
log.Printf(fmt.Sprintf("[DEBUG] id := %s", id))
// If the resource has been removed manually, notify Terraform of this fact.
if id == "" {
d.SetId("")
return nil
}
// If we got here, the resource exists, so we attempt to delete it.
deleteAPI := securitygroup.NewDelete(id)
err = nsxclient.Do(deleteAPI)
if err != nil {
return err
}
// If we got here, the resource had existed, we deleted it and there was
// no error. Notify Terraform of this fact and return successful
// completion.
d.SetId("")
log.Printf(fmt.Sprintf("[DEBUG] id %s deleted.", id))
return nil
}