diff --git a/.changelog/8308.txt b/.changelog/8308.txt new file mode 100644 index 00000000000..bd942844c1a --- /dev/null +++ b/.changelog/8308.txt @@ -0,0 +1,6 @@ +```release-note:new-resource +`google_dns_response_policy` (ga) +``` +```release-note:new-resource +`google_dns_response_policy_rule` (ga) +``` diff --git a/google/provider/provider.go b/google/provider/provider.go index 70a5b187dc4..dcdc2c43840 100644 --- a/google/provider/provider.go +++ b/google/provider/provider.go @@ -939,9 +939,9 @@ func DatasourceMapWithErrors() (map[string]*schema.Resource, error) { }) } -// Generated resources: 298 +// Generated resources: 300 // Generated IAM resources: 198 -// Total generated resources: 496 +// Total generated resources: 498 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -1242,6 +1242,8 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_dns_managed_zone_iam_member": tpgiamresource.ResourceIamMember(dns.DNSManagedZoneIamSchema, dns.DNSManagedZoneIamUpdaterProducer, dns.DNSManagedZoneIdParseFunc), "google_dns_managed_zone_iam_policy": tpgiamresource.ResourceIamPolicy(dns.DNSManagedZoneIamSchema, dns.DNSManagedZoneIamUpdaterProducer, dns.DNSManagedZoneIdParseFunc), "google_dns_policy": dns.ResourceDNSPolicy(), + "google_dns_response_policy": dns.ResourceDNSResponsePolicy(), + "google_dns_response_policy_rule": dns.ResourceDNSResponsePolicyRule(), "google_document_ai_processor": documentai.ResourceDocumentAIProcessor(), "google_document_ai_processor_default_version": documentai.ResourceDocumentAIProcessorDefaultVersion(), "google_essential_contacts_contact": essentialcontacts.ResourceEssentialContactsContact(), diff --git a/google/resource_dns_response_policy_generated_test.go b/google/resource_dns_response_policy_generated_test.go new file mode 100644 index 00000000000..98f164c7106 --- /dev/null +++ b/google/resource_dns_response_policy_generated_test.go @@ -0,0 +1,168 @@ +// 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 google + +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 TestAccDNSResponsePolicy_dnsResponsePolicyBasicExample(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: testAccCheckDNSResponsePolicyDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccDNSResponsePolicy_dnsResponsePolicyBasicExample(context), + }, + { + ResourceName: "google_dns_response_policy.example-response-policy", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccDNSResponsePolicy_dnsResponsePolicyBasicExample(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_compute_network" "network-1" { + name = "tf-test-network-1%{random_suffix}" + auto_create_subnetworks = false +} + +resource "google_compute_network" "network-2" { + name = "tf-test-network-2%{random_suffix}" + auto_create_subnetworks = false +} + +resource "google_compute_subnetwork" "subnetwork-1" { + name = google_compute_network.network-1.name + network = google_compute_network.network-1.name + ip_cidr_range = "10.0.36.0/24" + region = "us-central1" + private_ip_google_access = true + + secondary_ip_range { + range_name = "pod" + ip_cidr_range = "10.0.0.0/19" + } + + secondary_ip_range { + range_name = "svc" + ip_cidr_range = "10.0.32.0/22" + } +} + +resource "google_container_cluster" "cluster-1" { + name = "tf-test-cluster-1%{random_suffix}" + location = "us-central1-c" + initial_node_count = 1 + + networking_mode = "VPC_NATIVE" + default_snat_status { + disabled = true + } + network = google_compute_network.network-1.name + subnetwork = google_compute_subnetwork.subnetwork-1.name + + private_cluster_config { + enable_private_endpoint = true + enable_private_nodes = true + master_ipv4_cidr_block = "10.42.0.0/28" + master_global_access_config { + enabled = true + } + } + master_authorized_networks_config { + } + ip_allocation_policy { + cluster_secondary_range_name = google_compute_subnetwork.subnetwork-1.secondary_ip_range[0].range_name + services_secondary_range_name = google_compute_subnetwork.subnetwork-1.secondary_ip_range[1].range_name + } +} + +resource "google_dns_response_policy" "example-response-policy" { + response_policy_name = "tf-test-example-response-policy%{random_suffix}" + + networks { + network_url = google_compute_network.network-1.id + } + networks { + network_url = google_compute_network.network-2.id + } + gke_clusters { + gke_cluster_name = google_container_cluster.cluster-1.id + } +} +`, context) +} + +func testAccCheckDNSResponsePolicyDestroyProducer(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_dns_response_policy" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := acctest.GoogleProviderConfig(t) + + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{DNSBasePath}}projects/{{project}}/responsePolicies/{{response_policy_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("DNSResponsePolicy still exists at %s", url) + } + } + + return nil + } +} diff --git a/google/resource_dns_response_policy_rule_generated_test.go b/google/resource_dns_response_policy_rule_generated_test.go new file mode 100644 index 00000000000..0840f7fb891 --- /dev/null +++ b/google/resource_dns_response_policy_rule_generated_test.go @@ -0,0 +1,136 @@ +// 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 google + +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 TestAccDNSResponsePolicyRule_dnsResponsePolicyRuleBasicExample(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: testAccCheckDNSResponsePolicyRuleDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccDNSResponsePolicyRule_dnsResponsePolicyRuleBasicExample(context), + }, + { + ResourceName: "google_dns_response_policy_rule.example-response-policy-rule", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"response_policy"}, + }, + }, + }) +} + +func testAccDNSResponsePolicyRule_dnsResponsePolicyRuleBasicExample(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_compute_network" "network-1" { + name = "tf-test-network-1%{random_suffix}" + auto_create_subnetworks = false +} + +resource "google_compute_network" "network-2" { + name = "tf-test-network-2%{random_suffix}" + auto_create_subnetworks = false +} + +resource "google_dns_response_policy" "response-policy" { + response_policy_name = "tf-test-example-response-policy%{random_suffix}" + + networks { + network_url = google_compute_network.network-1.id + } + networks { + network_url = google_compute_network.network-2.id + } +} + +resource "google_dns_response_policy_rule" "example-response-policy-rule" { + response_policy = google_dns_response_policy.response-policy.response_policy_name + rule_name = "tf-test-example-rule%{random_suffix}" + dns_name = "dns.example.com." + + local_data { + local_datas { + name = "dns.example.com." + type = "A" + ttl = 300 + rrdatas = ["192.0.2.91"] + } + } + +} +`, context) +} + +func testAccCheckDNSResponsePolicyRuleDestroyProducer(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_dns_response_policy_rule" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := acctest.GoogleProviderConfig(t) + + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{DNSBasePath}}projects/{{project}}/responsePolicies/{{response_policy}}/rules/{{rule_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("DNSResponsePolicyRule still exists at %s", url) + } + } + + return nil + } +} diff --git a/google/services/dns/resource_dns_response_policy.go b/google/services/dns/resource_dns_response_policy.go new file mode 100644 index 00000000000..d5b89a86538 --- /dev/null +++ b/google/services/dns/resource_dns_response_policy.go @@ -0,0 +1,537 @@ +// 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 dns + +import ( + "fmt" + "log" + "reflect" + "strings" + "time" + + "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" +) + +func ResourceDNSResponsePolicy() *schema.Resource { + return &schema.Resource{ + Create: resourceDNSResponsePolicyCreate, + Read: resourceDNSResponsePolicyRead, + Update: resourceDNSResponsePolicyUpdate, + Delete: resourceDNSResponsePolicyDelete, + + Importer: &schema.ResourceImporter{ + State: resourceDNSResponsePolicyImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(20 * time.Minute), + Update: schema.DefaultTimeout(20 * time.Minute), + Delete: schema.DefaultTimeout(20 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "response_policy_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The user assigned name for this Response Policy, such as 'myresponsepolicy'.`, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: `The description of the response policy, such as 'My new response policy'.`, + Default: "Managed by Terraform", + }, + "gke_clusters": { + Type: schema.TypeList, + Optional: true, + Description: `The list of Google Kubernetes Engine clusters that can see this zone.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "gke_cluster_name": { + Type: schema.TypeString, + Required: true, + Description: `The resource name of the cluster to bind this ManagedZone to. +This should be specified in the format like +'projects/*/locations/*/clusters/*'`, + }, + }, + }, + }, + "networks": { + Type: schema.TypeList, + Optional: true, + Description: `The list of network names specifying networks to which this policy is applied.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "network_url": { + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, + Description: `The fully qualified URL of the VPC network to bind to. +This should be formatted like +'https://www.googleapis.com/compute/v1/projects/{project}/global/networks/{network}'`, + }, + }, + }, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceDNSResponsePolicyCreate(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{}) + responsePolicyNameProp, err := expandDNSResponsePolicyResponsePolicyName(d.Get("response_policy_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("response_policy_name"); !tpgresource.IsEmptyValue(reflect.ValueOf(responsePolicyNameProp)) && (ok || !reflect.DeepEqual(v, responsePolicyNameProp)) { + obj["responsePolicyName"] = responsePolicyNameProp + } + descriptionProp, err := expandDNSResponsePolicyDescription(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 + } + networksProp, err := expandDNSResponsePolicyNetworks(d.Get("networks"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("networks"); !tpgresource.IsEmptyValue(reflect.ValueOf(networksProp)) && (ok || !reflect.DeepEqual(v, networksProp)) { + obj["networks"] = networksProp + } + gkeClustersProp, err := expandDNSResponsePolicyGkeClusters(d.Get("gke_clusters"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("gke_clusters"); !tpgresource.IsEmptyValue(reflect.ValueOf(gkeClustersProp)) && (ok || !reflect.DeepEqual(v, gkeClustersProp)) { + obj["gkeClusters"] = gkeClustersProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{DNSBasePath}}projects/{{project}}/responsePolicies") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new ResponsePolicy: %#v", obj) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for ResponsePolicy: %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 ResponsePolicy: %s", err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/responsePolicies/{{response_policy_name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating ResponsePolicy %q: %#v", d.Id(), res) + + return resourceDNSResponsePolicyRead(d, meta) +} + +func resourceDNSResponsePolicyRead(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, "{{DNSBasePath}}projects/{{project}}/responsePolicies/{{response_policy_name}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for ResponsePolicy: %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("DNSResponsePolicy %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading ResponsePolicy: %s", err) + } + + if err := d.Set("response_policy_name", flattenDNSResponsePolicyResponsePolicyName(res["responsePolicyName"], d, config)); err != nil { + return fmt.Errorf("Error reading ResponsePolicy: %s", err) + } + if err := d.Set("description", flattenDNSResponsePolicyDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading ResponsePolicy: %s", err) + } + if err := d.Set("networks", flattenDNSResponsePolicyNetworks(res["networks"], d, config)); err != nil { + return fmt.Errorf("Error reading ResponsePolicy: %s", err) + } + if err := d.Set("gke_clusters", flattenDNSResponsePolicyGkeClusters(res["gkeClusters"], d, config)); err != nil { + return fmt.Errorf("Error reading ResponsePolicy: %s", err) + } + + return nil +} + +func resourceDNSResponsePolicyUpdate(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 ResponsePolicy: %s", err) + } + billingProject = project + + obj := make(map[string]interface{}) + descriptionProp, err := expandDNSResponsePolicyDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + networksProp, err := expandDNSResponsePolicyNetworks(d.Get("networks"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("networks"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, networksProp)) { + obj["networks"] = networksProp + } + gkeClustersProp, err := expandDNSResponsePolicyGkeClusters(d.Get("gke_clusters"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("gke_clusters"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, gkeClustersProp)) { + obj["gkeClusters"] = gkeClustersProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{DNSBasePath}}projects/{{project}}/responsePolicies/{{response_policy_name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating ResponsePolicy %q: %#v", d.Id(), obj) + + // 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: "PATCH", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutUpdate), + }) + + if err != nil { + return fmt.Errorf("Error updating ResponsePolicy %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating ResponsePolicy %q: %#v", d.Id(), res) + } + + return resourceDNSResponsePolicyRead(d, meta) +} + +func resourceDNSResponsePolicyDelete(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 ResponsePolicy: %s", err) + } + billingProject = project + + url, err := tpgresource.ReplaceVars(d, config, "{{DNSBasePath}}projects/{{project}}/responsePolicies/{{response_policy_name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + // if gke clusters are attached, they need to be detached before the response policy can be deleted + if d.Get("gke_clusters.#").(int) > 0 { + patched := make(map[string]interface{}) + patched["gkeClusters"] = nil + + url, err := tpgresource.ReplaceVars(d, config, "{{DNSBasePath}}projects/{{project}}/responsePolicies/{{response_policy_name}}") + if err != nil { + return err + } + + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: patched, + Timeout: d.Timeout(schema.TimeoutUpdate), + }) + if err != nil { + return fmt.Errorf("Error updating Policy %q: %s", d.Id(), err) + } + } + + // if networks are attached, they need to be detached before the response policy can be deleted + if d.Get("networks.#").(int) > 0 { + patched := make(map[string]interface{}) + patched["networks"] = nil + + url, err := tpgresource.ReplaceVars(d, config, "{{DNSBasePath}}projects/{{project}}/responsePolicies/{{response_policy_name}}") + if err != nil { + return err + } + + _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: config, + Method: "PATCH", + Project: project, + RawURL: url, + UserAgent: userAgent, + Body: patched, + Timeout: d.Timeout(schema.TimeoutUpdate), + }) + if err != nil { + return fmt.Errorf("Error updating Policy %q: %s", d.Id(), err) + } + } + log.Printf("[DEBUG] Deleting ResponsePolicy %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, "ResponsePolicy") + } + + log.Printf("[DEBUG] Finished deleting ResponsePolicy %q: %#v", d.Id(), res) + return nil +} + +func resourceDNSResponsePolicyImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*transport_tpg.Config) + if err := tpgresource.ParseImportId([]string{ + "projects/(?P[^/]+)/responsePolicies/(?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}}/responsePolicies/{{response_policy_name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenDNSResponsePolicyResponsePolicyName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDNSResponsePolicyDescription(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDNSResponsePolicyNetworks(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{}{ + "network_url": flattenDNSResponsePolicyNetworksNetworkUrl(original["networkUrl"], d, config), + }) + } + return transformed +} +func flattenDNSResponsePolicyNetworksNetworkUrl(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDNSResponsePolicyGkeClusters(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{}{ + "gke_cluster_name": flattenDNSResponsePolicyGkeClustersGkeClusterName(original["gkeClusterName"], d, config), + }) + } + return transformed +} +func flattenDNSResponsePolicyGkeClustersGkeClusterName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandDNSResponsePolicyResponsePolicyName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDNSResponsePolicyDescription(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDNSResponsePolicyNetworks(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + l := v.([]interface{}) + req := make([]interface{}, 0, len(l)) + for _, raw := range l { + if raw == nil { + continue + } + original := raw.(map[string]interface{}) + transformed := make(map[string]interface{}) + + transformedNetworkUrl, err := expandDNSResponsePolicyNetworksNetworkUrl(original["network_url"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedNetworkUrl); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["networkUrl"] = transformedNetworkUrl + } + + req = append(req, transformed) + } + return req, nil +} + +func expandDNSResponsePolicyNetworksNetworkUrl(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + if v == nil || v.(string) == "" { + return "", nil + } else if strings.HasPrefix(v.(string), "https://") { + return v, nil + } + url, err := tpgresource.ReplaceVars(d, config, "{{ComputeBasePath}}"+v.(string)) + if err != nil { + return "", err + } + return tpgresource.ConvertSelfLinkToV1(url), nil +} + +func expandDNSResponsePolicyGkeClusters(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + l := v.([]interface{}) + req := make([]interface{}, 0, len(l)) + for _, raw := range l { + if raw == nil { + continue + } + original := raw.(map[string]interface{}) + transformed := make(map[string]interface{}) + + transformedGkeClusterName, err := expandDNSResponsePolicyGkeClustersGkeClusterName(original["gke_cluster_name"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedGkeClusterName); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["gkeClusterName"] = transformedGkeClusterName + } + + req = append(req, transformed) + } + return req, nil +} + +func expandDNSResponsePolicyGkeClustersGkeClusterName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} diff --git a/google/services/dns/resource_dns_response_policy_rule.go b/google/services/dns/resource_dns_response_policy_rule.go new file mode 100644 index 00000000000..b9e1ff4dafb --- /dev/null +++ b/google/services/dns/resource_dns_response_policy_rule.go @@ -0,0 +1,529 @@ +// 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 dns + +import ( + "fmt" + "log" + "reflect" + "time" + + "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 ResourceDNSResponsePolicyRule() *schema.Resource { + return &schema.Resource{ + Create: resourceDNSResponsePolicyRuleCreate, + Read: resourceDNSResponsePolicyRuleRead, + Update: resourceDNSResponsePolicyRuleUpdate, + Delete: resourceDNSResponsePolicyRuleDelete, + + Importer: &schema.ResourceImporter{ + State: resourceDNSResponsePolicyRuleImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(20 * time.Minute), + Update: schema.DefaultTimeout(20 * time.Minute), + Delete: schema.DefaultTimeout(20 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "dns_name": { + Type: schema.TypeString, + Required: true, + Description: `The DNS name (wildcard or exact) to apply this rule to. Must be unique within the Response Policy Rule.`, + }, + "response_policy": { + Type: schema.TypeString, + Required: true, + DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, + Description: `Identifies the response policy addressed by this request.`, + }, + "rule_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `An identifier for this rule. Must be unique with the ResponsePolicy.`, + }, + "local_data": { + Type: schema.TypeList, + Optional: true, + Description: `Answer this query directly with DNS data. These ResourceRecordSets override any other DNS behavior for the matched name; +in particular they override private zones, the public internet, and GCP internal DNS. No SOA nor NS types are allowed.`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "local_datas": { + Type: schema.TypeList, + Required: true, + Description: `All resource record sets for this selector, one per resource record type. The name must match the dns_name.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + Description: `For example, www.example.com.`, + }, + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidateEnum([]string{"A", "AAAA", "CAA", "CNAME", "DNSKEY", "DS", "HTTPS", "IPSECVPNKEY", "MX", "NAPTR", "NS", "PTR", "SOA", "SPF", "SRV", "SSHFP", "SVCB", "TLSA", "TXT"}), + Description: `One of valid DNS resource types. Possible values: ["A", "AAAA", "CAA", "CNAME", "DNSKEY", "DS", "HTTPS", "IPSECVPNKEY", "MX", "NAPTR", "NS", "PTR", "SOA", "SPF", "SRV", "SSHFP", "SVCB", "TLSA", "TXT"]`, + }, + "rrdatas": { + Type: schema.TypeList, + Optional: true, + Description: `As defined in RFC 1035 (section 5) and RFC 1034 (section 3.6.1)`, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "ttl": { + Type: schema.TypeInt, + Optional: true, + Description: `Number of seconds that this ResourceRecordSet can be cached by +resolvers.`, + }, + }, + }, + }, + }, + }, + ConflictsWith: []string{}, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceDNSResponsePolicyRuleCreate(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{}) + ruleNameProp, err := expandDNSResponsePolicyRuleRuleName(d.Get("rule_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("rule_name"); !tpgresource.IsEmptyValue(reflect.ValueOf(ruleNameProp)) && (ok || !reflect.DeepEqual(v, ruleNameProp)) { + obj["ruleName"] = ruleNameProp + } + dnsNameProp, err := expandDNSResponsePolicyRuleDnsName(d.Get("dns_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("dns_name"); !tpgresource.IsEmptyValue(reflect.ValueOf(dnsNameProp)) && (ok || !reflect.DeepEqual(v, dnsNameProp)) { + obj["dnsName"] = dnsNameProp + } + localDataProp, err := expandDNSResponsePolicyRuleLocalData(d.Get("local_data"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("local_data"); !tpgresource.IsEmptyValue(reflect.ValueOf(localDataProp)) && (ok || !reflect.DeepEqual(v, localDataProp)) { + obj["localData"] = localDataProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{DNSBasePath}}projects/{{project}}/responsePolicies/{{response_policy}}/rules") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new ResponsePolicyRule: %#v", obj) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for ResponsePolicyRule: %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 ResponsePolicyRule: %s", err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/responsePolicies/{{response_policy}}/rules/{{rule_name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating ResponsePolicyRule %q: %#v", d.Id(), res) + + return resourceDNSResponsePolicyRuleRead(d, meta) +} + +func resourceDNSResponsePolicyRuleRead(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, "{{DNSBasePath}}projects/{{project}}/responsePolicies/{{response_policy}}/rules/{{rule_name}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for ResponsePolicyRule: %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("DNSResponsePolicyRule %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading ResponsePolicyRule: %s", err) + } + + if err := d.Set("rule_name", flattenDNSResponsePolicyRuleRuleName(res["ruleName"], d, config)); err != nil { + return fmt.Errorf("Error reading ResponsePolicyRule: %s", err) + } + if err := d.Set("dns_name", flattenDNSResponsePolicyRuleDnsName(res["dnsName"], d, config)); err != nil { + return fmt.Errorf("Error reading ResponsePolicyRule: %s", err) + } + if err := d.Set("local_data", flattenDNSResponsePolicyRuleLocalData(res["localData"], d, config)); err != nil { + return fmt.Errorf("Error reading ResponsePolicyRule: %s", err) + } + + return nil +} + +func resourceDNSResponsePolicyRuleUpdate(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 ResponsePolicyRule: %s", err) + } + billingProject = project + + obj := make(map[string]interface{}) + dnsNameProp, err := expandDNSResponsePolicyRuleDnsName(d.Get("dns_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("dns_name"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, dnsNameProp)) { + obj["dnsName"] = dnsNameProp + } + localDataProp, err := expandDNSResponsePolicyRuleLocalData(d.Get("local_data"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("local_data"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, localDataProp)) { + obj["localData"] = localDataProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{DNSBasePath}}projects/{{project}}/responsePolicies/{{response_policy}}/rules/{{rule_name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating ResponsePolicyRule %q: %#v", d.Id(), obj) + + // 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: "PATCH", + Project: billingProject, + RawURL: url, + UserAgent: userAgent, + Body: obj, + Timeout: d.Timeout(schema.TimeoutUpdate), + }) + + if err != nil { + return fmt.Errorf("Error updating ResponsePolicyRule %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating ResponsePolicyRule %q: %#v", d.Id(), res) + } + + return resourceDNSResponsePolicyRuleRead(d, meta) +} + +func resourceDNSResponsePolicyRuleDelete(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 ResponsePolicyRule: %s", err) + } + billingProject = project + + url, err := tpgresource.ReplaceVars(d, config, "{{DNSBasePath}}projects/{{project}}/responsePolicies/{{response_policy}}/rules/{{rule_name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting ResponsePolicyRule %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, "ResponsePolicyRule") + } + + log.Printf("[DEBUG] Finished deleting ResponsePolicyRule %q: %#v", d.Id(), res) + return nil +} + +func resourceDNSResponsePolicyRuleImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*transport_tpg.Config) + if err := tpgresource.ParseImportId([]string{ + "projects/(?P[^/]+)/responsePolicies/(?P[^/]+)/rules/(?P[^/]+)", + "(?P[^/]+)/(?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}}/responsePolicies/{{response_policy}}/rules/{{rule_name}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenDNSResponsePolicyRuleRuleName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDNSResponsePolicyRuleDnsName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDNSResponsePolicyRuleLocalData(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["local_datas"] = + flattenDNSResponsePolicyRuleLocalDataLocalDatas(original["localDatas"], d, config) + return []interface{}{transformed} +} +func flattenDNSResponsePolicyRuleLocalDataLocalDatas(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{}{ + "name": flattenDNSResponsePolicyRuleLocalDataLocalDatasName(original["name"], d, config), + "type": flattenDNSResponsePolicyRuleLocalDataLocalDatasType(original["type"], d, config), + "ttl": flattenDNSResponsePolicyRuleLocalDataLocalDatasTtl(original["ttl"], d, config), + "rrdatas": flattenDNSResponsePolicyRuleLocalDataLocalDatasRrdatas(original["rrdatas"], d, config), + }) + } + return transformed +} +func flattenDNSResponsePolicyRuleLocalDataLocalDatasName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDNSResponsePolicyRuleLocalDataLocalDatasType(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDNSResponsePolicyRuleLocalDataLocalDatasTtl(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 flattenDNSResponsePolicyRuleLocalDataLocalDatasRrdatas(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandDNSResponsePolicyRuleRuleName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDNSResponsePolicyRuleDnsName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDNSResponsePolicyRuleLocalData(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{}) + + transformedLocalDatas, err := expandDNSResponsePolicyRuleLocalDataLocalDatas(original["local_datas"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedLocalDatas); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["localDatas"] = transformedLocalDatas + } + + return transformed, nil +} + +func expandDNSResponsePolicyRuleLocalDataLocalDatas(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + l := v.([]interface{}) + req := make([]interface{}, 0, len(l)) + for _, raw := range l { + if raw == nil { + continue + } + original := raw.(map[string]interface{}) + transformed := make(map[string]interface{}) + + transformedName, err := expandDNSResponsePolicyRuleLocalDataLocalDatasName(original["name"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedName); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["name"] = transformedName + } + + transformedType, err := expandDNSResponsePolicyRuleLocalDataLocalDatasType(original["type"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedType); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["type"] = transformedType + } + + transformedTtl, err := expandDNSResponsePolicyRuleLocalDataLocalDatasTtl(original["ttl"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedTtl); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["ttl"] = transformedTtl + } + + transformedRrdatas, err := expandDNSResponsePolicyRuleLocalDataLocalDatasRrdatas(original["rrdatas"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedRrdatas); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["rrdatas"] = transformedRrdatas + } + + req = append(req, transformed) + } + return req, nil +} + +func expandDNSResponsePolicyRuleLocalDataLocalDatasName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDNSResponsePolicyRuleLocalDataLocalDatasType(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDNSResponsePolicyRuleLocalDataLocalDatasTtl(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDNSResponsePolicyRuleLocalDataLocalDatasRrdatas(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} diff --git a/google/services/dns/resource_dns_response_policy_rule_sweeper.go b/google/services/dns/resource_dns_response_policy_rule_sweeper.go new file mode 100644 index 00000000000..f71dbdcde49 --- /dev/null +++ b/google/services/dns/resource_dns_response_policy_rule_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 dns + +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("DNSResponsePolicyRule", testSweepDNSResponsePolicyRule) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepDNSResponsePolicyRule(region string) error { + resourceName := "DNSResponsePolicyRule" + 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://dns.googleapis.com/dns/v1/projects/{{project}}/responsePolicies/{{response_policy}}/rules", "?")[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["responsePolicyRules"] + 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://dns.googleapis.com/dns/v1/projects/{{project}}/responsePolicies/{{response_policy}}/rules/{{rule_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/dns_response_policy.html.markdown b/website/docs/r/dns_response_policy.html.markdown index 562b5c306d4..a5ca2a6aafd 100644 --- a/website/docs/r/dns_response_policy.html.markdown +++ b/website/docs/r/dns_response_policy.html.markdown @@ -23,8 +23,6 @@ description: |- A Response Policy is a collection of selectors that apply to queries made against one or more Virtual Private Cloud networks. -~> **Warning:** This resource is in beta, and should be used with the terraform-provider-google-beta provider. -See [Provider Versions](https://terraform.io/docs/providers/google/guides/provider_versions.html) for more details on beta resources.
@@ -37,22 +35,16 @@ See [Provider Versions](https://terraform.io/docs/providers/google/guides/provid ```hcl resource "google_compute_network" "network-1" { - provider = google-beta - name = "network-1" auto_create_subnetworks = false } resource "google_compute_network" "network-2" { - provider = google-beta - name = "network-2" auto_create_subnetworks = false } resource "google_compute_subnetwork" "subnetwork-1" { - provider = google-beta - name = google_compute_network.network-1.name network = google_compute_network.network-1.name ip_cidr_range = "10.0.36.0/24" @@ -71,8 +63,6 @@ resource "google_compute_subnetwork" "subnetwork-1" { } resource "google_container_cluster" "cluster-1" { - provider = google-beta - name = "cluster-1" location = "us-central1-c" initial_node_count = 1 @@ -101,10 +91,8 @@ resource "google_container_cluster" "cluster-1" { } resource "google_dns_response_policy" "example-response-policy" { - provider = google-beta - response_policy_name = "example-response-policy" - + networks { network_url = google_compute_network.network-1.id } diff --git a/website/docs/r/dns_response_policy_rule.html.markdown b/website/docs/r/dns_response_policy_rule.html.markdown index a6485898f90..07dba373a12 100644 --- a/website/docs/r/dns_response_policy_rule.html.markdown +++ b/website/docs/r/dns_response_policy_rule.html.markdown @@ -24,8 +24,6 @@ Selectors are DNS names, which may be wildcards or exact matches. Each DNS query subject to a Response Policy matches at most one ResponsePolicyRule, as identified by the dns_name field with the longest matching suffix. -~> **Warning:** This resource is in beta, and should be used with the terraform-provider-google-beta provider. -See [Provider Versions](https://terraform.io/docs/providers/google/guides/provider_versions.html) for more details on beta resources.
@@ -38,24 +36,18 @@ See [Provider Versions](https://terraform.io/docs/providers/google/guides/provid ```hcl resource "google_compute_network" "network-1" { - provider = google-beta - name = "network-1" auto_create_subnetworks = false } resource "google_compute_network" "network-2" { - provider = google-beta - name = "network-2" auto_create_subnetworks = false } resource "google_dns_response_policy" "response-policy" { - provider = google-beta - response_policy_name = "example-response-policy" - + networks { network_url = google_compute_network.network-1.id } @@ -65,8 +57,6 @@ resource "google_dns_response_policy" "response-policy" { } resource "google_dns_response_policy_rule" "example-response-policy-rule" { - provider = google-beta - response_policy = google_dns_response_policy.response-policy.response_policy_name rule_name = "example-rule" dns_name = "dns.example.com." @@ -78,7 +68,7 @@ resource "google_dns_response_policy_rule" "example-response-policy-rule" { ttl = 300 rrdatas = ["192.0.2.91"] } - } + } } ``` @@ -111,7 +101,7 @@ The following arguments are supported: Structure is [documented below](#nested_local_data). * `behavior` - - (Optional) + (Optional, [Beta](https://terraform.io/docs/providers/google/guides/provider_versions.html)) Answer this query with a behavior rather than DNS data. Acceptable values are 'behaviorUnspecified', and 'bypassResponsePolicy' * `project` - (Optional) The ID of the project in which the resource belongs.