-
Notifications
You must be signed in to change notification settings - Fork 2
/
resource_security_group.go
579 lines (491 loc) · 14.7 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
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
package provider
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"github.com/hashicorp/go-cty/cty"
"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/krystal/go-katapult"
"github.com/krystal/go-katapult/core"
)
func resourceSecurityGroup() *schema.Resource { //nolint:funlen
ruleSchema := resourceSecurityGroupRule().Schema
delete(ruleSchema, "security_group_id")
directionSchema := ruleSchema["direction"]
ruleSchema["direction"] = &schema.Schema{
Type: directionSchema.Type,
Computed: true,
Description: directionSchema.Description,
}
return &schema.Resource{
CreateContext: resourceSecurityGroupCreate,
ReadContext: resourceSecurityGroupRead,
UpdateContext: resourceSecurityGroupUpdate,
DeleteContext: resourceSecurityGroupDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Description: "Allows management of security groups, their rules, and " +
"their associations. By default all traffic is blocked, both " +
"inbound and outbound. To allow traffic you must explicitly add " +
"rules to the security group. You can also allow all traffic by " +
"setting the `allow_all_inbound` and `allow_all_outbound` " +
"attributes to `true`.",
Schema: map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
Computed: true,
Description: "The ID of the security group. This is " +
"automatically generated by the API.",
},
"name": {
Type: schema.TypeString,
Required: true,
Description: "The name of the security group.",
ValidateFunc: validation.StringIsNotEmpty,
},
"associations": {
Type: schema.TypeSet,
Optional: true,
Description: "The resource IDs to apply this security group " +
"to. Accepts IDs of virtual machines, virtual machine " +
"groups, and tags.",
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringIsNotEmpty,
},
},
"allow_all_inbound": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether or not to allow all inbound traffic. " +
"If not explicitly set, it defaults to false, blocking " +
"all inbound traffic not covered by a inbound rule. " +
"If changed to true on a existing security group, all " +
"existing inbound rules will be deleted, hence it " +
"cannot be enabled while any inbound rules are defined.",
},
"allow_all_outbound": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether or not to allow all outbound traffic. " +
"If not explicitly set, it defaults to false, blocking " +
"all outbound traffic not covered by a outbound rule. " +
"If changed to true on a existing security group, all " +
"existing outbound rules will be deleted, hence it " +
"cannot be enabled while any outbound rules are defined.",
},
"external_rules": {
Type: schema.TypeBool,
Optional: true,
Description: "When enabled, The full list of rules are not " +
"managed by Terraform. Induvidual rules can still be " +
"managed with the `katapult_security_group_rule` " +
"resource. This is required to prevent Terraform from " +
"deleting rules managed outside of Terraform. Defaults " +
"to `false`.",
ConflictsWith: []string{"inbound_rule", "outbound_rule"},
},
"inbound_rule": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{Schema: ruleSchema},
ConflictsWith: []string{"external_rules"},
Description: "Zero or more inbound rules to apply to the " +
"security group. Each rule specifies inbound traffic " +
"which should be allowed.",
},
"outbound_rule": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{Schema: ruleSchema},
ConflictsWith: []string{"external_rules"},
Description: "Zero or more outbound rules to apply to the " +
"security group. Each rule specifies outbound traffic " +
"which should be allowed.",
},
},
}
}
//
// CRUD
//
func resourceSecurityGroupCreate(
ctx context.Context,
d *schema.ResourceData,
meta interface{},
) diag.Diagnostics {
m := meta.(*Meta)
diags := validateSecurityGroupRules(d)
if len(diags) > 0 {
return diags
}
associations := schemaSetToSlice[string](
d.Get("associations").(*schema.Set),
)
allowAllInbound := d.Get("allow_all_inbound").(bool)
allowAllOutbound := d.Get("allow_all_outbound").(bool)
args := &core.SecurityGroupCreateArguments{
Name: d.Get("name").(string),
Associations: &associations,
AllowAllInbound: &allowAllInbound,
AllowAllOutbound: &allowAllOutbound,
}
sg, _, err := m.Core.SecurityGroups.Create(
ctx, m.OrganizationRef, args,
)
if err != nil {
return diag.FromErr(err)
}
d.SetId(sg.ID)
if !d.Get("external_rules").(bool) {
err = updateSecurityGroupRules(ctx, d, m, "inbound")
if err != nil {
return diag.FromErr(err)
}
err = updateSecurityGroupRules(ctx, d, m, "outbound")
if err != nil {
return diag.FromErr(err)
}
}
return resourceSecurityGroupRead(ctx, d, meta)
}
func resourceSecurityGroupRead(
ctx context.Context,
d *schema.ResourceData,
meta interface{},
) diag.Diagnostics {
m := meta.(*Meta)
var diags diag.Diagnostics
sg, _, err := m.Core.SecurityGroups.GetByID(ctx, d.Id())
if err != nil {
if errors.Is(err, katapult.ErrNotFound) {
d.SetId("")
return diags
}
return diag.FromErr(err)
}
_ = d.Set("name", sg.Name)
_ = d.Set("allow_all_inbound", sg.AllowAllInbound)
_ = d.Set("allow_all_outbound", sg.AllowAllOutbound)
err = d.Set("associations", stringSliceToSchemaSet(sg.Associations))
if err != nil {
diags = append(diags, diag.FromErr(err)...)
}
// Skip rule handling if external_rules is enabled.
if d.Get("external_rules").(bool) {
return diags
}
// Warn the user if external_rules was disabled. Due to the previous read
// before the update not knowing about the change, any existing rules
// managed outside of Terraform will not be known to Terraform until the
// next refresh.
if d.HasChange("external_rules") {
diags = append(diags, diag.Diagnostic{
Severity: diag.Warning,
Summary: fmt.Sprintf(
"security group %q (%s): external_rules option has been "+
"disabled.",
sg.Name, sg.ID,
),
Detail: "Please run \"terraform plan\" or \"terraform apply\" " +
"again to ensure all rules are in sync with Terraform " +
"definitions.",
})
}
inbound, outbound, err := getAllFlattenedSecurityGroupRules(
ctx, m, sg.Ref(),
)
if err != nil {
return diag.FromErr(err)
}
err = d.Set("inbound_rule", inbound)
if err != nil {
diags = append(diags, diag.FromErr(err)...)
}
err = d.Set("outbound_rule", outbound)
if err != nil {
diags = append(diags, diag.FromErr(err)...)
}
return diags
}
func resourceSecurityGroupUpdate(
ctx context.Context,
d *schema.ResourceData,
meta interface{},
) diag.Diagnostics {
m := meta.(*Meta)
diags := validateSecurityGroupRules(d)
if len(diags) > 0 {
return diags
}
sgRef := core.SecurityGroupRef{ID: d.Id()}
args := &core.SecurityGroupUpdateArguments{}
if d.HasChange("name") {
args.Name = d.Get("name").(string)
}
if d.HasChange("associations") {
raw := d.Get("associations").(*schema.Set)
assocs := schemaSetToSlice[string](raw)
args.Associations = &assocs
}
if d.HasChange("allow_all_inbound") {
allowAllInbound := d.Get("allow_all_inbound").(bool)
args.AllowAllInbound = &allowAllInbound
}
if d.HasChange("allow_all_outbound") {
allowAllOutbound := d.Get("allow_all_outbound").(bool)
args.AllowAllOutbound = &allowAllOutbound
}
_, _, err := m.Core.SecurityGroups.Update(ctx, sgRef, args)
if err != nil {
return diag.FromErr(err)
}
// Handle rules if external_rules is disabled, or if it was changed to
// enabled now, in which case we need to remove all rules.
handleRules := !d.Get("external_rules").(bool) ||
d.HasChange("external_rules")
// Calculate the changes to inbound and outbound rules, and
// create/update/delete rules as needed.
if handleRules {
err = updateSecurityGroupRules(ctx, d, m, "inbound")
if err != nil {
return diag.FromErr(err)
}
err = updateSecurityGroupRules(ctx, d, m, "outbound")
if err != nil {
return diag.FromErr(err)
}
}
return resourceSecurityGroupRead(ctx, d, meta)
}
func resourceSecurityGroupDelete(
ctx context.Context,
d *schema.ResourceData,
meta interface{},
) diag.Diagnostics {
m := meta.(*Meta)
sgRef := core.SecurityGroupRef{ID: d.Id()}
_, _, err := m.Core.SecurityGroups.Delete(ctx, sgRef)
if err != nil {
return diag.FromErr(err)
}
return diag.Diagnostics{}
}
//
// Helpers
//
// validateSecurityGroupRules makes sure that if one of the allow_all_*
// attributes are enabled, then no rules are defined for the same direction.
func validateSecurityGroupRules(d *schema.ResourceData) diag.Diagnostics {
var diags diag.Diagnostics
name := fmt.Sprintf("%q", d.Get("name").(string))
if v := d.Id(); v != "" {
name += " (" + v + ")"
}
if d.Get("allow_all_inbound").(bool) &&
len(d.Get("inbound_rule").([]any)) > 0 {
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: fmt.Sprintf(
"security group %s: cannot enable allow_all_inbound "+
"while also specifyng one or more inbound_rule",
name,
),
AttributePath: cty.GetAttrPath("inbound_rule"),
})
}
if d.Get("allow_all_outbound").(bool) &&
len(d.Get("outbound_rule").([]any)) > 0 {
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: fmt.Sprintf(
"security group %s: cannot enable allow_all_outbound "+
"while also specifyng one or more outbound_rule",
name,
),
AttributePath: cty.GetAttrPath("outbound_rule"),
})
}
return diags
}
// updateSecurityGroupRules updates the inbound or outbound rules for a security
// group. This function will create, update, and delete rules as needed.
func updateSecurityGroupRules(
ctx context.Context,
d *schema.ResourceData,
m *Meta,
direction string,
) error {
attr := fmt.Sprintf("%s_rule", direction)
if !d.HasChange(attr) {
return nil
}
rawOld, rawNew := d.GetChange(attr)
create, update, del := diffSecurityGroupRules(
rawOld.([]any), rawNew.([]any),
)
sgRef := core.SecurityGroupRef{ID: d.Id()}
for _, r := range create {
ports := r["ports"].(string)
targets := schemaSetToSlice[string](r["targets"].(*schema.Set))
notes := r["notes"].(string)
args := &core.SecurityGroupRuleArguments{
Direction: direction,
Protocol: strings.ToUpper(r["protocol"].(string)),
Ports: &ports,
Targets: &targets,
Notes: ¬es,
}
_, _, err := m.Core.SecurityGroupRules.Create(ctx, sgRef, args)
if err != nil {
return err
}
}
for _, r := range update {
id := r["id"].(string)
ruleRef := core.SecurityGroupRuleRef{ID: id}
ports := r["ports"].(string)
targets := schemaSetToSlice[string](r["targets"].(*schema.Set))
notes := r["notes"].(string)
args := &core.SecurityGroupRuleArguments{
Protocol: strings.ToUpper(r["protocol"].(string)),
Ports: &ports,
Targets: &targets,
Notes: ¬es,
}
_, _, err := m.Core.SecurityGroupRules.Update(ctx, ruleRef, args)
if err != nil {
return err
}
}
for _, r := range del {
id := r["id"].(string)
ruleRef := core.SecurityGroupRuleRef{ID: id}
_, _, err := m.Core.SecurityGroupRules.Delete(ctx, ruleRef)
if err != nil && !errors.Is(err, katapult.ErrNotFound) {
return err
}
}
return nil
}
func diffSecurityGroupRules(
oldRuleList []any,
newRuleList []any,
) (create, update, del []map[string]any) {
oldRules := securityGroupRuleListToMaps(oldRuleList)
newRules := securityGroupRuleListToMaps(newRuleList)
existing := map[string]map[string]any{}
for _, r := range oldRules {
if id, ok := r["id"].(string); ok && id != "" {
existing[id] = r
}
}
for _, newRule := range newRules {
id, ok := newRule["id"].(string)
if !ok || id == "" {
create = append(create, newRule)
continue
}
oldRule, ok := existing[id]
delete(existing, id)
if !ok || diffSecurityGroupRule(oldRule, newRule) {
update = append(update, newRule)
}
}
for _, oldRule := range existing {
del = append(del, oldRule)
}
return create, update, del
}
func securityGroupRuleListToMaps(l []any) []map[string]any {
var out []map[string]any
for _, v := range l {
if m, ok := v.(map[string]any); ok {
out = append(out, m)
}
}
return out
}
func diffSecurityGroupRule(oldRule, newRule map[string]any) bool {
if oldRule == nil && newRule == nil {
return false
}
if oldRule == nil || newRule == nil {
return true
}
// If the length of the keys is different, then the rules are different.
if len(oldRule) != len(newRule) {
return true
}
// If the list of keys are different (ignoring order), then the rules are
// different.
if !stringsEqual(mapKeys(oldRule), mapKeys(newRule)) {
return true
}
// If any of the values are different, then the rules are different. We
// treat string slice values as a special case, ignoring the order of the
// items, as long as they contain the same set of items.
for k, v := range newRule {
if diffSchemaSetOrAny(oldRule[k], v) {
return true
}
}
return false
}
// diffSchemaSetOrAny compares two values, returning true if they are not equal.
//
// If the values are both string slices, they are compared as sets, ignoring the
// order of the elements. Otherwise they are compared using reflect.DeepEqual.
func diffSchemaSetOrAny(a, b any) bool {
aSet, aOK := a.(*schema.Set)
bSet, bOK := b.(*schema.Set)
if aOK && bOK {
return !aSet.Equal(bSet)
}
return !reflect.DeepEqual(a, b)
}
func getAllFlattenedSecurityGroupRules(
ctx context.Context,
m *Meta,
sgRef core.SecurityGroupRef,
) (inbound []map[string]any, outbound []map[string]any, err error) {
inbound = []map[string]any{}
outbound = []map[string]any{}
totalPages := 2
for pageNum := 1; pageNum <= totalPages; pageNum++ {
pageResult, resp, err := m.Core.SecurityGroupRules.List(
ctx, sgRef, &core.ListOptions{Page: pageNum},
)
if err != nil {
return nil, nil, err
}
totalPages = resp.Pagination.TotalPages
for _, rule := range pageResult {
flattened := flattenSecurityGroupRule(rule)
switch rule.Direction {
case "inbound":
inbound = append(inbound, flattened)
case "outbound":
outbound = append(outbound, flattened)
}
}
}
return inbound, outbound, nil
}
func flattenSecurityGroupRule(rule *core.SecurityGroupRule) map[string]any {
return map[string]any{
"id": rule.ID,
"direction": rule.Direction,
"protocol": rule.Protocol,
"ports": rule.Ports,
"targets": rule.Targets,
"notes": rule.Notes,
}
}