-
Notifications
You must be signed in to change notification settings - Fork 154
/
resource_huaweicloud_network_acl.go
536 lines (463 loc) · 15.3 KB
/
resource_huaweicloud_network_acl.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
package huaweicloud
import (
"time"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/chnsz/golangsdk"
"github.com/chnsz/golangsdk/openstack/networking/v1/subnets"
"github.com/chnsz/golangsdk/openstack/networking/v2/extensions/fwaas_v2/firewall_groups"
"github.com/chnsz/golangsdk/openstack/networking/v2/extensions/fwaas_v2/policies"
"github.com/chnsz/golangsdk/openstack/networking/v2/extensions/fwaas_v2/routerinsertion"
"github.com/chnsz/golangsdk/openstack/networking/v2/ports"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils/fmtp"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils/logp"
)
// FirewallGroup is an HuaweiCloud firewall group.
type FirewallGroup struct {
firewall_groups.FirewallGroup
routerinsertion.FirewallGroupExt
}
// @API VPC GET /v2.0/ports
// @API VPC GET /v1/{project_id}/subnets/{id}
// @API VPC DELETE /v2.0/fwaas/firewall_groups/{id}
// @API VPC GET /v2.0/fwaas/firewall_groups/{id}
// @API VPC PUT /v2.0/fwaas/firewall_groups/{id}
// @API VPC POST /v2.0/fwaas/firewall_groups
// @API VPC DELETE /v2.0/fwaas/firewall_policies/{id}
// @API VPC PUT /v2.0/fwaas/firewall_policies/{id}
// @API VPC POST /v2.0/fwaas/firewall_policies
func ResourceNetworkACL() *schema.Resource {
return &schema.Resource{
Create: resourceNetworkACLCreate,
Read: resourceNetworkACLRead,
Update: resourceNetworkACLUpdate,
Delete: resourceNetworkACLDelete,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"name": {
Type: schema.TypeString,
Required: true,
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"inbound_rules": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"outbound_rules": {
Type: schema.TypeList,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"subnets": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"inbound_policy_id": {
Type: schema.TypeString,
Computed: true,
},
"outbound_policy_id": {
Type: schema.TypeString,
Computed: true,
},
"ports": {
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"status": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceNetworkACLCreate(d *schema.ResourceData, meta interface{}) error {
var err error
var portIds []string
var inboundPolicyID, outboundPolicyID string
config := meta.(*config.Config)
fwClient, err := config.FwV2Client(GetRegion(d, config))
if err != nil {
return fmtp.Errorf("Error creating HuaweiCloud fw client: %s", err)
}
defer func() {
// delete firewall policies when encounter errors
if err != nil && inboundPolicyID != "" {
deleteErr := policies.Delete(fwClient, inboundPolicyID).Err
if deleteErr != nil {
logp.Printf("[WARN] Error deleting inbound firewall policy %s: %s", inboundPolicyID, deleteErr)
}
}
if err != nil && outboundPolicyID != "" {
deleteErr := policies.Delete(fwClient, outboundPolicyID).Err
if deleteErr != nil {
logp.Printf("[WARN] Error deleting outbound firewall policy %s: %s", outboundPolicyID, deleteErr)
}
}
}()
// get port Ids from subnets
subnetsRaw := d.Get("subnets").(*schema.Set).List()
if len(subnetsRaw) > 0 {
for _, v := range subnetsRaw {
port, err := getGWPortFromSubnet(config, v.(string))
if err != nil {
return err
}
portIds = append(portIds, port)
}
logp.Printf("[DEBUG] Will attempt to associate Firewall group with subnets: %+v", subnetsRaw)
}
groupName := d.Get("name").(string)
// create inbound policy
inboundRaw := d.Get("inbound_rules").([]interface{})
if len(inboundRaw) > 0 {
inboundRules := make([]string, len(inboundRaw))
for i, r := range inboundRaw {
inboundRules[i] = r.(string)
}
policyName := "inbound_policy_for_" + groupName
policyOpts := policies.CreateOpts{
Name: policyName,
Rules: inboundRules,
}
logp.Printf("[DEBUG] Create inbound firewall policy: %#v", policyOpts)
policy, err := policies.Create(fwClient, policyOpts).Extract()
if err != nil {
return err
}
logp.Printf("[DEBUG] Firewall inbound policy created: %#v", policy)
inboundPolicyID = policy.ID
}
// create outbound policy
outboundRaw := d.Get("outbound_rules").([]interface{})
if len(outboundRaw) > 0 {
outboundRules := make([]string, len(outboundRaw))
for i, r := range outboundRaw {
outboundRules[i] = r.(string)
}
policyName := "outbound_policy_for_" + groupName
policyOpts := policies.CreateOpts{
Name: policyName,
Rules: outboundRules,
}
logp.Printf("[DEBUG] Create outbound firewall policy: %#v", policyOpts)
policy, err := policies.Create(fwClient, policyOpts).Extract()
if err != nil {
return err
}
logp.Printf("[DEBUG] Firewall outbound policy created: %#v", policy)
outboundPolicyID = policy.ID
}
var createOpts firewall_groups.CreateOptsBuilder
createOpts = &firewall_groups.CreateOpts{
Name: groupName,
Description: d.Get("description").(string),
IngressPolicyID: inboundPolicyID,
EgressPolicyID: outboundPolicyID,
}
if len(portIds) > 0 {
createOpts = &routerinsertion.CreateOptsExt{
CreateOptsBuilder: createOpts,
PortIDs: portIds,
}
}
logp.Printf("[DEBUG] Create firewall group: %#v", createOpts)
group, err := firewall_groups.Create(fwClient, createOpts).Extract()
if err != nil {
return err
}
d.SetId(group.ID)
logp.Printf("[DEBUG] waiting for Firewall group (%s) to become ACTIVE", d.Id())
stateConf := &resource.StateChangeConf{
// if none subnets was associated with the firewall group, the state will be "INACTIVE"
// so we seems the "INACTIVE" as a target state.
Pending: []string{"PENDING_CREATE"},
Target: []string{"ACTIVE", "INACTIVE"},
Refresh: waitForFirewallGroupActive(fwClient, group.ID),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 2,
MinTimeout: 2 * time.Second,
}
_, stateErr := stateConf.WaitForState()
if stateErr != nil {
return fmtp.Errorf("Error waiting for Firewall group (%s) to become ACTIVE: %s",
d.Id(), stateErr)
}
logp.Printf("[DEBUG] Firewall group (%s) is active.", group.ID)
return resourceNetworkACLRead(d, meta)
}
func resourceNetworkACLRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*config.Config)
fwClient, err := config.FwV2Client(GetRegion(d, config))
if err != nil {
return fmtp.Errorf("Error creating HuaweiCloud fw client: %s", err)
}
var fwGroup FirewallGroup
err = firewall_groups.Get(fwClient, d.Id()).ExtractInto(&fwGroup)
if err != nil {
return CheckDeleted(d, err, "firewall")
}
logp.Printf("[DEBUG] Read HuaweiCloud Firewall group %s: %#v", d.Id(), fwGroup)
d.Set("name", fwGroup.Name)
d.Set("status", fwGroup.Status)
d.Set("description", fwGroup.Description)
d.Set("inbound_policy_id", fwGroup.IngressPolicyID)
d.Set("outbound_policy_id", fwGroup.EgressPolicyID)
if err := d.Set("ports", fwGroup.PortIDs); err != nil {
return fmtp.Errorf("[DEBUG] Error saving ports to state for HuaweiCloud firewall group (%s): %s", d.Id(), err)
}
return nil
}
func resourceNetworkACLUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*config.Config)
fwClient, err := config.FwV2Client(GetRegion(d, config))
if err != nil {
return fmtp.Errorf("Error creating HuaweiCloud fw client: %s", err)
}
// first of all, inbound_policy/rules and outbound_policy/rules should be updated
if d.HasChange("inbound_rules") {
err := updateNetworkACLPolicyRules(d, fwClient, "inbind")
if err != nil {
return err
}
}
if d.HasChange("outbound_rules") {
err := updateNetworkACLPolicyRules(d, fwClient, "outbind")
if err != nil {
return err
}
}
// update other parameters
var changed bool
opts := firewall_groups.UpdateOpts{}
if d.HasChanges("name", "description") {
changed = true
opts.Name = d.Get("name").(string)
opts.Description = d.Get("description").(string)
}
var updateOpts firewall_groups.UpdateOptsBuilder
var portIds []string
if d.HasChange("subnets") {
changed = true
// get port Ids from subnets
subnetsRaw := d.Get("subnets").(*schema.Set).List()
for _, v := range subnetsRaw {
port, err := getGWPortFromSubnet(config, v.(string))
if err != nil {
return err
}
portIds = append(portIds, port)
}
logp.Printf("[DEBUG] Will attempt to associate Firewall group with subnets: %+v", subnetsRaw)
updateOpts = routerinsertion.UpdateOptsExt{
UpdateOptsBuilder: opts,
PortIDs: portIds,
}
} else {
updateOpts = opts
}
if changed {
logp.Printf("[DEBUG] Updating firewall with id %s: %#v", d.Id(), updateOpts)
err = firewall_groups.Update(fwClient, d.Id(), updateOpts).Err
if err != nil {
return err
}
// if none subnets was associated with the firewall group, the state will be "INACTIVE"
// so we seems the "INACTIVE" as a target state.
stateConf := &resource.StateChangeConf{
Pending: []string{"PENDING_CREATE", "PENDING_UPDATE"},
Target: []string{"ACTIVE", "INACTIVE"},
Refresh: waitForFirewallGroupActive(fwClient, d.Id()),
Timeout: d.Timeout(schema.TimeoutUpdate),
Delay: 2,
MinTimeout: 2 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmtp.Errorf("Error updating firewall group (%s): %s", d.Id(), err)
}
}
return resourceNetworkACLRead(d, meta)
}
func resourceNetworkACLDelete(d *schema.ResourceData, meta interface{}) error {
logp.Printf("[DEBUG] Destroy firewall group: %s", d.Id())
config := meta.(*config.Config)
fwClient, err := config.FwV2Client(GetRegion(d, config))
if err != nil {
return fmtp.Errorf("Error creating HuaweiCloud fw client: %s", err)
}
inboundPolicyID := d.Get("inbound_policy_id").(string)
outboundPolicyID := d.Get("outbound_policy_id").(string)
err = firewall_groups.Delete(fwClient, d.Id()).Err
if err != nil {
return err
}
stateConf := &resource.StateChangeConf{
Pending: []string{"DELETING"},
Target: []string{"DELETED"},
Refresh: waitForFirewallGroupDeletion(fwClient, d.Id()),
Timeout: d.Timeout(schema.TimeoutDelete),
Delay: 2,
MinTimeout: 2 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmtp.Errorf("Error deleting firewall group (%s): %s", d.Id(), err)
}
// delete firewall policies after the firewall group
if inboundPolicyID != "" {
deleteErr := policies.Delete(fwClient, inboundPolicyID).Err
if deleteErr != nil {
logp.Printf("[WARN] Error deleting inbound firewall policy %s: %s", inboundPolicyID, deleteErr)
}
}
if outboundPolicyID != "" {
deleteErr := policies.Delete(fwClient, outboundPolicyID).Err
if deleteErr != nil {
logp.Printf("[WARN] Error deleting outbound firewall policy %s: %s", outboundPolicyID, deleteErr)
}
}
d.SetId("")
return nil
}
func getGWPortFromSubnet(config *config.Config, subnetID string) (string, error) {
var gatewayIP string
var gatewayPort string
subnetClient, err := config.NetworkingV1Client(config.Region)
if err != nil {
return "", fmtp.Errorf("Error creating Huaweicloud vpc client: %s", err)
}
networkingClient, err := config.NetworkingV2Client(config.Region)
if err != nil {
return "", fmtp.Errorf("Error creating HuaweiCloud networking client: %s", err)
}
// get Gateway IP
n, err := subnets.Get(subnetClient, subnetID).Extract()
if err != nil {
return "", fmtp.Errorf("Error retrieving Huaweicloud subnet %s: %s", subnetID, err)
}
gatewayIP = n.GatewayIP
logp.Printf("[DEBUG] the gateway IP address of subnet %s is %s", subnetID, gatewayIP)
// list all ports in the subnet
listOpts := ports.ListOpts{
NetworkID: subnetID,
//Status: "ACTIVE",
}
allPages, err := ports.List(networkingClient, listOpts).AllPages()
if err != nil {
return "", fmtp.Errorf("Unable to list Huaweicloud ports of %s: %s", subnetID, err)
}
var allPorts []ports.Port
err = ports.ExtractPortsInto(allPages, &allPorts)
if err != nil {
return "", fmtp.Errorf("Unable to retrieve Huaweicloud ports of %s: %s", subnetID, err)
}
if len(allPorts) == 0 {
return "", fmtp.Errorf("No ports was found in %s", subnetID)
}
// Filter IPs by the gatewayIP
var isExist bool
for _, p := range allPorts {
for _, ipObject := range p.FixedIPs {
if ipObject.IPAddress == gatewayIP {
isExist = true
gatewayPort = p.ID
logp.Printf("[DEBUG] the gateway port of subnet %s is %s", subnetID, gatewayPort)
break
}
}
if isExist {
break
}
}
if !isExist {
return "", fmtp.Errorf("No gateway port was found in %s", subnetID)
}
return gatewayPort, nil
}
func updateNetworkACLPolicyRules(d *schema.ResourceData, client *golangsdk.ServiceClient, direct string) error {
var policyKey, rulesKey string
if direct == "inbind" {
policyKey = "inbound_policy_id"
rulesKey = "inbound_rules"
} else {
policyKey = "outbound_policy_id"
rulesKey = "outbound_rules"
}
groupName := d.Get("name").(string)
policyID := d.Get(policyKey).(string)
policyName := direct + "_policy_for_" + groupName
v := d.Get(rulesKey).([]interface{})
rulesList := make([]string, len(v))
for i, v := range v {
rulesList[i] = v.(string)
}
if policyID != "" {
// update the firewall policy, even if the rules are empty
policyOpts := policies.UpdateOpts{
Name: policyName,
Rules: rulesList,
}
logp.Printf("[DEBUG] updating firewall policy with id %s: %#v", policyID, policyOpts)
err := policies.Update(client, policyID, policyOpts).Err
if err != nil {
return fmtp.Errorf("Error updating firewall policy %s: %s", policyID, err)
}
} else {
// create new firewall policy
policyOpts := policies.CreateOpts{
Name: policyName,
Rules: rulesList,
}
logp.Printf("[DEBUG] Create firewall policy: %#v", policyOpts)
policy, err := policies.Create(client, policyOpts).Extract()
if err != nil {
return fmtp.Errorf("Error creating firewall policy: %s", err)
}
//lintignore:R001
d.Set(policyKey, policy.ID)
}
return nil
}
func waitForFirewallGroupActive(fwClient *golangsdk.ServiceClient, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
var fw FirewallGroup
err := firewall_groups.Get(fwClient, id).ExtractInto(&fw)
if err != nil {
return nil, "", err
}
return fw, fw.Status, nil
}
}
func waitForFirewallGroupDeletion(fwClient *golangsdk.ServiceClient, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
fw, err := firewall_groups.Get(fwClient, id).Extract()
logp.Printf("[DEBUG] Got firewall group %s => %#v", id, fw)
if err != nil {
if _, ok := err.(golangsdk.ErrDefault404); ok {
logp.Printf("[DEBUG] Firewall group %s is actually deleted", id)
return "", "DELETED", nil
}
return nil, "", fmtp.Errorf("Unexpected error: %s", err)
}
logp.Printf("[DEBUG] Firewall group %s deletion is pending", id)
return fw, "DELETING", nil
}
}