diff --git a/.changelog/9320.txt b/.changelog/9320.txt new file mode 100644 index 00000000000..03e9cb43da5 --- /dev/null +++ b/.changelog/9320.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_network_connectivity_policy_based_route` +``` diff --git a/google/provider/provider.go b/google/provider/provider.go index bceabf13dd5..4dcee857e0e 100644 --- a/google/provider/provider.go +++ b/google/provider/provider.go @@ -1021,9 +1021,9 @@ func DatasourceMapWithErrors() (map[string]*schema.Resource, error) { }) } -// Generated resources: 337 +// Generated resources: 338 // Generated IAM resources: 210 -// Total generated resources: 547 +// Total generated resources: 548 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -1459,6 +1459,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_monitoring_custom_service": monitoring.ResourceMonitoringService(), "google_monitoring_slo": monitoring.ResourceMonitoringSlo(), "google_monitoring_uptime_check_config": monitoring.ResourceMonitoringUptimeCheckConfig(), + "google_network_connectivity_policy_based_route": networkconnectivity.ResourceNetworkConnectivityPolicyBasedRoute(), "google_network_connectivity_service_connection_policy": networkconnectivity.ResourceNetworkConnectivityServiceConnectionPolicy(), "google_network_management_connectivity_test": networkmanagement.ResourceNetworkManagementConnectivityTest(), "google_network_security_address_group": networksecurity.ResourceNetworkSecurityAddressGroup(), diff --git a/google/services/networkconnectivity/resource_network_connectivity_policy_based_route.go b/google/services/networkconnectivity/resource_network_connectivity_policy_based_route.go new file mode 100644 index 00000000000..e6ff7b99d92 --- /dev/null +++ b/google/services/networkconnectivity/resource_network_connectivity_policy_based_route.go @@ -0,0 +1,839 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package networkconnectivity + +import ( + "fmt" + "log" + "reflect" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" + "github.com/hashicorp/terraform-provider-google/google/verify" +) + +func ResourceNetworkConnectivityPolicyBasedRoute() *schema.Resource { + return &schema.Resource{ + Create: resourceNetworkConnectivityPolicyBasedRouteCreate, + Read: resourceNetworkConnectivityPolicyBasedRouteRead, + Delete: resourceNetworkConnectivityPolicyBasedRouteDelete, + + Importer: &schema.ResourceImporter{ + State: resourceNetworkConnectivityPolicyBasedRouteImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + }, + + CustomizeDiff: customdiff.All( + tpgresource.SetLabelsDiff, + tpgresource.DefaultProviderProject, + ), + + Schema: map[string]*schema.Schema{ + "filter": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + Description: `The filter to match L4 traffic.`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "protocol_version": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: verify.ValidateEnum([]string{"IPV4"}), + Description: `Internet protocol versions this policy-based route applies to. Possible values: ["IPV4"]`, + }, + "dest_range": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `The destination IP range of outgoing packets that this policy-based route applies to. Default is "0.0.0.0/0" if protocol version is IPv4.`, + Default: "0.0.0.0/0", + }, + "ip_protocol": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `The IP protocol that this policy-based route applies to. Valid values are 'TCP', 'UDP', and 'ALL'. Default is 'ALL'.`, + Default: "ALL", + }, + "src_range": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `The source IP range of outgoing packets that this policy-based route applies to. Default is "0.0.0.0/0" if protocol version is IPv4.`, + Default: "0.0.0.0/0", + }, + }, + }, + }, + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The name of the policy based route.`, + }, + "network": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Fully-qualified URL of the network that this route applies to, for example: projects/my-project/global/networks/my-network.`, + }, + "description": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `An optional description of this resource.`, + }, + "interconnect_attachment": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `The interconnect attachments that this policy-based route applies to.`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "region": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Cloud region to install this policy-based route on for Interconnect attachments. Use 'all' to install it on all Interconnect attachments.`, + }, + }, + }, + ConflictsWith: []string{"virtual_machine"}, + }, + "labels": { + Type: schema.TypeMap, + Optional: true, + ForceNew: true, + Description: `User-defined labels. + + +**Note**: This field is non-authoritative, and will only manage the labels present in your configuration. +Please refer to the field 'effective_labels' for all of the labels present on the resource.`, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "next_hop_ilb_ip": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `The IP address of a global-access-enabled L4 ILB that is the next hop for matching packets.`, + ExactlyOneOf: []string{"next_hop_ilb_ip", "next_hop_other_routes"}, + }, + "next_hop_other_routes": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: verify.ValidateEnum([]string{"DEFAULT_ROUTING", ""}), + Description: `Other routes that will be referenced to determine the next hop of the packet. Possible values: ["DEFAULT_ROUTING"]`, + ExactlyOneOf: []string{"next_hop_ilb_ip", "next_hop_other_routes"}, + }, + "priority": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + Description: `The priority of this policy-based route. Priority is used to break ties in cases where there are more than one matching policy-based routes found. In cases where multiple policy-based routes are matched, the one with the lowest-numbered priority value wins. The default value is 1000. The priority value must be from 1 to 65535, inclusive.`, + Default: 1000, + }, + "virtual_machine": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `VM instances to which this policy-based route applies to.`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "tags": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + Description: `A list of VM instance tags that this policy-based route applies to. VM instances that have ANY of tags specified here will install this PBR.`, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + ConflictsWith: []string{"interconnect_attachment"}, + }, + "create_time": { + Type: schema.TypeString, + Computed: true, + Description: `Time when the policy-based route was created.`, + }, + "effective_labels": { + Type: schema.TypeMap, + Computed: true, + ForceNew: true, + Description: `All of labels (key/value pairs) present on the resource in GCP, including the labels configured through Terraform, other clients and services.`, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "kind": { + Type: schema.TypeString, + Computed: true, + Description: `Type of this resource.`, + }, + "terraform_labels": { + Type: schema.TypeMap, + Computed: true, + Description: `The combination of labels configured directly on the resource + and default labels configured on the provider.`, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "update_time": { + Type: schema.TypeString, + Computed: true, + Description: `Time when the policy-based route was created.`, + }, + "warnings": { + Type: schema.TypeList, + Computed: true, + Description: `If potential misconfigurations are detected for this route, this field will be populated with warning messages.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "code": { + Type: schema.TypeString, + Computed: true, + Description: `A warning code, if applicable.`, + }, + "data": { + Type: schema.TypeMap, + Computed: true, + Description: `Metadata about this warning in key: value format. The key should provides more detail on the warning being returned. For example, for warnings where there are no results in a list request for a particular zone, this key might be scope and the key value might be the zone name. Other examples might be a key indicating a deprecated resource and a suggested replacement.`, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "warning_message": { + Type: schema.TypeString, + Computed: true, + Description: `A human-readable description of the warning code.`, + }, + }, + }, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceNetworkConnectivityPolicyBasedRouteCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + obj := make(map[string]interface{}) + descriptionProp, err := expandNetworkConnectivityPolicyBasedRouteDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !tpgresource.IsEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + networkProp, err := expandNetworkConnectivityPolicyBasedRouteNetwork(d.Get("network"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("network"); !tpgresource.IsEmptyValue(reflect.ValueOf(networkProp)) && (ok || !reflect.DeepEqual(v, networkProp)) { + obj["network"] = networkProp + } + filterProp, err := expandNetworkConnectivityPolicyBasedRouteFilter(d.Get("filter"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("filter"); !tpgresource.IsEmptyValue(reflect.ValueOf(filterProp)) && (ok || !reflect.DeepEqual(v, filterProp)) { + obj["filter"] = filterProp + } + nextHopOtherRoutesProp, err := expandNetworkConnectivityPolicyBasedRouteNextHopOtherRoutes(d.Get("next_hop_other_routes"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("next_hop_other_routes"); !tpgresource.IsEmptyValue(reflect.ValueOf(nextHopOtherRoutesProp)) && (ok || !reflect.DeepEqual(v, nextHopOtherRoutesProp)) { + obj["nextHopOtherRoutes"] = nextHopOtherRoutesProp + } + nextHopIlbIpProp, err := expandNetworkConnectivityPolicyBasedRouteNextHopIlbIp(d.Get("next_hop_ilb_ip"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("next_hop_ilb_ip"); !tpgresource.IsEmptyValue(reflect.ValueOf(nextHopIlbIpProp)) && (ok || !reflect.DeepEqual(v, nextHopIlbIpProp)) { + obj["nextHopIlbIp"] = nextHopIlbIpProp + } + priorityProp, err := expandNetworkConnectivityPolicyBasedRoutePriority(d.Get("priority"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("priority"); !tpgresource.IsEmptyValue(reflect.ValueOf(priorityProp)) && (ok || !reflect.DeepEqual(v, priorityProp)) { + obj["priority"] = priorityProp + } + virtualMachineProp, err := expandNetworkConnectivityPolicyBasedRouteVirtualMachine(d.Get("virtual_machine"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("virtual_machine"); !tpgresource.IsEmptyValue(reflect.ValueOf(virtualMachineProp)) && (ok || !reflect.DeepEqual(v, virtualMachineProp)) { + obj["virtualMachine"] = virtualMachineProp + } + interconnectAttachmentProp, err := expandNetworkConnectivityPolicyBasedRouteInterconnectAttachment(d.Get("interconnect_attachment"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("interconnect_attachment"); !tpgresource.IsEmptyValue(reflect.ValueOf(interconnectAttachmentProp)) && (ok || !reflect.DeepEqual(v, interconnectAttachmentProp)) { + obj["interconnectAttachment"] = interconnectAttachmentProp + } + labelsProp, err := expandNetworkConnectivityPolicyBasedRouteEffectiveLabels(d.Get("effective_labels"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("effective_labels"); !tpgresource.IsEmptyValue(reflect.ValueOf(labelsProp)) && (ok || !reflect.DeepEqual(v, labelsProp)) { + obj["labels"] = labelsProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{NetworkConnectivityBasePath}}projects/{{project}}/locations/global/policyBasedRoutes?policyBasedRouteId={{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new PolicyBasedRoute: %#v", obj) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for PolicyBasedRoute: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "POST", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutCreate), + }) + if err != nil { + return fmt.Errorf("Error creating PolicyBasedRoute: %s", err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/global/policyBasedRoutes/{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + err = NetworkConnectivityOperationWaitTime( + config, res, project, "Creating PolicyBasedRoute", userAgent, + d.Timeout(schema.TimeoutCreate)) + + if err != nil { + // The resource didn't actually create + d.SetId("") + return fmt.Errorf("Error waiting to create PolicyBasedRoute: %s", err) + } + + log.Printf("[DEBUG] Finished creating PolicyBasedRoute %q: %#v", d.Id(), res) + + return resourceNetworkConnectivityPolicyBasedRouteRead(d, meta) +} + +func resourceNetworkConnectivityPolicyBasedRouteRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + url, err := tpgresource.ReplaceVars(d, config, "{{NetworkConnectivityBasePath}}projects/{{project}}/locations/global/policyBasedRoutes/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for PolicyBasedRoute: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + }) + if err != nil { + return transport_tpg.HandleNotFoundError(err, d, fmt.Sprintf("NetworkConnectivityPolicyBasedRoute %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + + if err := d.Set("description", flattenNetworkConnectivityPolicyBasedRouteDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("labels", flattenNetworkConnectivityPolicyBasedRouteLabels(res["labels"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("network", flattenNetworkConnectivityPolicyBasedRouteNetwork(res["network"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("filter", flattenNetworkConnectivityPolicyBasedRouteFilter(res["filter"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("next_hop_other_routes", flattenNetworkConnectivityPolicyBasedRouteNextHopOtherRoutes(res["nextHopOtherRoutes"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("next_hop_ilb_ip", flattenNetworkConnectivityPolicyBasedRouteNextHopIlbIp(res["nextHopIlbIp"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("priority", flattenNetworkConnectivityPolicyBasedRoutePriority(res["priority"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("virtual_machine", flattenNetworkConnectivityPolicyBasedRouteVirtualMachine(res["virtualMachine"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("interconnect_attachment", flattenNetworkConnectivityPolicyBasedRouteInterconnectAttachment(res["interconnectAttachment"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("create_time", flattenNetworkConnectivityPolicyBasedRouteCreateTime(res["createTime"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("update_time", flattenNetworkConnectivityPolicyBasedRouteUpdateTime(res["updateTime"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("kind", flattenNetworkConnectivityPolicyBasedRouteKind(res["kind"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("warnings", flattenNetworkConnectivityPolicyBasedRouteWarnings(res["warnings"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("terraform_labels", flattenNetworkConnectivityPolicyBasedRouteTerraformLabels(res["labels"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + if err := d.Set("effective_labels", flattenNetworkConnectivityPolicyBasedRouteEffectiveLabels(res["labels"], d, config)); err != nil { + return fmt.Errorf("Error reading PolicyBasedRoute: %s", err) + } + + return nil +} + +func resourceNetworkConnectivityPolicyBasedRouteDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*transport_tpg.Config) + userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for PolicyBasedRoute: %s", err) + } + billingProject = project + + url, err := tpgresource.ReplaceVars(d, config, "{{NetworkConnectivityBasePath}}projects/{{project}}/locations/global/policyBasedRoutes/{{name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting PolicyBasedRoute %q", d.Id()) + + // err == nil indicates that the billing_project value was found + if bp, err := tpgresource.GetBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "DELETE", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutDelete), + }) + if err != nil { + return transport_tpg.HandleNotFoundError(err, d, "PolicyBasedRoute") + } + + err = NetworkConnectivityOperationWaitTime( + config, res, project, "Deleting PolicyBasedRoute", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting PolicyBasedRoute %q: %#v", d.Id(), res) + return nil +} + +func resourceNetworkConnectivityPolicyBasedRouteImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*transport_tpg.Config) + if err := tpgresource.ParseImportId([]string{ + "^projects/(?P[^/]+)/locations/global/policyBasedRoutes/(?P[^/]+)$", + "^(?P[^/]+)/(?P[^/]+)$", + "^(?P[^/]+)$", + }, d, config); err != nil { + return nil, err + } + + // Replace import id for the resource id + id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/global/policyBasedRoutes/{{name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenNetworkConnectivityPolicyBasedRouteDescription(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteLabels(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return v + } + + transformed := make(map[string]interface{}) + if l, ok := d.GetOkExists("labels"); ok { + for k := range l.(map[string]interface{}) { + transformed[k] = v.(map[string]interface{})[k] + } + } + + return transformed +} + +func flattenNetworkConnectivityPolicyBasedRouteNetwork(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteFilter(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return nil + } + original := v.(map[string]interface{}) + if len(original) == 0 { + return nil + } + transformed := make(map[string]interface{}) + transformed["protocol_version"] = + flattenNetworkConnectivityPolicyBasedRouteFilterProtocolVersion(original["protocolVersion"], d, config) + transformed["ip_protocol"] = + flattenNetworkConnectivityPolicyBasedRouteFilterIpProtocol(original["ipProtocol"], d, config) + transformed["src_range"] = + flattenNetworkConnectivityPolicyBasedRouteFilterSrcRange(original["srcRange"], d, config) + transformed["dest_range"] = + flattenNetworkConnectivityPolicyBasedRouteFilterDestRange(original["destRange"], d, config) + return []interface{}{transformed} +} +func flattenNetworkConnectivityPolicyBasedRouteFilterProtocolVersion(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteFilterIpProtocol(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteFilterSrcRange(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteFilterDestRange(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteNextHopOtherRoutes(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteNextHopIlbIp(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRoutePriority(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + // Handles the string fixed64 format + if strVal, ok := v.(string); ok { + if intVal, err := tpgresource.StringToFixed64(strVal); err == nil { + return intVal + } + } + + // number values are represented as float64 + if floatVal, ok := v.(float64); ok { + intVal := int(floatVal) + return intVal + } + + return v // let terraform core handle it otherwise +} + +func flattenNetworkConnectivityPolicyBasedRouteVirtualMachine(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return nil + } + original := v.(map[string]interface{}) + if len(original) == 0 { + return nil + } + transformed := make(map[string]interface{}) + transformed["tags"] = + flattenNetworkConnectivityPolicyBasedRouteVirtualMachineTags(original["tags"], d, config) + return []interface{}{transformed} +} +func flattenNetworkConnectivityPolicyBasedRouteVirtualMachineTags(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteInterconnectAttachment(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return nil + } + original := v.(map[string]interface{}) + if len(original) == 0 { + return nil + } + transformed := make(map[string]interface{}) + transformed["region"] = + flattenNetworkConnectivityPolicyBasedRouteInterconnectAttachmentRegion(original["region"], d, config) + return []interface{}{transformed} +} +func flattenNetworkConnectivityPolicyBasedRouteInterconnectAttachmentRegion(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteCreateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteUpdateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteKind(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteWarnings(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return v + } + l := v.([]interface{}) + transformed := make([]interface{}, 0, len(l)) + for _, raw := range l { + original := raw.(map[string]interface{}) + if len(original) < 1 { + // Do not include empty json objects coming back from the api + continue + } + transformed = append(transformed, map[string]interface{}{ + "code": flattenNetworkConnectivityPolicyBasedRouteWarningsCode(original["code"], d, config), + "data": flattenNetworkConnectivityPolicyBasedRouteWarningsData(original["data"], d, config), + "warning_message": flattenNetworkConnectivityPolicyBasedRouteWarningsWarningMessage(original["warningMessage"], d, config), + }) + } + return transformed +} +func flattenNetworkConnectivityPolicyBasedRouteWarningsCode(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteWarningsData(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteWarningsWarningMessage(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenNetworkConnectivityPolicyBasedRouteTerraformLabels(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + if v == nil { + return v + } + + transformed := make(map[string]interface{}) + if l, ok := d.GetOkExists("terraform_labels"); ok { + for k := range l.(map[string]interface{}) { + transformed[k] = v.(map[string]interface{})[k] + } + } + + return transformed +} + +func flattenNetworkConnectivityPolicyBasedRouteEffectiveLabels(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandNetworkConnectivityPolicyBasedRouteDescription(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkConnectivityPolicyBasedRouteNetwork(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkConnectivityPolicyBasedRouteFilter(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + l := v.([]interface{}) + if len(l) == 0 || l[0] == nil { + return nil, nil + } + raw := l[0] + original := raw.(map[string]interface{}) + transformed := make(map[string]interface{}) + + transformedProtocolVersion, err := expandNetworkConnectivityPolicyBasedRouteFilterProtocolVersion(original["protocol_version"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedProtocolVersion); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["protocolVersion"] = transformedProtocolVersion + } + + transformedIpProtocol, err := expandNetworkConnectivityPolicyBasedRouteFilterIpProtocol(original["ip_protocol"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedIpProtocol); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["ipProtocol"] = transformedIpProtocol + } + + transformedSrcRange, err := expandNetworkConnectivityPolicyBasedRouteFilterSrcRange(original["src_range"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedSrcRange); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["srcRange"] = transformedSrcRange + } + + transformedDestRange, err := expandNetworkConnectivityPolicyBasedRouteFilterDestRange(original["dest_range"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedDestRange); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["destRange"] = transformedDestRange + } + + return transformed, nil +} + +func expandNetworkConnectivityPolicyBasedRouteFilterProtocolVersion(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkConnectivityPolicyBasedRouteFilterIpProtocol(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkConnectivityPolicyBasedRouteFilterSrcRange(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkConnectivityPolicyBasedRouteFilterDestRange(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkConnectivityPolicyBasedRouteNextHopOtherRoutes(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkConnectivityPolicyBasedRouteNextHopIlbIp(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkConnectivityPolicyBasedRoutePriority(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkConnectivityPolicyBasedRouteVirtualMachine(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + l := v.([]interface{}) + if len(l) == 0 || l[0] == nil { + return nil, nil + } + raw := l[0] + original := raw.(map[string]interface{}) + transformed := make(map[string]interface{}) + + transformedTags, err := expandNetworkConnectivityPolicyBasedRouteVirtualMachineTags(original["tags"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedTags); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["tags"] = transformedTags + } + + return transformed, nil +} + +func expandNetworkConnectivityPolicyBasedRouteVirtualMachineTags(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkConnectivityPolicyBasedRouteInterconnectAttachment(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + l := v.([]interface{}) + if len(l) == 0 || l[0] == nil { + return nil, nil + } + raw := l[0] + original := raw.(map[string]interface{}) + transformed := make(map[string]interface{}) + + transformedRegion, err := expandNetworkConnectivityPolicyBasedRouteInterconnectAttachmentRegion(original["region"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedRegion); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["region"] = transformedRegion + } + + return transformed, nil +} + +func expandNetworkConnectivityPolicyBasedRouteInterconnectAttachmentRegion(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandNetworkConnectivityPolicyBasedRouteEffectiveLabels(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (map[string]string, error) { + if v == nil { + return map[string]string{}, nil + } + m := make(map[string]string) + for k, val := range v.(map[string]interface{}) { + m[k] = val.(string) + } + return m, nil +} diff --git a/google/services/networkconnectivity/resource_network_connectivity_policy_based_route_generated_test.go b/google/services/networkconnectivity/resource_network_connectivity_policy_based_route_generated_test.go new file mode 100644 index 00000000000..a0a6be8d56d --- /dev/null +++ b/google/services/networkconnectivity/resource_network_connectivity_policy_based_route_generated_test.go @@ -0,0 +1,177 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package networkconnectivity_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func TestAccNetworkConnectivityPolicyBasedRoute_networkConnectivityPolicyBasedRouteBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckNetworkConnectivityPolicyBasedRouteDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccNetworkConnectivityPolicyBasedRoute_networkConnectivityPolicyBasedRouteBasicExample(context), + }, + { + ResourceName: "google_network_connectivity_policy_based_route.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"name", "labels", "terraform_labels"}, + }, + }, + }) +} + +func testAccNetworkConnectivityPolicyBasedRoute_networkConnectivityPolicyBasedRouteBasicExample(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_network_connectivity_policy_based_route" "default" { + name = "tf-test-my-pbr%{random_suffix}" + network = google_compute_network.my_network.id + filter { + protocol_version = "IPV4" + } + next_hop_other_routes = "DEFAULT_ROUTING" +} + +resource "google_compute_network" "my_network" { + name = "tf-test-my-network%{random_suffix}" + auto_create_subnetworks = false +} +`, context) +} + +func TestAccNetworkConnectivityPolicyBasedRoute_networkConnectivityPolicyBasedRouteFullExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckNetworkConnectivityPolicyBasedRouteDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccNetworkConnectivityPolicyBasedRoute_networkConnectivityPolicyBasedRouteFullExample(context), + }, + { + ResourceName: "google_network_connectivity_policy_based_route.default", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"name", "labels", "terraform_labels"}, + }, + }, + }) +} + +func testAccNetworkConnectivityPolicyBasedRoute_networkConnectivityPolicyBasedRouteFullExample(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_network_connectivity_policy_based_route" "default" { + name = "tf-test-my-pbr%{random_suffix}" + description = "My routing policy" + network = google_compute_network.my_network.id + priority = 2302 + + filter { + protocol_version = "IPV4" + ip_protocol = "UDP" + src_range = "10.0.0.0/24" + dest_range = "0.0.0.0/0" + } + next_hop_ilb_ip = google_compute_global_address.ilb.address + + virtual_machine { + tags = ["restricted"] + } + + labels = { + env = "default" + } +} + +resource "google_compute_network" "my_network" { + name = "tf-test-my-network%{random_suffix}" + auto_create_subnetworks = false +} + +# This example substitutes an arbitrary internal IP for an internal network +# load balancer for brevity. Consult https://cloud.google.com/load-balancing/docs/internal +# to set one up. +resource "google_compute_global_address" "ilb" { + name = "tf-test-my-ilb%{random_suffix}" +} +`, context) +} + +func testAccCheckNetworkConnectivityPolicyBasedRouteDestroyProducer(t *testing.T) func(s *terraform.State) error { + return func(s *terraform.State) error { + for name, rs := range s.RootModule().Resources { + if rs.Type != "google_network_connectivity_policy_based_route" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := acctest.GoogleProviderConfig(t) + + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{NetworkConnectivityBasePath}}projects/{{project}}/locations/global/policyBasedRoutes/{{name}}") + if err != nil { + return err + } + + billingProject := "" + + if config.BillingProject != "" { + billingProject = config.BillingProject + } + + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: billingProject, + RawURL: url, + UserAgent: config.UserAgent, + }) + if err == nil { + return fmt.Errorf("NetworkConnectivityPolicyBasedRoute still exists at %s", url) + } + } + + return nil + } +} diff --git a/google/services/networkconnectivity/resource_network_connectivity_policy_based_route_sweeper.go b/google/services/networkconnectivity/resource_network_connectivity_policy_based_route_sweeper.go new file mode 100644 index 00000000000..aec53c19efc --- /dev/null +++ b/google/services/networkconnectivity/resource_network_connectivity_policy_based_route_sweeper.go @@ -0,0 +1,139 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** Type: MMv1 *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package networkconnectivity + +import ( + "context" + "log" + "strings" + "testing" + + "github.com/hashicorp/terraform-provider-google/google/envvar" + "github.com/hashicorp/terraform-provider-google/google/sweeper" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func init() { + sweeper.AddTestSweepers("NetworkConnectivityPolicyBasedRoute", testSweepNetworkConnectivityPolicyBasedRoute) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepNetworkConnectivityPolicyBasedRoute(region string) error { + resourceName := "NetworkConnectivityPolicyBasedRoute" + log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName) + + config, err := sweeper.SharedConfigForRegion(region) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error getting shared config for region: %s", err) + return err + } + + err = config.LoadAndValidate(context.Background()) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error loading: %s", err) + return err + } + + t := &testing.T{} + billingId := envvar.GetTestBillingAccountFromEnv(t) + + // Setup variables to replace in list template + d := &tpgresource.ResourceDataMock{ + FieldsInSchema: map[string]interface{}{ + "project": config.Project, + "region": region, + "location": region, + "zone": "-", + "billing_account": billingId, + }, + } + + listTemplate := strings.Split("https://networkconnectivity.googleapis.com/v1/projects/{{project}}/locations/global/policyBasedRoutes", "?")[0] + listUrl, err := tpgresource.ReplaceVars(d, config, listTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err) + return nil + } + + res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "GET", + Project: config.Project, + RawURL: listUrl, + UserAgent: config.UserAgent, + }) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) + return nil + } + + resourceList, ok := res["policyBasedRoutes"] + if !ok { + log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.") + return nil + } + + rl := resourceList.([]interface{}) + + log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName) + // Keep count of items that aren't sweepable for logging. + nonPrefixCount := 0 + for _, ri := range rl { + obj := ri.(map[string]interface{}) + if obj["name"] == nil { + log.Printf("[INFO][SWEEPER_LOG] %s resource name was nil", resourceName) + return nil + } + + name := tpgresource.GetResourceNameFromSelfLink(obj["name"].(string)) + // Skip resources that shouldn't be sweeped + if !sweeper.IsSweepableTestResource(name) { + nonPrefixCount++ + continue + } + + deleteTemplate := "https://networkconnectivity.googleapis.com/v1/projects/{{project}}/locations/global/policyBasedRoutes/{{name}}" + deleteUrl, err := tpgresource.ReplaceVars(d, config, deleteTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing delete url: %s", err) + return nil + } + deleteUrl = deleteUrl + name + + // Don't wait on operations as we may have a lot to delete + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "DELETE", + Project: config.Project, + RawURL: deleteUrl, + UserAgent: config.UserAgent, + }) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error deleting for url %s : %s", deleteUrl, err) + } else { + log.Printf("[INFO][SWEEPER_LOG] Sent delete request for %s resource: %s", resourceName, name) + } + } + + if nonPrefixCount > 0 { + log.Printf("[INFO][SWEEPER_LOG] %d items were non-sweepable and skipped.", nonPrefixCount) + } + + return nil +} diff --git a/website/docs/r/network_connectivity_policy_based_route.html.markdown b/website/docs/r/network_connectivity_policy_based_route.html.markdown new file mode 100644 index 00000000000..72d0d891964 --- /dev/null +++ b/website/docs/r/network_connectivity_policy_based_route.html.markdown @@ -0,0 +1,268 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** AUTO GENERATED CODE *** Type: MMv1 *** +# +# ---------------------------------------------------------------------------- +# +# This file is automatically generated by Magic Modules and manual +# changes will be clobbered when the file is regenerated. +# +# Please read more about how to change this file in +# .github/CONTRIBUTING.md. +# +# ---------------------------------------------------------------------------- +subcategory: "Network Connectivity" +description: |- + Policy-based Routes are more powerful routes that route L4 network traffic based on not just destination IP, but also source IP, protocol and more. +--- + +# google\_network\_connectivity\_policy\_based\_route + +Policy-based Routes are more powerful routes that route L4 network traffic based on not just destination IP, but also source IP, protocol and more. A Policy-based Route always take precedence when it conflicts with other types of routes. + + +To get more information about PolicyBasedRoute, see: + +* [API documentation](https://cloud.google.com/network-connectivity/docs/reference/networkconnectivity/rest/v1/projects.locations.global.policyBasedRoutes) +* How-to Guides + * [Use policy-based routes](https://cloud.google.com/vpc/docs/use-policy-based-routes#api) + + +## Example Usage - Network Connectivity Policy Based Route Basic + + +```hcl +resource "google_network_connectivity_policy_based_route" "default" { + name = "my-pbr" + network = google_compute_network.my_network.id + filter { + protocol_version = "IPV4" + } + next_hop_other_routes = "DEFAULT_ROUTING" +} + +resource "google_compute_network" "my_network" { + name = "my-network" + auto_create_subnetworks = false +} +``` + +## Example Usage - Network Connectivity Policy Based Route Full + + +```hcl +resource "google_network_connectivity_policy_based_route" "default" { + name = "my-pbr" + description = "My routing policy" + network = google_compute_network.my_network.id + priority = 2302 + + filter { + protocol_version = "IPV4" + ip_protocol = "UDP" + src_range = "10.0.0.0/24" + dest_range = "0.0.0.0/0" + } + next_hop_ilb_ip = google_compute_global_address.ilb.address + + virtual_machine { + tags = ["restricted"] + } + + labels = { + env = "default" + } +} + +resource "google_compute_network" "my_network" { + name = "my-network" + auto_create_subnetworks = false +} + +# This example substitutes an arbitrary internal IP for an internal network +# load balancer for brevity. Consult https://cloud.google.com/load-balancing/docs/internal +# to set one up. +resource "google_compute_global_address" "ilb" { + name = "my-ilb" +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `name` - + (Required) + The name of the policy based route. + +* `network` - + (Required) + Fully-qualified URL of the network that this route applies to, for example: projects/my-project/global/networks/my-network. + +* `filter` - + (Required) + The filter to match L4 traffic. + Structure is [documented below](#nested_filter). + + +The `filter` block supports: + +* `protocol_version` - + (Required) + Internet protocol versions this policy-based route applies to. + Possible values are: `IPV4`. + +* `ip_protocol` - + (Optional) + The IP protocol that this policy-based route applies to. Valid values are 'TCP', 'UDP', and 'ALL'. Default is 'ALL'. + +* `src_range` - + (Optional) + The source IP range of outgoing packets that this policy-based route applies to. Default is "0.0.0.0/0" if protocol version is IPv4. + +* `dest_range` - + (Optional) + The destination IP range of outgoing packets that this policy-based route applies to. Default is "0.0.0.0/0" if protocol version is IPv4. + +- - - + + +* `description` - + (Optional) + An optional description of this resource. + +* `labels` - + (Optional) + User-defined labels. + + **Note**: This field is non-authoritative, and will only manage the labels present in your configuration. + Please refer to the field `effective_labels` for all of the labels present on the resource. + +* `next_hop_other_routes` - + (Optional) + Other routes that will be referenced to determine the next hop of the packet. + Possible values are: `DEFAULT_ROUTING`. + +* `next_hop_ilb_ip` - + (Optional) + The IP address of a global-access-enabled L4 ILB that is the next hop for matching packets. + +* `priority` - + (Optional) + The priority of this policy-based route. Priority is used to break ties in cases where there are more than one matching policy-based routes found. In cases where multiple policy-based routes are matched, the one with the lowest-numbered priority value wins. The default value is 1000. The priority value must be from 1 to 65535, inclusive. + +* `virtual_machine` - + (Optional) + VM instances to which this policy-based route applies to. + Structure is [documented below](#nested_virtual_machine). + +* `interconnect_attachment` - + (Optional) + The interconnect attachments that this policy-based route applies to. + Structure is [documented below](#nested_interconnect_attachment). + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + +The `virtual_machine` block supports: + +* `tags` - + (Required) + A list of VM instance tags that this policy-based route applies to. VM instances that have ANY of tags specified here will install this PBR. + +The `interconnect_attachment` block supports: + +* `region` - + (Required) + Cloud region to install this policy-based route on for Interconnect attachments. Use `all` to install it on all Interconnect attachments. + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `projects/{{project}}/locations/global/policyBasedRoutes/{{name}}` + +* `create_time` - + Time when the policy-based route was created. + +* `update_time` - + Time when the policy-based route was created. + +* `kind` - + Type of this resource. + +* `warnings` - + If potential misconfigurations are detected for this route, this field will be populated with warning messages. + Structure is [documented below](#nested_warnings). + +* `terraform_labels` - + The combination of labels configured directly on the resource + and default labels configured on the provider. + +* `effective_labels` - + All of labels (key/value pairs) present on the resource in GCP, including the labels configured through Terraform, other clients and services. + + +The `warnings` block contains: + +* `code` - + (Output) + A warning code, if applicable. + +* `data` - + (Output) + Metadata about this warning in key: value format. The key should provides more detail on the warning being returned. For example, for warnings where there are no results in a list request for a particular zone, this key might be scope and the key value might be the zone name. Other examples might be a key indicating a deprecated resource and a suggested replacement. + +* `warning_message` - + (Output) + A human-readable description of the warning code. + +## Timeouts + +This resource provides the following +[Timeouts](https://developer.hashicorp.com/terraform/plugin/sdkv2/resources/retries-and-customizable-timeouts) configuration options: + +- `create` - Default is 30 minutes. +- `delete` - Default is 30 minutes. + +## Import + + +PolicyBasedRoute can be imported using any of these accepted formats: + +* `projects/{{project}}/locations/global/policyBasedRoutes/{{name}}` +* `{{project}}/{{name}}` +* `{{name}}` + + +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import PolicyBasedRoute using one of the formats above. For example: + +```tf +import { + id = "projects/{{project}}/locations/global/policyBasedRoutes/{{name}}" + to = google_network_connectivity_policy_based_route.default +} +``` + +When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), PolicyBasedRoute can be imported using one of the formats above. For example: + +``` +$ terraform import google_network_connectivity_policy_based_route.default projects/{{project}}/locations/global/policyBasedRoutes/{{name}} +$ terraform import google_network_connectivity_policy_based_route.default {{project}}/{{name}} +$ terraform import google_network_connectivity_policy_based_route.default {{name}} +``` + +## User Project Overrides + +This resource supports [User Project Overrides](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#user_project_override).