Skip to content

Commit

Permalink
add customize diff to prevent two rules with the same priority (Googl…
Browse files Browse the repository at this point in the history
  • Loading branch information
megan07 authored and Nathan Klish committed May 18, 2020
1 parent 9335f00 commit 6ae3107
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func resourceComputeSecurityPolicy() *schema.Resource {
Importer: &schema.ResourceImporter{
State: resourceSecurityPolicyStateImporter,
},
CustomizeDiff: rulesCustomizeDiff,

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(4 * time.Minute),
Expand Down Expand Up @@ -151,6 +152,22 @@ func resourceComputeSecurityPolicy() *schema.Resource {
}
}

func rulesCustomizeDiff(diff *schema.ResourceDiff, _ interface{}) error {
_, n := diff.GetChange("rule")
nSet := n.(*schema.Set)

nPriorities := map[int64]bool{}
for _, rule := range nSet.List() {
priority := int64(rule.(map[string]interface{})["priority"].(int))
if nPriorities[priority] {
return fmt.Errorf("Two rules have the same priority, please update one of the priorities to be different.")
}
nPriorities[priority] = true
}

return nil
}

func resourceComputeSecurityPolicyCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ func TestAccComputeSecurityPolicy_update(t *testing.T) {
ImportStateVerify: true,
},

{
Config: testAccComputeSecurityPolicy_updateSamePriority(spName),
ExpectError: regexp.MustCompile("Two rules have the same priority, please update one of the priorities to be different."),
},

{
Config: testAccComputeSecurityPolicy_update(spName),
},
Expand Down Expand Up @@ -178,6 +183,52 @@ resource "google_compute_security_policy" "policy" {
`, spName)
}

func testAccComputeSecurityPolicy_updateSamePriority(spName string) string {
return fmt.Sprintf(`
resource "google_compute_security_policy" "policy" {
name = "%s"
description = "updated description"

// keep this
rule {
action = "allow"
priority = "2147483647"
match {
versioned_expr = "SRC_IPS_V1"
config {
src_ip_ranges = ["*"]
}
}
description = "default rule"
}

// add this
rule {
action = "deny(403)"
priority = "2000"
match {
versioned_expr = "SRC_IPS_V1"
config {
src_ip_ranges = ["10.0.1.0/24"]
}
}
}

rule {
action = "allow"
priority = "2000"
match {
versioned_expr = "SRC_IPS_V1"
config {
src_ip_ranges = ["10.0.0.0/24"]
}
}
preview = true
}
}
`, spName)
}

func testAccComputeSecurityPolicy_update(spName string) string {
return fmt.Sprintf(`
resource "google_compute_security_policy" "policy" {
Expand Down

0 comments on commit 6ae3107

Please sign in to comment.