Skip to content

Commit

Permalink
Add new compute-firewall-policy-with-rules resource (GoogleCloudPlatf…
Browse files Browse the repository at this point in the history
  • Loading branch information
mihhalj authored Sep 13, 2024
1 parent 8709d00 commit f6bc823
Show file tree
Hide file tree
Showing 10 changed files with 923 additions and 0 deletions.
452 changes: 452 additions & 0 deletions mmv1/products/compute/FirewallPolicyWithRules.yaml

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
func firewallPolicyWithRulesConvertPriorityToInt(v interface {}) (int64, error) {
if strVal, ok := v.(string); ok {
if intVal, err := tpgresource.StringToFixed64(strVal); err == nil {
return intVal, nil
}
}

if intVal, ok := v.(int64); ok {
return intVal, nil
}

if floatVal, ok := v.(float64); ok {
intVal := int64(floatVal)
return intVal, nil
}

return 0, fmt.Errorf("Incorrect rule priority: %s. Priority must be a number", v)
}

func firewallPolicyWithRulesIsPredefinedRule(rule map[string]interface{}) (bool, error) {
// Priorities from 2147483548 to 2147483647 are reserved and cannot be modified by the user.
const ReservedPriorityStart = 2147483548

priority := rule["priority"]
priorityInt, err := firewallPolicyWithRulesConvertPriorityToInt(priority)

if err != nil {
return false, err
}

return priorityInt >= ReservedPriorityStart, nil
}

func firewallPolicyWithRulesSplitPredefinedRules(allRules []interface{}) ([]interface{}, []interface{}, error) {
predefinedRules := make([]interface{}, 0)
rules := make([]interface{}, 0)
for _, rule := range allRules {
isPredefined, err := firewallPolicyWithRulesIsPredefinedRule(rule.(map[string]interface{}))
if err != nil {
return nil, nil, err
}

if isPredefined {
predefinedRules = append(predefinedRules, rule)
} else {
rules = append(rules, rule)
}
}
return rules, predefinedRules, nil
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
rules, predefinedRules, err := firewallPolicyWithRulesSplitPredefinedRules(res["rules"].([]interface{}))

if err != nil {
return nil, fmt.Errorf("Error occurred while splitting pre-defined rules: %s", err)
}

res["rules"] = rules
res["predefinedRules"] = predefinedRules

config := meta.(*transport_tpg.Config)

if err := d.Set("predefined_rules", flattenComputeFirewallPolicyWithRulesPredefinedRules(predefinedRules, d, config)); err != nil {
return nil, fmt.Errorf("Error occurred while setting pre-defined rules: %s", err)
}

return res, nil
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
delete(obj, "rules") // Rules are not supported in the create API
return obj, nil

Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
data "google_project" "project" {
provider = google-beta
}

resource "google_compute_firewall_policy_with_rules" "<%= ctx[:primary_resource_id] %>" {
short_name = "<%= ctx[:vars]['policy_name'] %>"
description = "Terraform test"
parent = "organizations/<%= ctx[:test_env_vars]['org_id'] %>"
provider = google-beta

rule {
description = "tcp rule"
priority = 1000
enable_logging = true
action = "allow"
direction = "EGRESS"
match {
layer4_config {
ip_protocol = "tcp"
ports = [8080, 7070]
}
dest_ip_ranges = ["11.100.0.1/32"]
dest_fqdns = ["www.yyy.com", "www.zzz.com"]
dest_region_codes = ["HK", "IN"]
dest_threat_intelligences = ["iplist-search-engines-crawlers", "iplist-tor-exit-nodes"]
dest_address_groups = [google_network_security_address_group.address_group_1.id]
}
target_resources = ["https://www.googleapis.com/compute/beta/projects/${data.google_project.project.name}/global/networks/default"]
}
rule {
description = "udp rule"
priority = 2000
enable_logging = false
action = "deny"
direction = "INGRESS"
match {
layer4_config {
ip_protocol = "udp"
}
src_ip_ranges = ["0.0.0.0/0"]
src_fqdns = ["www.abc.com", "www.def.com"]
src_region_codes = ["US", "CA"]
src_threat_intelligences = ["iplist-known-malicious-ips", "iplist-public-clouds"]
src_address_groups = [google_network_security_address_group.address_group_1.id]
}
disabled = true
}
rule {
description = "security profile group rule"
rule_name = "tcp rule"
priority = 3000
enable_logging = false
action = "apply_security_profile_group"
direction = "INGRESS"
match {
layer4_config {
ip_protocol = "tcp"
}
src_ip_ranges = ["0.0.0.0/0"]
}
target_service_accounts = ["[email protected]"]
security_profile_group = "//networksecurity.googleapis.com/${google_network_security_security_profile_group.security_profile_group_1.id}"
tls_inspect = true
}
}

resource "google_network_security_address_group" "address_group_1" {
provider = google-beta
name = "<%= ctx[:vars]['address_group_name'] %>"
parent = "organizations/<%= ctx[:test_env_vars]['org_id'] %>"
description = "Global address group"
location = "global"
items = ["208.80.154.224/32"]
type = "IPV4"
capacity = 100
}

resource "google_network_security_security_profile_group" "security_profile_group_1" {
provider = google-beta
name = "<%= ctx[:vars]['security_profile_group_name'] %>"
parent = "organizations/<%= ctx[:test_env_vars]['org_id'] %>"
description = "my description"
threat_prevention_profile = google_network_security_security_profile.security_profile_1.id
}

resource "google_network_security_security_profile" "security_profile_1" {
provider = google-beta
name = "<%= ctx[:vars]['security_profile_name'] %>"
type = "THREAT_PREVENTION"
parent = "organizations/<%= ctx[:test_env_vars]['org_id'] %>"
location = "global"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
parent := d.Get("parent").(string)
var opRes map[string]interface{}
err = ComputeOrgOperationWaitTimeWithResponse(
config, res, &opRes, parent, "Creating FirewallPolicy", userAgent,
d.Timeout(schema.TimeoutCreate))

if err != nil {
// The resource didn't actually create
d.SetId("")
return fmt.Errorf("Error waiting to create FirewallPolicy: %s", err)
}

policyId, ok := opRes["targetId"]
if !ok {
return fmt.Errorf("Create response didn't contain targetId. Create may not have succeeded.")
}
if err := d.Set("policy_id", policyId.(string)); err != nil {
return fmt.Errorf("Error setting policy_id: %s", err)
}

// Store the ID now.
id, err = tpgresource.ReplaceVars(d, config, "locations/global/firewallPolicies/{{policy_id}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)

url, err = tpgresource.ReplaceVarsForId(d, config, "{{ComputeBasePath}}locations/global/firewallPolicies/{{policy_id}}")
if err != nil {
return err
}

headers = make(http.Header)
res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "GET",
Project: billingProject,
RawURL: url,
UserAgent: userAgent,
Headers: headers,
})
if err != nil {
return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("ComputeFirewallPolicyWithRules %q", d.Id()))
}

if err := d.Set("fingerprint", flattenComputeFirewallPolicyWithRulesFingerprint(res["fingerprint"], d, config)); err != nil {
return fmt.Errorf("Error reading FirewallPolicyWithRules: %s", err)
}

res, err = resourceComputeFirewallPolicyWithRulesDecoder(d, meta, res)
if err != nil {
return err
}

log.Printf("[DEBUG] Updating FirewallPolicyWithRules %q", d.Id())
return resourceComputeFirewallPolicyWithRulesUpdate(d, meta)
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
parent := d.Get("parent").(string)
var opRes map[string]interface{}
err = ComputeOrgOperationWaitTimeWithResponse(
config, res, &opRes, parent, "Deleting FirewallPolicy", userAgent,
d.Timeout(schema.TimeoutCreate))

if err != nil {
// The resource didn't actually delete
return fmt.Errorf("Error waiting to delete FirewallPolicy: %s", err)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
parent := d.Get("parent").(string)
var opRes map[string]interface{}
err = ComputeOrgOperationWaitTimeWithResponse(
config, res, &opRes, parent, "Updating FirewallPolicy", userAgent,
d.Timeout(schema.TimeoutCreate))

if err != nil {
// The resource didn't actually update
return fmt.Errorf("Error waiting to update FirewallPolicy: %s", err)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
config := meta.(*transport_tpg.Config)

predefinedRulesProp, err := expandComputeFirewallPolicyWithRulesRule(d.Get("predefined_rules"), d, config)
if err != nil {
return nil, err
}

rules := obj["rules"].([]interface{})
obj["rules"] = append(rules, predefinedRulesProp)

return obj, nil
Loading

0 comments on commit f6bc823

Please sign in to comment.