From 4f4da60456d418691e46ee137f12d031c4afe7e3 Mon Sep 17 00:00:00 2001 From: Zhenguo Niu Date: Tue, 17 Mar 2020 15:04:31 +0800 Subject: [PATCH] Fix removing FW rule assigned to FW policy (#275) --- .../resource_huaweicloud_fw_rule_v2.go | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/huaweicloud/resource_huaweicloud_fw_rule_v2.go b/huaweicloud/resource_huaweicloud_fw_rule_v2.go index 92df783bee..16990453b5 100644 --- a/huaweicloud/resource_huaweicloud_fw_rule_v2.go +++ b/huaweicloud/resource_huaweicloud_fw_rule_v2.go @@ -8,6 +8,7 @@ import ( "github.com/huaweicloud/golangsdk" "github.com/huaweicloud/golangsdk/openstack/networking/v2/extensions/fwaas_v2/policies" "github.com/huaweicloud/golangsdk/openstack/networking/v2/extensions/fwaas_v2/rules" + "github.com/huaweicloud/golangsdk/pagination" ) func resourceFWRuleV2() *schema.Resource { @@ -236,8 +237,12 @@ func resourceFWRuleV2Delete(d *schema.ResourceData, meta interface{}) error { return err } - if rule.PolicyID != "" { - _, err := policies.RemoveRule(fwClient, rule.PolicyID, rule.ID).Extract() + policyID, err := assignedPolicyID(fwClient, rule.ID) + if err != nil { + return err + } + if policyID != "" { + _, err := policies.RemoveRule(fwClient, policyID, rule.ID).Extract() if err != nil { return err } @@ -246,6 +251,30 @@ func resourceFWRuleV2Delete(d *schema.ResourceData, meta interface{}) error { return rules.Delete(fwClient, d.Id()).Err } +func assignedPolicyID(fwClient *golangsdk.ServiceClient, ruleID string) (string, error) { + pager := policies.List(fwClient, policies.ListOpts{}) + policyID := "" + err := pager.EachPage(func(page pagination.Page) (b bool, err error) { + policyList, err := policies.ExtractPolicies(page) + if err != nil { + return false, err + } + for _, policy := range policyList { + for _, rule := range policy.Rules { + if rule == ruleID { + policyID = policy.ID + return false, nil + } + } + } + return true, nil + }) + if err != nil { + return "", err + } + return policyID, nil +} + func resourceFWRuleV2DetermineIPVersion(ipv int) golangsdk.IPVersion { // Determine the IP Version var ipVersion golangsdk.IPVersion