/
resource_ibm_is_security_group_rule.go
469 lines (431 loc) · 13.5 KB
/
resource_ibm_is_security_group_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
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
package ibm
import (
"fmt"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.ibm.com/Bluemix/riaas-go-client/clients/network"
iserrors "github.ibm.com/Bluemix/riaas-go-client/errors"
"github.ibm.com/Bluemix/riaas-go-client/riaas/models"
)
const (
isSecurityGroupRuleCode = "code"
isSecurityGroupRuleDirection = "direction"
isSecurityGroupRuleIPVersion = "ip_version"
isSecurityGroupRuleIPVersionDefault = "ipv4"
isSecurityGroupRulePortMax = "port_max"
isSecurityGroupRulePortMin = "port_min"
isSecurityGroupRuleProtocolICMP = "icmp"
isSecurityGroupRuleProtocolTCP = "tcp"
isSecurityGroupRuleProtocolUDP = "udp"
isSecurityGroupRuleProtocol = "protocol"
isSecurityGroupRuleRemote = "remote"
isSecurityGroupRuleType = "type"
isSecurityGroupID = "group"
isSecurityGroupRuleID = "rule_id"
)
func resourceIBMISSecurityGroupRule() *schema.Resource {
return &schema.Resource{
Create: resourceIBMISSecurityGroupRuleCreate,
Read: resourceIBMISSecurityGroupRuleRead,
Update: resourceIBMISSecurityGroupRuleUpdate,
Delete: resourceIBMISSecurityGroupRuleDelete,
Exists: resourceIBMISSecurityGroupRuleExists,
Importer: &schema.ResourceImporter{},
Schema: map[string]*schema.Schema{
isSecurityGroupID: {
Type: schema.TypeString,
Required: true,
Description: "Security group id",
ForceNew: true,
},
isSecurityGroupRuleID: {
Type: schema.TypeString,
Computed: true,
Description: "Rule id",
},
isSecurityGroupRuleDirection: {
Type: schema.TypeString,
Required: true,
Description: "Direction of traffic to enforce, either inbound or outbound",
ValidateFunc: validateIsSecurityRuleDirection,
},
isSecurityGroupRuleIPVersion: {
Type: schema.TypeString,
Optional: true,
Description: "IP version: ipv4 or ipv6",
Default: isSecurityGroupRuleIPVersionDefault,
ValidateFunc: validateIPVersion,
},
isSecurityGroupRuleRemote: {
Type: schema.TypeString,
Optional: true,
Description: "Security group id: an IP address, a CIDR block, or a single security group identifier",
},
isSecurityGroupRuleProtocolICMP: {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
ForceNew: true,
MinItems: 1,
ConflictsWith: []string{isSecurityGroupRuleProtocolTCP, isSecurityGroupRuleProtocolUDP},
Description: "protocol=icmp",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
isSecurityGroupRuleType: {
Type: schema.TypeInt,
Optional: true,
ForceNew: false,
ValidateFunc: validateICMPType,
},
isSecurityGroupRuleCode: {
Type: schema.TypeInt,
Optional: true,
ForceNew: false,
ValidateFunc: validateICMPCode,
},
},
},
},
isSecurityGroupRuleProtocolTCP: {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
MinItems: 1,
ForceNew: true,
Description: "protocol=tcp",
ConflictsWith: []string{isSecurityGroupRuleProtocolUDP, isSecurityGroupRuleProtocolICMP},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
isSecurityGroupRulePortMin: {
Type: schema.TypeInt,
Optional: true,
ForceNew: false,
ValidateFunc: validateISSecurityRulePort,
},
isSecurityGroupRulePortMax: {
Type: schema.TypeInt,
Optional: true,
ForceNew: false,
ValidateFunc: validateISSecurityRulePort,
},
},
},
},
isSecurityGroupRuleProtocolUDP: {
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
ForceNew: true,
MinItems: 1,
Description: "protocol=udp",
ConflictsWith: []string{isSecurityGroupRuleProtocolTCP, isSecurityGroupRuleProtocolICMP},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
isSecurityGroupRulePortMin: {
Type: schema.TypeInt,
Optional: true,
ForceNew: false,
ValidateFunc: validateISSecurityRulePort,
},
isSecurityGroupRulePortMax: {
Type: schema.TypeInt,
Optional: true,
ForceNew: false,
ValidateFunc: validateISSecurityRulePort,
},
},
},
},
},
}
}
func resourceIBMISSecurityGroupRuleCreate(d *schema.ResourceData, meta interface{}) error {
parsed, err := parseIBMISSecurityGroupRuleDictionary(d, "create")
if err != nil {
return err
}
isSecurityGroupRuleKey := "security_group_rule_key_" + parsed.secgrpID
ibmMutexKV.Lock(isSecurityGroupRuleKey)
defer ibmMutexKV.Unlock(isSecurityGroupRuleKey)
sess, err := meta.(ClientSession).ISSession()
if err != nil {
return err
}
sgC := network.NewSecurityGroupClient(sess)
rule, err := sgC.AddRule(parsed.secgrpID, parsed.direction, parsed.ipversion, parsed.protocol,
parsed.remoteAddress, parsed.remoteCIDR, parsed.remoteSecGrpID,
parsed.icmpType, parsed.icmpCode, parsed.portMin, parsed.portMax)
if err != nil {
return err
}
d.Set(isSecurityGroupRuleID, rule.ID.String())
tfID := makeTerraformRuleID(parsed.secgrpID, rule.ID.String())
d.SetId(tfID)
err = resourceIBMISSecurityGroupRuleRead(d, meta)
return err
}
func resourceIBMISSecurityGroupRuleRead(d *schema.ResourceData, meta interface{}) error {
sess, err := meta.(ClientSession).ISSession()
if err != nil {
return err
}
sgC := network.NewSecurityGroupClient(sess)
secgrpID, ruleID, err := parseISTerraformID(d.Id())
if err != nil {
return err
}
rule, err := sgC.GetRule(secgrpID, ruleID)
if err != nil {
return err
}
tfID := makeTerraformRuleID(secgrpID, rule.ID.String())
d.Set(isSecurityGroupID, secgrpID)
d.Set(isSecurityGroupRuleID, rule.ID.String())
d.Set(isSecurityGroupRuleIPVersion, rule.IPVersion)
d.Set(isSecurityGroupRuleProtocol, rule.Protocol)
protocol := "all"
if rule.Protocol != nil {
protocol = *rule.Protocol
}
if protocol == isSecurityGroupRuleProtocolTCP || protocol == isSecurityGroupRuleProtocolUDP {
tcpProtocol := map[string]interface{}{}
if rule.PortMin != nil {
tcpProtocol["port_min"] = *rule.PortMin
}
if rule.PortMax != nil {
tcpProtocol["port_max"] = *rule.PortMax
}
protocolList := make([]map[string]interface{}, 0)
protocolList = append(protocolList, tcpProtocol)
if protocol == isSecurityGroupRuleProtocolTCP {
d.Set(isSecurityGroupRuleProtocolTCP, protocolList)
} else {
d.Set(isSecurityGroupRuleProtocolUDP, protocolList)
}
}
if protocol == isSecurityGroupRuleProtocolICMP {
icmpProtocol := map[string]interface{}{}
if rule.Type != nil {
icmpProtocol["type"] = *rule.Type
}
if rule.Code != nil {
icmpProtocol["code"] = *rule.Code
}
protocolList := make([]map[string]interface{}, 0)
protocolList = append(protocolList, icmpProtocol)
d.Set(isSecurityGroupRuleProtocolICMP, protocolList)
}
remote := extractRuleRemote(rule.Remote)
d.Set(isSecurityGroupRuleRemote, remote)
d.SetId(tfID)
return nil
}
func resourceIBMISSecurityGroupRuleUpdate(d *schema.ResourceData, meta interface{}) error {
sess, err := meta.(ClientSession).ISSession()
if err != nil {
return err
}
sgC := network.NewSecurityGroupClient(sess)
parsed, err := parseIBMISSecurityGroupRuleDictionary(d, "update")
if err != nil {
return err
}
isSecurityGroupRuleKey := "security_group_rule_key_" + parsed.secgrpID
ibmMutexKV.Lock(isSecurityGroupRuleKey)
defer ibmMutexKV.Unlock(isSecurityGroupRuleKey)
_, err = sgC.UpdateRule(parsed.secgrpID, parsed.ruleID, parsed.direction,
parsed.ipversion, parsed.protocol, parsed.remoteAddress,
parsed.remoteCIDR, parsed.remoteSecGrpID, parsed.icmpType,
parsed.icmpCode, parsed.portMin, parsed.portMax)
if err != nil {
return err
}
return resourceIBMISSecurityGroupRuleRead(d, meta)
}
func resourceIBMISSecurityGroupRuleDelete(d *schema.ResourceData, meta interface{}) error {
sess, err := meta.(ClientSession).ISSession()
if err != nil {
return err
}
sgC := network.NewSecurityGroupClient(sess)
secgrpID, ruleID, err := parseISTerraformID(d.Id())
if err != nil {
return err
}
isSecurityGroupRuleKey := "security_group_rule_key_" + secgrpID
ibmMutexKV.Lock(isSecurityGroupRuleKey)
defer ibmMutexKV.Unlock(isSecurityGroupRuleKey)
err = sgC.DeleteRule(secgrpID, ruleID)
if err != nil {
iserror, ok := err.(iserrors.RiaasError)
if ok {
if len(iserror.Payload.Errors) == 1 &&
iserror.Payload.Errors[0].Code == "not_found" {
return nil
}
}
return err
}
return err
}
func resourceIBMISSecurityGroupRuleExists(d *schema.ResourceData, meta interface{}) (bool, error) {
sess, err := meta.(ClientSession).ISSession()
if err != nil {
return false, err
}
sgC := network.NewSecurityGroupClient(sess)
secgrpID, ruleID, err := parseISTerraformID(d.Id())
if err != nil {
return false, err
}
_, err = sgC.GetRule(secgrpID, ruleID)
if err != nil {
iserror, ok := err.(iserrors.RiaasError)
if ok {
if len(iserror.Payload.Errors) == 1 &&
iserror.Payload.Errors[0].Code == "not_found" {
return false, nil
}
}
return false, err
}
return true, nil
}
func parseISTerraformID(s string) (string, string, error) {
segments := strings.Split(s, ".")
if len(segments) != 2 {
return "", "", fmt.Errorf("invalid terraform Id %s (incorrect number of segments)", s)
}
if segments[0] == "" || segments[1] == "" {
return "", "", fmt.Errorf("invalid terraform Id %s (one or more empty segments)", s)
}
return segments[0], segments[1], nil
}
type parsedIBMISSecurityGroupRuleDictionary struct {
// After parsing, unused string fields are set to
// "" and unused int64 fields will be set to -1.
// This ("" for unused strings and -1 for unused int64s)
// is expected by our riaas API client.
secgrpID string
ruleID string
direction string
ipversion string
remote string
remoteAddress string
remoteCIDR string
remoteSecGrpID string
protocol string
icmpType int64
icmpCode int64
portMin int64
portMax int64
}
func inferRemoteSecurityGroup(s string) (address, cidr, id string, err error) {
if isSecurityGroupAddress(s) {
address = s
return
} else if isSecurityGroupCIDR(s) {
cidr = s
return
} else {
id = s
return
}
}
func parseIBMISSecurityGroupRuleDictionary(d *schema.ResourceData, tag string) (*parsedIBMISSecurityGroupRuleDictionary, error) {
parsed := &parsedIBMISSecurityGroupRuleDictionary{}
var err error
parsed.icmpType = -1
parsed.icmpCode = -1
parsed.portMin = -1
parsed.portMax = -1
parsed.secgrpID, parsed.ruleID, err = parseISTerraformID(d.Id())
if err != nil {
parsed.secgrpID = d.Get(isSecurityGroupID).(string)
}
parsed.direction = d.Get(isSecurityGroupRuleDirection).(string)
parsed.ipversion = d.Get(isSecurityGroupRuleIPVersion).(string)
parsed.remote = ""
if pr, ok := d.GetOk(isSecurityGroupRuleRemote); ok {
parsed.remote = pr.(string)
}
parsed.remoteAddress = ""
parsed.remoteCIDR = ""
parsed.remoteSecGrpID = ""
err = nil
if parsed.remote != "" {
parsed.remoteAddress, parsed.remoteCIDR, parsed.remoteSecGrpID, err = inferRemoteSecurityGroup(parsed.remote)
}
if err != nil {
return nil, err
}
parsed.protocol = "all"
if icmpInterface, ok := d.GetOk("icmp"); ok {
haveType := false
if icmpInterface.([]interface{})[0] == nil {
return nil, fmt.Errorf("Internal error. icmp interface is nil")
}
icmp := icmpInterface.([]interface{})[0].(map[string]interface{})
if value, ok := icmp["type"]; ok {
parsed.icmpType = int64(value.(int))
haveType = true
}
if value, ok := icmp["code"]; ok {
if !haveType {
return nil, fmt.Errorf("icmp code requires icmp type")
}
parsed.icmpCode = int64(value.(int))
}
parsed.protocol = "icmp"
}
for _, prot := range []string{"tcp", "udp"} {
if tcpInterface, ok := d.GetOk(prot); ok {
haveMin := false
haveMax := false
if tcpInterface.([]interface{})[0] == nil {
return nil, fmt.Errorf("Internal error. %q interface is nil", prot)
}
ports := tcpInterface.([]interface{})[0].(map[string]interface{})
if value, ok := ports["port_min"]; ok {
parsed.portMin = int64(value.(int))
haveMin = true
}
if value, ok := ports["port_max"]; ok {
parsed.portMax = int64(value.(int))
haveMax = true
}
// If only min or max is set, ensure that both min and max are set to the same value
if haveMin && !haveMax {
parsed.portMax = parsed.portMin
}
if haveMax && !haveMin {
parsed.portMin = parsed.portMax
}
parsed.protocol = prot
}
}
// log.Printf("[DEBUG] parse tag=%s\n\t%v \n\t%v \n\t%v \n\t%v \n\t%v \n\t%v \n\t%v \n\t%v \n\t%v \n\t%v \n\t%v \n\t%v ",
// tag, parsed.secgrpID, parsed.ruleID, parsed.direction, parsed.ipversion, parsed.protocol, parsed.remoteAddress,
// parsed.remoteCIDR, parsed.remoteSecGrpID, parsed.icmpType, parsed.icmpCode, parsed.portMin, parsed.portMax)
return parsed, nil
}
func makeTerraformRuleID(id1, id2 string) string {
// Include both group and rule id to create a unique Terraform id. As a bonus,
// we can extract the group id as needed for API calls such as READ.
return id1 + "." + id2
}
func extractRuleRemote(remote *models.SecurityGroupRuleRemote) string {
if remote == nil {
return ""
}
if remote.Address != "" {
return remote.Address
}
if remote.CidrBlock != "" {
return remote.CidrBlock
}
if remote.ID.String() != "" {
return remote.ID.String()
}
return ""
}