From f37b9daff7f9833b0175de774a4dd6dc9b3842dd Mon Sep 17 00:00:00 2001 From: Modular Magician Date: Wed, 6 Sep 2023 16:54:15 +0000 Subject: [PATCH] Remove cloud iot service (#8868) Signed-off-by: Modular Magician --- .changelog/8868.txt | 12 + .teamcity/components/generated/services.kt | 5 - google/fwmodels/provider_model.go | 1 - google/fwprovider/framework_provider.go | 6 - google/fwtransport/framework_config.go | 10 - google/provider/provider.go | 19 +- .../cloudiot/iam_cloudiot_registry.go | 245 ----- .../iam_cloudiot_registry_generated_test.go | 227 ----- .../cloudiot/resource_cloudiot_device.go | 959 ------------------ ...resource_cloudiot_device_generated_test.go | 170 ---- ...source_cloudiot_device_registry_id_test.go | 35 - .../resource_cloudiot_device_sweeper.go | 139 --- .../resource_cloudiot_device_update_test.go | 106 -- .../cloudiot/resource_cloudiot_registry.go | 886 ---------------- ...source_cloudiot_registry_generated_test.go | 229 ----- .../resource_cloudiot_registry_sweeper.go | 139 --- .../resource_cloudiot_registry_update_test.go | 112 -- .../cloudiot/test-fixtures/rsa_cert.pem | 17 - .../cloudiot/test-fixtures/rsa_public.pem | 14 - google/sweeper/gcp_sweeper_test.go | 1 - google/transport/config.go | 9 - ...cloudiot_registry_iam_policy.html.markdown | 57 -- website/docs/r/cloudiot_device.html.markdown | 262 ----- .../docs/r/cloudiot_registry.html.markdown | 224 ---- .../r/cloudiot_registry_iam.html.markdown | 158 --- 25 files changed, 15 insertions(+), 4027 deletions(-) create mode 100644 .changelog/8868.txt delete mode 100644 google/services/cloudiot/iam_cloudiot_registry.go delete mode 100644 google/services/cloudiot/iam_cloudiot_registry_generated_test.go delete mode 100644 google/services/cloudiot/resource_cloudiot_device.go delete mode 100644 google/services/cloudiot/resource_cloudiot_device_generated_test.go delete mode 100644 google/services/cloudiot/resource_cloudiot_device_registry_id_test.go delete mode 100644 google/services/cloudiot/resource_cloudiot_device_sweeper.go delete mode 100644 google/services/cloudiot/resource_cloudiot_device_update_test.go delete mode 100644 google/services/cloudiot/resource_cloudiot_registry.go delete mode 100644 google/services/cloudiot/resource_cloudiot_registry_generated_test.go delete mode 100644 google/services/cloudiot/resource_cloudiot_registry_sweeper.go delete mode 100644 google/services/cloudiot/resource_cloudiot_registry_update_test.go delete mode 100644 google/services/cloudiot/test-fixtures/rsa_cert.pem delete mode 100644 google/services/cloudiot/test-fixtures/rsa_public.pem delete mode 100644 website/docs/d/cloudiot_registry_iam_policy.html.markdown delete mode 100644 website/docs/r/cloudiot_device.html.markdown delete mode 100644 website/docs/r/cloudiot_registry.html.markdown delete mode 100644 website/docs/r/cloudiot_registry_iam.html.markdown diff --git a/.changelog/8868.txt b/.changelog/8868.txt new file mode 100644 index 00000000000..0a9304190b8 --- /dev/null +++ b/.changelog/8868.txt @@ -0,0 +1,12 @@ +```release-note:deprecation +cloudiot: deprecated resource `google_cloudiot_registry` +``` +```release-note:deprecation +cloudiot: deprecated resource `google_cloudiot_device` +``` +```release-note:deprecation +cloudiot: deprecated resource `google_cloudiot_registry_iam_*` +``` +```release-note:deprecation +cloudiot: deprecated datasource `google_cloudiot_registry_iam_policy` +``` diff --git a/.teamcity/components/generated/services.kt b/.teamcity/components/generated/services.kt index 81c36388dbe..ae083de7b70 100644 --- a/.teamcity/components/generated/services.kt +++ b/.teamcity/components/generated/services.kt @@ -156,11 +156,6 @@ var services = mapOf( "displayName" to "Cloudids", "path" to "./google/services/cloudids" ), - "cloudiot" to mapOf( - "name" to "cloudiot", - "displayName" to "Cloudiot", - "path" to "./google/services/cloudiot" - ), "cloudrun" to mapOf( "name" to "cloudrun", "displayName" to "Cloudrun", diff --git a/google/fwmodels/provider_model.go b/google/fwmodels/provider_model.go index 267bdaf079e..0e1426f6d55 100644 --- a/google/fwmodels/provider_model.go +++ b/google/fwmodels/provider_model.go @@ -50,7 +50,6 @@ type ProviderModel struct { Cloudfunctions2CustomEndpoint types.String `tfsdk:"cloudfunctions2_custom_endpoint"` CloudIdentityCustomEndpoint types.String `tfsdk:"cloud_identity_custom_endpoint"` CloudIdsCustomEndpoint types.String `tfsdk:"cloud_ids_custom_endpoint"` - CloudIotCustomEndpoint types.String `tfsdk:"cloud_iot_custom_endpoint"` CloudRunCustomEndpoint types.String `tfsdk:"cloud_run_custom_endpoint"` CloudRunV2CustomEndpoint types.String `tfsdk:"cloud_run_v2_custom_endpoint"` CloudSchedulerCustomEndpoint types.String `tfsdk:"cloud_scheduler_custom_endpoint"` diff --git a/google/fwprovider/framework_provider.go b/google/fwprovider/framework_provider.go index 338fc00f364..adad083ed6e 100644 --- a/google/fwprovider/framework_provider.go +++ b/google/fwprovider/framework_provider.go @@ -269,12 +269,6 @@ func (p *FrameworkProvider) Schema(_ context.Context, _ provider.SchemaRequest, transport_tpg.CustomEndpointValidator(), }, }, - "cloud_iot_custom_endpoint": &schema.StringAttribute{ - Optional: true, - Validators: []validator.String{ - transport_tpg.CustomEndpointValidator(), - }, - }, "cloud_run_custom_endpoint": &schema.StringAttribute{ Optional: true, Validators: []validator.String{ diff --git a/google/fwtransport/framework_config.go b/google/fwtransport/framework_config.go index 40d6f07395f..04186820e99 100644 --- a/google/fwtransport/framework_config.go +++ b/google/fwtransport/framework_config.go @@ -74,7 +74,6 @@ type FrameworkProviderConfig struct { Cloudfunctions2BasePath string CloudIdentityBasePath string CloudIdsBasePath string - CloudIotBasePath string CloudRunBasePath string CloudRunV2BasePath string CloudSchedulerBasePath string @@ -212,7 +211,6 @@ func (p *FrameworkProviderConfig) LoadAndValidateFramework(ctx context.Context, p.Cloudfunctions2BasePath = data.Cloudfunctions2CustomEndpoint.ValueString() p.CloudIdentityBasePath = data.CloudIdentityCustomEndpoint.ValueString() p.CloudIdsBasePath = data.CloudIdsCustomEndpoint.ValueString() - p.CloudIotBasePath = data.CloudIotCustomEndpoint.ValueString() p.CloudRunBasePath = data.CloudRunCustomEndpoint.ValueString() p.CloudRunV2BasePath = data.CloudRunV2CustomEndpoint.ValueString() p.CloudSchedulerBasePath = data.CloudSchedulerCustomEndpoint.ValueString() @@ -611,14 +609,6 @@ func (p *FrameworkProviderConfig) HandleDefaults(ctx context.Context, data *fwmo data.CloudIdsCustomEndpoint = types.StringValue(customEndpoint.(string)) } } - if data.CloudIotCustomEndpoint.IsNull() { - customEndpoint := transport_tpg.MultiEnvDefault([]string{ - "GOOGLE_CLOUD_IOT_CUSTOM_ENDPOINT", - }, transport_tpg.DefaultBasePaths[transport_tpg.CloudIotBasePathKey]) - if customEndpoint != nil { - data.CloudIotCustomEndpoint = types.StringValue(customEndpoint.(string)) - } - } if data.CloudRunCustomEndpoint.IsNull() { customEndpoint := transport_tpg.MultiEnvDefault([]string{ "GOOGLE_CLOUD_RUN_CUSTOM_ENDPOINT", diff --git a/google/provider/provider.go b/google/provider/provider.go index 00146d5ed6b..3183ba94c81 100644 --- a/google/provider/provider.go +++ b/google/provider/provider.go @@ -38,7 +38,6 @@ import ( "github.com/hashicorp/terraform-provider-google/google/services/cloudfunctions2" "github.com/hashicorp/terraform-provider-google/google/services/cloudidentity" "github.com/hashicorp/terraform-provider-google/google/services/cloudids" - "github.com/hashicorp/terraform-provider-google/google/services/cloudiot" "github.com/hashicorp/terraform-provider-google/google/services/cloudrun" "github.com/hashicorp/terraform-provider-google/google/services/cloudrunv2" "github.com/hashicorp/terraform-provider-google/google/services/cloudscheduler" @@ -351,11 +350,6 @@ func Provider() *schema.Provider { Optional: true, ValidateFunc: transport_tpg.ValidateCustomEndpoint, }, - "cloud_iot_custom_endpoint": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: transport_tpg.ValidateCustomEndpoint, - }, "cloud_run_custom_endpoint": { Type: schema.TypeString, Optional: true, @@ -887,7 +881,6 @@ func DatasourceMapWithErrors() (map[string]*schema.Resource, error) { "google_cloudbuildv2_connection_iam_policy": tpgiamresource.DataSourceIamPolicy(cloudbuildv2.Cloudbuildv2ConnectionIamSchema, cloudbuildv2.Cloudbuildv2ConnectionIamUpdaterProducer), "google_cloudfunctions_function_iam_policy": tpgiamresource.DataSourceIamPolicy(cloudfunctions.CloudFunctionsCloudFunctionIamSchema, cloudfunctions.CloudFunctionsCloudFunctionIamUpdaterProducer), "google_cloudfunctions2_function_iam_policy": tpgiamresource.DataSourceIamPolicy(cloudfunctions2.Cloudfunctions2functionIamSchema, cloudfunctions2.Cloudfunctions2functionIamUpdaterProducer), - "google_cloudiot_registry_iam_policy": tpgiamresource.DataSourceIamPolicy(cloudiot.CloudIotDeviceRegistryIamSchema, cloudiot.CloudIotDeviceRegistryIamUpdaterProducer), "google_cloud_run_service_iam_policy": tpgiamresource.DataSourceIamPolicy(cloudrun.CloudRunServiceIamSchema, cloudrun.CloudRunServiceIamUpdaterProducer), "google_cloud_run_v2_job_iam_policy": tpgiamresource.DataSourceIamPolicy(cloudrunv2.CloudRunV2JobIamSchema, cloudrunv2.CloudRunV2JobIamUpdaterProducer), "google_cloud_run_v2_service_iam_policy": tpgiamresource.DataSourceIamPolicy(cloudrunv2.CloudRunV2ServiceIamSchema, cloudrunv2.CloudRunV2ServiceIamUpdaterProducer), @@ -965,9 +958,9 @@ func DatasourceMapWithErrors() (map[string]*schema.Resource, error) { }) } -// Generated resources: 306 -// Generated IAM resources: 204 -// Total generated resources: 510 +// Generated resources: 304 +// Generated IAM resources: 201 +// Total generated resources: 505 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -1089,11 +1082,6 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_cloud_identity_group": cloudidentity.ResourceCloudIdentityGroup(), "google_cloud_identity_group_membership": cloudidentity.ResourceCloudIdentityGroupMembership(), "google_cloud_ids_endpoint": cloudids.ResourceCloudIdsEndpoint(), - "google_cloudiot_device": cloudiot.ResourceCloudIotDevice(), - "google_cloudiot_registry": cloudiot.ResourceCloudIotDeviceRegistry(), - "google_cloudiot_registry_iam_binding": tpgiamresource.ResourceIamBinding(cloudiot.CloudIotDeviceRegistryIamSchema, cloudiot.CloudIotDeviceRegistryIamUpdaterProducer, cloudiot.CloudIotDeviceRegistryIdParseFunc), - "google_cloudiot_registry_iam_member": tpgiamresource.ResourceIamMember(cloudiot.CloudIotDeviceRegistryIamSchema, cloudiot.CloudIotDeviceRegistryIamUpdaterProducer, cloudiot.CloudIotDeviceRegistryIdParseFunc), - "google_cloudiot_registry_iam_policy": tpgiamresource.ResourceIamPolicy(cloudiot.CloudIotDeviceRegistryIamSchema, cloudiot.CloudIotDeviceRegistryIamUpdaterProducer, cloudiot.CloudIotDeviceRegistryIdParseFunc), "google_cloud_run_domain_mapping": cloudrun.ResourceCloudRunDomainMapping(), "google_cloud_run_service": cloudrun.ResourceCloudRunService(), "google_cloud_run_service_iam_binding": tpgiamresource.ResourceIamBinding(cloudrun.CloudRunServiceIamSchema, cloudrun.CloudRunServiceIamUpdaterProducer, cloudrun.CloudRunServiceIdParseFunc), @@ -1736,7 +1724,6 @@ func ProviderConfigure(ctx context.Context, d *schema.ResourceData, p *schema.Pr config.Cloudfunctions2BasePath = d.Get("cloudfunctions2_custom_endpoint").(string) config.CloudIdentityBasePath = d.Get("cloud_identity_custom_endpoint").(string) config.CloudIdsBasePath = d.Get("cloud_ids_custom_endpoint").(string) - config.CloudIotBasePath = d.Get("cloud_iot_custom_endpoint").(string) config.CloudRunBasePath = d.Get("cloud_run_custom_endpoint").(string) config.CloudRunV2BasePath = d.Get("cloud_run_v2_custom_endpoint").(string) config.CloudSchedulerBasePath = d.Get("cloud_scheduler_custom_endpoint").(string) diff --git a/google/services/cloudiot/iam_cloudiot_registry.go b/google/services/cloudiot/iam_cloudiot_registry.go deleted file mode 100644 index 84b3210e7b3..00000000000 --- a/google/services/cloudiot/iam_cloudiot_registry.go +++ /dev/null @@ -1,245 +0,0 @@ -// 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 cloudiot - -import ( - "fmt" - - "github.com/hashicorp/errwrap" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "google.golang.org/api/cloudresourcemanager/v1" - - "github.com/hashicorp/terraform-provider-google/google/tpgiamresource" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -var CloudIotDeviceRegistryIamSchema = map[string]*schema.Schema{ - "project": { - Type: schema.TypeString, - Computed: true, - Optional: true, - ForceNew: true, - }, - "region": { - Type: schema.TypeString, - Computed: true, - Optional: true, - ForceNew: true, - }, - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, - }, -} - -type CloudIotDeviceRegistryIamUpdater struct { - project string - region string - name string - d tpgresource.TerraformResourceData - Config *transport_tpg.Config -} - -func CloudIotDeviceRegistryIamUpdaterProducer(d tpgresource.TerraformResourceData, config *transport_tpg.Config) (tpgiamresource.ResourceIamUpdater, error) { - values := make(map[string]string) - - project, _ := tpgresource.GetProject(d, config) - if project != "" { - if err := d.Set("project", project); err != nil { - return nil, fmt.Errorf("Error setting project: %s", err) - } - } - values["project"] = project - region, _ := tpgresource.GetRegion(d, config) - if region != "" { - if err := d.Set("region", region); err != nil { - return nil, fmt.Errorf("Error setting region: %s", err) - } - } - values["region"] = region - if v, ok := d.GetOk("name"); ok { - values["name"] = v.(string) - } - - // We may have gotten either a long or short name, so attempt to parse long name if possible - m, err := tpgresource.GetImportIdQualifiers([]string{"projects/(?P[^/]+)/locations/(?P[^/]+)/registries/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, d, config, d.Get("name").(string)) - if err != nil { - return nil, err - } - - for k, v := range m { - values[k] = v - } - - u := &CloudIotDeviceRegistryIamUpdater{ - project: values["project"], - region: values["region"], - name: values["name"], - d: d, - Config: config, - } - - if err := d.Set("project", u.project); err != nil { - return nil, fmt.Errorf("Error setting project: %s", err) - } - if err := d.Set("region", u.region); err != nil { - return nil, fmt.Errorf("Error setting region: %s", err) - } - if err := d.Set("name", u.GetResourceId()); err != nil { - return nil, fmt.Errorf("Error setting name: %s", err) - } - - return u, nil -} - -func CloudIotDeviceRegistryIdParseFunc(d *schema.ResourceData, config *transport_tpg.Config) error { - values := make(map[string]string) - - project, _ := tpgresource.GetProject(d, config) - if project != "" { - values["project"] = project - } - - region, _ := tpgresource.GetRegion(d, config) - if region != "" { - values["region"] = region - } - - m, err := tpgresource.GetImportIdQualifiers([]string{"projects/(?P[^/]+)/locations/(?P[^/]+)/registries/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, d, config, d.Id()) - if err != nil { - return err - } - - for k, v := range m { - values[k] = v - } - - u := &CloudIotDeviceRegistryIamUpdater{ - project: values["project"], - region: values["region"], - name: values["name"], - d: d, - Config: config, - } - if err := d.Set("name", u.GetResourceId()); err != nil { - return fmt.Errorf("Error setting name: %s", err) - } - d.SetId(u.GetResourceId()) - return nil -} - -func (u *CloudIotDeviceRegistryIamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) { - url, err := u.qualifyDeviceRegistryUrl("getIamPolicy") - if err != nil { - return nil, err - } - - project, err := tpgresource.GetProject(u.d, u.Config) - if err != nil { - return nil, err - } - var obj map[string]interface{} - - userAgent, err := tpgresource.GenerateUserAgentString(u.d, u.Config.UserAgent) - if err != nil { - return nil, err - } - - policy, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: u.Config, - Method: "POST", - Project: project, - RawURL: url, - UserAgent: userAgent, - Body: obj, - }) - if err != nil { - return nil, errwrap.Wrapf(fmt.Sprintf("Error retrieving IAM policy for %s: {{err}}", u.DescribeResource()), err) - } - - out := &cloudresourcemanager.Policy{} - err = tpgresource.Convert(policy, out) - if err != nil { - return nil, errwrap.Wrapf("Cannot convert a policy to a resource manager policy: {{err}}", err) - } - - return out, nil -} - -func (u *CloudIotDeviceRegistryIamUpdater) SetResourceIamPolicy(policy *cloudresourcemanager.Policy) error { - json, err := tpgresource.ConvertToMap(policy) - if err != nil { - return err - } - - obj := make(map[string]interface{}) - obj["policy"] = json - - url, err := u.qualifyDeviceRegistryUrl("setIamPolicy") - if err != nil { - return err - } - project, err := tpgresource.GetProject(u.d, u.Config) - if err != nil { - return err - } - - userAgent, err := tpgresource.GenerateUserAgentString(u.d, u.Config.UserAgent) - if err != nil { - return err - } - - _, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ - Config: u.Config, - Method: "POST", - Project: project, - RawURL: url, - UserAgent: userAgent, - Body: obj, - Timeout: u.d.Timeout(schema.TimeoutCreate), - }) - if err != nil { - return errwrap.Wrapf(fmt.Sprintf("Error setting IAM policy for %s: {{err}}", u.DescribeResource()), err) - } - - return nil -} - -func (u *CloudIotDeviceRegistryIamUpdater) qualifyDeviceRegistryUrl(methodIdentifier string) (string, error) { - urlTemplate := fmt.Sprintf("{{CloudIotBasePath}}%s:%s", fmt.Sprintf("projects/%s/locations/%s/registries/%s", u.project, u.region, u.name), methodIdentifier) - url, err := tpgresource.ReplaceVars(u.d, u.Config, urlTemplate) - if err != nil { - return "", err - } - return url, nil -} - -func (u *CloudIotDeviceRegistryIamUpdater) GetResourceId() string { - return fmt.Sprintf("projects/%s/locations/%s/registries/%s", u.project, u.region, u.name) -} - -func (u *CloudIotDeviceRegistryIamUpdater) GetMutexKey() string { - return fmt.Sprintf("iam-cloudiot-deviceregistry-%s", u.GetResourceId()) -} - -func (u *CloudIotDeviceRegistryIamUpdater) DescribeResource() string { - return fmt.Sprintf("cloudiot deviceregistry %q", u.GetResourceId()) -} diff --git a/google/services/cloudiot/iam_cloudiot_registry_generated_test.go b/google/services/cloudiot/iam_cloudiot_registry_generated_test.go deleted file mode 100644 index ce7a173c0b6..00000000000 --- a/google/services/cloudiot/iam_cloudiot_registry_generated_test.go +++ /dev/null @@ -1,227 +0,0 @@ -// 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 cloudiot_test - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - - "github.com/hashicorp/terraform-provider-google/google/acctest" - "github.com/hashicorp/terraform-provider-google/google/envvar" -) - -func TestAccCloudIotDeviceRegistryIamBindingGenerated(t *testing.T) { - t.Parallel() - - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "role": "roles/viewer", - "project": envvar.GetTestProjectFromEnv(), - "region": envvar.GetTestRegionFromEnv(), - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - Steps: []resource.TestStep{ - { - Config: testAccCloudIotDeviceRegistryIamBinding_basicGenerated(context), - }, - { - ResourceName: "google_cloudiot_registry_iam_binding.foo", - ImportStateId: fmt.Sprintf("projects/%s/locations/%s/registries/%s roles/viewer", envvar.GetTestProjectFromEnv(), envvar.GetTestRegionFromEnv(), fmt.Sprintf("tf-test-cloudiot-registry%s", context["random_suffix"])), - ImportState: true, - ImportStateVerify: true, - }, - { - // Test Iam Binding update - Config: testAccCloudIotDeviceRegistryIamBinding_updateGenerated(context), - }, - { - ResourceName: "google_cloudiot_registry_iam_binding.foo", - ImportStateId: fmt.Sprintf("projects/%s/locations/%s/registries/%s roles/viewer", envvar.GetTestProjectFromEnv(), envvar.GetTestRegionFromEnv(), fmt.Sprintf("tf-test-cloudiot-registry%s", context["random_suffix"])), - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func TestAccCloudIotDeviceRegistryIamMemberGenerated(t *testing.T) { - t.Parallel() - - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "role": "roles/viewer", - "project": envvar.GetTestProjectFromEnv(), - "region": envvar.GetTestRegionFromEnv(), - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - Steps: []resource.TestStep{ - { - // Test Iam Member creation (no update for member, no need to test) - Config: testAccCloudIotDeviceRegistryIamMember_basicGenerated(context), - }, - { - ResourceName: "google_cloudiot_registry_iam_member.foo", - ImportStateId: fmt.Sprintf("projects/%s/locations/%s/registries/%s roles/viewer user:admin@hashicorptest.com", envvar.GetTestProjectFromEnv(), envvar.GetTestRegionFromEnv(), fmt.Sprintf("tf-test-cloudiot-registry%s", context["random_suffix"])), - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func TestAccCloudIotDeviceRegistryIamPolicyGenerated(t *testing.T) { - t.Parallel() - - context := map[string]interface{}{ - "random_suffix": acctest.RandString(t, 10), - "role": "roles/viewer", - "project": envvar.GetTestProjectFromEnv(), - "region": envvar.GetTestRegionFromEnv(), - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - Steps: []resource.TestStep{ - { - Config: testAccCloudIotDeviceRegistryIamPolicy_basicGenerated(context), - Check: resource.TestCheckResourceAttrSet("data.google_cloudiot_registry_iam_policy.foo", "policy_data"), - }, - { - ResourceName: "google_cloudiot_registry_iam_policy.foo", - ImportStateId: fmt.Sprintf("projects/%s/locations/%s/registries/%s", envvar.GetTestProjectFromEnv(), envvar.GetTestRegionFromEnv(), fmt.Sprintf("tf-test-cloudiot-registry%s", context["random_suffix"])), - ImportState: true, - ImportStateVerify: true, - }, - { - Config: testAccCloudIotDeviceRegistryIamPolicy_emptyBinding(context), - }, - { - ResourceName: "google_cloudiot_registry_iam_policy.foo", - ImportStateId: fmt.Sprintf("projects/%s/locations/%s/registries/%s", envvar.GetTestProjectFromEnv(), envvar.GetTestRegionFromEnv(), fmt.Sprintf("tf-test-cloudiot-registry%s", context["random_suffix"])), - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func testAccCloudIotDeviceRegistryIamMember_basicGenerated(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_cloudiot_registry" "test-registry" { - name = "tf-test-cloudiot-registry%{random_suffix}" -} - -resource "google_cloudiot_registry_iam_member" "foo" { - project = google_cloudiot_registry.test-registry.project - region = google_cloudiot_registry.test-registry.region - name = google_cloudiot_registry.test-registry.name - role = "%{role}" - member = "user:admin@hashicorptest.com" -} -`, context) -} - -func testAccCloudIotDeviceRegistryIamPolicy_basicGenerated(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_cloudiot_registry" "test-registry" { - name = "tf-test-cloudiot-registry%{random_suffix}" -} - -data "google_iam_policy" "foo" { - binding { - role = "%{role}" - members = ["user:admin@hashicorptest.com"] - } -} - -resource "google_cloudiot_registry_iam_policy" "foo" { - project = google_cloudiot_registry.test-registry.project - region = google_cloudiot_registry.test-registry.region - name = google_cloudiot_registry.test-registry.name - policy_data = data.google_iam_policy.foo.policy_data -} - -data "google_cloudiot_registry_iam_policy" "foo" { - project = google_cloudiot_registry.test-registry.project - region = google_cloudiot_registry.test-registry.region - name = google_cloudiot_registry.test-registry.name - depends_on = [ - google_cloudiot_registry_iam_policy.foo - ] -} -`, context) -} - -func testAccCloudIotDeviceRegistryIamPolicy_emptyBinding(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_cloudiot_registry" "test-registry" { - name = "tf-test-cloudiot-registry%{random_suffix}" -} - -data "google_iam_policy" "foo" { -} - -resource "google_cloudiot_registry_iam_policy" "foo" { - project = google_cloudiot_registry.test-registry.project - region = google_cloudiot_registry.test-registry.region - name = google_cloudiot_registry.test-registry.name - policy_data = data.google_iam_policy.foo.policy_data -} -`, context) -} - -func testAccCloudIotDeviceRegistryIamBinding_basicGenerated(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_cloudiot_registry" "test-registry" { - name = "tf-test-cloudiot-registry%{random_suffix}" -} - -resource "google_cloudiot_registry_iam_binding" "foo" { - project = google_cloudiot_registry.test-registry.project - region = google_cloudiot_registry.test-registry.region - name = google_cloudiot_registry.test-registry.name - role = "%{role}" - members = ["user:admin@hashicorptest.com"] -} -`, context) -} - -func testAccCloudIotDeviceRegistryIamBinding_updateGenerated(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_cloudiot_registry" "test-registry" { - name = "tf-test-cloudiot-registry%{random_suffix}" -} - -resource "google_cloudiot_registry_iam_binding" "foo" { - project = google_cloudiot_registry.test-registry.project - region = google_cloudiot_registry.test-registry.region - name = google_cloudiot_registry.test-registry.name - role = "%{role}" - members = ["user:admin@hashicorptest.com", "user:gterraformtest1@gmail.com"] -} -`, context) -} diff --git a/google/services/cloudiot/resource_cloudiot_device.go b/google/services/cloudiot/resource_cloudiot_device.go deleted file mode 100644 index edd6a7cb6b5..00000000000 --- a/google/services/cloudiot/resource_cloudiot_device.go +++ /dev/null @@ -1,959 +0,0 @@ -// 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 cloudiot - -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" - "github.com/hashicorp/terraform-provider-google/google/verify" -) - -func ResourceCloudIotDevice() *schema.Resource { - return &schema.Resource{ - Create: resourceCloudIotDeviceCreate, - Read: resourceCloudIotDeviceRead, - Update: resourceCloudIotDeviceUpdate, - Delete: resourceCloudIotDeviceDelete, - - Importer: &schema.ResourceImporter{ - State: resourceCloudIotDeviceImport, - }, - - 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{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - Description: `A unique name for the resource.`, - }, - "registry": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - Description: `The name of the device registry where this device should be created.`, - }, - "blocked": { - Type: schema.TypeBool, - Optional: true, - Description: `If a device is blocked, connections or requests from this device will fail.`, - }, - "credentials": { - Type: schema.TypeList, - Optional: true, - Description: `The credentials used to authenticate this device.`, - MaxItems: 3, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "public_key": { - Type: schema.TypeList, - Required: true, - Description: `A public key used to verify the signature of JSON Web Tokens (JWTs).`, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "format": { - Type: schema.TypeString, - Required: true, - ValidateFunc: verify.ValidateEnum([]string{"RSA_PEM", "RSA_X509_PEM", "ES256_PEM", "ES256_X509_PEM"}), - Description: `The format of the key. Possible values: ["RSA_PEM", "RSA_X509_PEM", "ES256_PEM", "ES256_X509_PEM"]`, - }, - "key": { - Type: schema.TypeString, - Required: true, - Description: `The key data.`, - }, - }, - }, - }, - "expiration_time": { - Type: schema.TypeString, - Computed: true, - Optional: true, - Description: `The time at which this credential becomes invalid.`, - }, - }, - }, - }, - "gateway_config": { - Type: schema.TypeList, - Optional: true, - Description: `Gateway-related configuration and state.`, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "gateway_auth_method": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: verify.ValidateEnum([]string{"ASSOCIATION_ONLY", "DEVICE_AUTH_TOKEN_ONLY", "ASSOCIATION_AND_DEVICE_AUTH_TOKEN", ""}), - Description: `Indicates whether the device is a gateway. Possible values: ["ASSOCIATION_ONLY", "DEVICE_AUTH_TOKEN_ONLY", "ASSOCIATION_AND_DEVICE_AUTH_TOKEN"]`, - }, - "gateway_type": { - Type: schema.TypeString, - Optional: true, - ForceNew: true, - ValidateFunc: verify.ValidateEnum([]string{"GATEWAY", "NON_GATEWAY", ""}), - Description: `Indicates whether the device is a gateway. Default value: "NON_GATEWAY" Possible values: ["GATEWAY", "NON_GATEWAY"]`, - Default: "NON_GATEWAY", - }, - "last_accessed_gateway_id": { - Type: schema.TypeString, - Computed: true, - Description: `The ID of the gateway the device accessed most recently.`, - }, - "last_accessed_gateway_time": { - Type: schema.TypeString, - Computed: true, - Description: `The most recent time at which the device accessed the gateway specified in last_accessed_gateway.`, - }, - }, - }, - }, - "log_level": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: verify.ValidateEnum([]string{"NONE", "ERROR", "INFO", "DEBUG", ""}), - Description: `The logging verbosity for device activity. Possible values: ["NONE", "ERROR", "INFO", "DEBUG"]`, - }, - "metadata": { - Type: schema.TypeMap, - Optional: true, - Description: `The metadata key-value pairs assigned to the device.`, - Elem: &schema.Schema{Type: schema.TypeString}, - }, - "config": { - Type: schema.TypeList, - Computed: true, - Description: `The most recent device configuration, which is eventually sent from Cloud IoT Core to the device.`, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "binary_data": { - Type: schema.TypeString, - Optional: true, - Description: `The device configuration data.`, - }, - "cloud_update_time": { - Type: schema.TypeString, - Computed: true, - Description: `The time at which this configuration version was updated in Cloud IoT Core.`, - }, - "device_ack_time": { - Type: schema.TypeString, - Computed: true, - Description: `The time at which Cloud IoT Core received the acknowledgment from the device, -indicating that the device has received this configuration version.`, - }, - "version": { - Type: schema.TypeString, - Computed: true, - Description: `The version of this update.`, - }, - }, - }, - }, - "last_config_ack_time": { - Type: schema.TypeString, - Computed: true, - Description: `The last time a cloud-to-device config version acknowledgment was received from the device.`, - }, - "last_config_send_time": { - Type: schema.TypeString, - Computed: true, - Description: `The last time a cloud-to-device config version was sent to the device.`, - }, - "last_error_status": { - Type: schema.TypeList, - Computed: true, - Description: `The error message of the most recent error, such as a failure to publish to Cloud Pub/Sub.`, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "details": { - Type: schema.TypeList, - Optional: true, - Description: `A list of messages that carry the error details.`, - Elem: &schema.Schema{ - Type: schema.TypeMap, - }, - }, - "message": { - Type: schema.TypeString, - Optional: true, - Description: `A developer-facing error message, which should be in English.`, - }, - "number": { - Type: schema.TypeInt, - Optional: true, - Description: `The status code, which should be an enum value of google.rpc.Code.`, - }, - }, - }, - }, - "last_error_time": { - Type: schema.TypeString, - Computed: true, - Description: `The time the most recent error occurred, such as a failure to publish to Cloud Pub/Sub.`, - }, - "last_event_time": { - Type: schema.TypeString, - Computed: true, - Description: `The last time a telemetry event was received.`, - }, - "last_heartbeat_time": { - Type: schema.TypeString, - Computed: true, - Description: `The last time an MQTT PINGREQ was received.`, - }, - "last_state_time": { - Type: schema.TypeString, - Computed: true, - Description: `The last time a state event was received.`, - }, - "num_id": { - Type: schema.TypeString, - Computed: true, - Description: `A server-defined unique numeric ID for the device. -This is a more compact way to identify devices, and it is globally unique.`, - }, - "state": { - Type: schema.TypeList, - Computed: true, - Description: `The state most recently received from the device.`, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "binary_data": { - Type: schema.TypeString, - Optional: true, - Description: `The device state data.`, - }, - "update_time": { - Type: schema.TypeString, - Optional: true, - Description: `The time at which this state version was updated in Cloud IoT Core.`, - }, - }, - }, - }, - }, - UseJSONNumber: true, - } -} - -func resourceCloudIotDeviceCreate(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{}) - idProp, err := expandCloudIotDeviceName(d.Get("name"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("name"); !tpgresource.IsEmptyValue(reflect.ValueOf(idProp)) && (ok || !reflect.DeepEqual(v, idProp)) { - obj["id"] = idProp - } - credentialsProp, err := expandCloudIotDeviceCredentials(d.Get("credentials"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("credentials"); !tpgresource.IsEmptyValue(reflect.ValueOf(credentialsProp)) && (ok || !reflect.DeepEqual(v, credentialsProp)) { - obj["credentials"] = credentialsProp - } - blockedProp, err := expandCloudIotDeviceBlocked(d.Get("blocked"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("blocked"); !tpgresource.IsEmptyValue(reflect.ValueOf(blockedProp)) && (ok || !reflect.DeepEqual(v, blockedProp)) { - obj["blocked"] = blockedProp - } - logLevelProp, err := expandCloudIotDeviceLogLevel(d.Get("log_level"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("log_level"); !tpgresource.IsEmptyValue(reflect.ValueOf(logLevelProp)) && (ok || !reflect.DeepEqual(v, logLevelProp)) { - obj["logLevel"] = logLevelProp - } - metadataProp, err := expandCloudIotDeviceMetadata(d.Get("metadata"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("metadata"); !tpgresource.IsEmptyValue(reflect.ValueOf(metadataProp)) && (ok || !reflect.DeepEqual(v, metadataProp)) { - obj["metadata"] = metadataProp - } - gatewayConfigProp, err := expandCloudIotDeviceGatewayConfig(d.Get("gateway_config"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("gateway_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(gatewayConfigProp)) && (ok || !reflect.DeepEqual(v, gatewayConfigProp)) { - obj["gatewayConfig"] = gatewayConfigProp - } - - url, err := tpgresource.ReplaceVars(d, config, "{{CloudIotBasePath}}{{registry}}/devices") - if err != nil { - return err - } - - log.Printf("[DEBUG] Creating new Device: %#v", obj) - billingProject := "" - - // 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 Device: %s", err) - } - - // Store the ID now - id, err := tpgresource.ReplaceVars(d, config, "{{registry}}/devices/{{name}}") - if err != nil { - return fmt.Errorf("Error constructing id: %s", err) - } - d.SetId(id) - - log.Printf("[DEBUG] Finished creating Device %q: %#v", d.Id(), res) - - return resourceCloudIotDeviceRead(d, meta) -} - -func resourceCloudIotDeviceRead(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, "{{CloudIotBasePath}}{{registry}}/devices/{{name}}") - if err != nil { - return err - } - - billingProject := "" - - // 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("CloudIotDevice %q", d.Id())) - } - - if err := d.Set("name", flattenCloudIotDeviceName(res["id"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("num_id", flattenCloudIotDeviceNumId(res["numId"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("credentials", flattenCloudIotDeviceCredentials(res["credentials"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("last_heartbeat_time", flattenCloudIotDeviceLastHeartbeatTime(res["lastHeartbeatTime"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("last_event_time", flattenCloudIotDeviceLastEventTime(res["lastEventTime"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("last_state_time", flattenCloudIotDeviceLastStateTime(res["lastStateTime"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("last_config_ack_time", flattenCloudIotDeviceLastConfigAckTime(res["lastConfigAckTime"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("last_config_send_time", flattenCloudIotDeviceLastConfigSendTime(res["lastConfigSendTime"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("blocked", flattenCloudIotDeviceBlocked(res["blocked"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("last_error_time", flattenCloudIotDeviceLastErrorTime(res["lastErrorTime"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("last_error_status", flattenCloudIotDeviceLastErrorStatus(res["lastErrorStatus"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("config", flattenCloudIotDeviceConfig(res["config"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("state", flattenCloudIotDeviceState(res["state"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("log_level", flattenCloudIotDeviceLogLevel(res["logLevel"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("metadata", flattenCloudIotDeviceMetadata(res["metadata"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - if err := d.Set("gateway_config", flattenCloudIotDeviceGatewayConfig(res["gatewayConfig"], d, config)); err != nil { - return fmt.Errorf("Error reading Device: %s", err) - } - - return nil -} - -func resourceCloudIotDeviceUpdate(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) - if err != nil { - return err - } - - billingProject := "" - - obj := make(map[string]interface{}) - credentialsProp, err := expandCloudIotDeviceCredentials(d.Get("credentials"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("credentials"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, credentialsProp)) { - obj["credentials"] = credentialsProp - } - blockedProp, err := expandCloudIotDeviceBlocked(d.Get("blocked"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("blocked"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, blockedProp)) { - obj["blocked"] = blockedProp - } - logLevelProp, err := expandCloudIotDeviceLogLevel(d.Get("log_level"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("log_level"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, logLevelProp)) { - obj["logLevel"] = logLevelProp - } - metadataProp, err := expandCloudIotDeviceMetadata(d.Get("metadata"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("metadata"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, metadataProp)) { - obj["metadata"] = metadataProp - } - gatewayConfigProp, err := expandCloudIotDeviceGatewayConfig(d.Get("gateway_config"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("gateway_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, gatewayConfigProp)) { - obj["gatewayConfig"] = gatewayConfigProp - } - - url, err := tpgresource.ReplaceVars(d, config, "{{CloudIotBasePath}}{{registry}}/devices/{{name}}") - if err != nil { - return err - } - - log.Printf("[DEBUG] Updating Device %q: %#v", d.Id(), obj) - updateMask := []string{} - - if d.HasChange("credentials") { - updateMask = append(updateMask, "credentials") - } - - if d.HasChange("blocked") { - updateMask = append(updateMask, "blocked") - } - - if d.HasChange("log_level") { - updateMask = append(updateMask, "logLevel") - } - - if d.HasChange("metadata") { - updateMask = append(updateMask, "metadata") - } - - if d.HasChange("gateway_config") { - updateMask = append(updateMask, "gateway_config.gateway_auth_method") - } - // updateMask is a URL parameter but not present in the schema, so ReplaceVars - // won't set it - url, err = transport_tpg.AddQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")}) - if err != nil { - return err - } - - // 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 Device %q: %s", d.Id(), err) - } else { - log.Printf("[DEBUG] Finished updating Device %q: %#v", d.Id(), res) - } - - return resourceCloudIotDeviceRead(d, meta) -} - -func resourceCloudIotDeviceDelete(d *schema.ResourceData, meta interface{}) error { - config := meta.(*transport_tpg.Config) - userAgent, err := tpgresource.GenerateUserAgentString(d, config.UserAgent) - if err != nil { - return err - } - - billingProject := "" - - url, err := tpgresource.ReplaceVars(d, config, "{{CloudIotBasePath}}{{registry}}/devices/{{name}}") - if err != nil { - return err - } - - var obj map[string]interface{} - log.Printf("[DEBUG] Deleting Device %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, "Device") - } - - log.Printf("[DEBUG] Finished deleting Device %q: %#v", d.Id(), res) - return nil -} - -func resourceCloudIotDeviceImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - config := meta.(*transport_tpg.Config) - if err := tpgresource.ParseImportId([]string{ - "(?P.+)/devices/(?P[^/]+)", - }, d, config); err != nil { - return nil, err - } - - // Replace import id for the resource id - id, err := tpgresource.ReplaceVars(d, config, "{{registry}}/devices/{{name}}") - if err != nil { - return nil, fmt.Errorf("Error constructing id: %s", err) - } - d.SetId(id) - - return []*schema.ResourceData{d}, nil -} - -func flattenCloudIotDeviceName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceNumId(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceCredentials(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{}{ - "expiration_time": flattenCloudIotDeviceCredentialsExpirationTime(original["expirationTime"], d, config), - "public_key": flattenCloudIotDeviceCredentialsPublicKey(original["publicKey"], d, config), - }) - } - return transformed -} -func flattenCloudIotDeviceCredentialsExpirationTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceCredentialsPublicKey(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["format"] = - flattenCloudIotDeviceCredentialsPublicKeyFormat(original["format"], d, config) - transformed["key"] = - flattenCloudIotDeviceCredentialsPublicKeyKey(original["key"], d, config) - return []interface{}{transformed} -} -func flattenCloudIotDeviceCredentialsPublicKeyFormat(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceCredentialsPublicKeyKey(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceLastHeartbeatTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceLastEventTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceLastStateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceLastConfigAckTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceLastConfigSendTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceBlocked(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceLastErrorTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceLastErrorStatus(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["number"] = - flattenCloudIotDeviceLastErrorStatusNumber(original["number"], d, config) - transformed["message"] = - flattenCloudIotDeviceLastErrorStatusMessage(original["message"], d, config) - transformed["details"] = - flattenCloudIotDeviceLastErrorStatusDetails(original["details"], d, config) - return []interface{}{transformed} -} -func flattenCloudIotDeviceLastErrorStatusNumber(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 flattenCloudIotDeviceLastErrorStatusMessage(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceLastErrorStatusDetails(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceConfig(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["version"] = - flattenCloudIotDeviceConfigVersion(original["version"], d, config) - transformed["cloud_update_time"] = - flattenCloudIotDeviceConfigCloudUpdateTime(original["cloudUpdateTime"], d, config) - transformed["device_ack_time"] = - flattenCloudIotDeviceConfigDeviceAckTime(original["deviceAckTime"], d, config) - transformed["binary_data"] = - flattenCloudIotDeviceConfigBinaryData(original["binaryData"], d, config) - return []interface{}{transformed} -} -func flattenCloudIotDeviceConfigVersion(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceConfigCloudUpdateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceConfigDeviceAckTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceConfigBinaryData(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceState(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["update_time"] = - flattenCloudIotDeviceStateUpdateTime(original["updateTime"], d, config) - transformed["binary_data"] = - flattenCloudIotDeviceStateBinaryData(original["binaryData"], d, config) - return []interface{}{transformed} -} -func flattenCloudIotDeviceStateUpdateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceStateBinaryData(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceLogLevel(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceMetadata(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceGatewayConfig(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["gateway_type"] = - flattenCloudIotDeviceGatewayConfigGatewayType(original["gatewayType"], d, config) - transformed["gateway_auth_method"] = - flattenCloudIotDeviceGatewayConfigGatewayAuthMethod(original["gatewayAuthMethod"], d, config) - transformed["last_accessed_gateway_id"] = - flattenCloudIotDeviceGatewayConfigLastAccessedGatewayId(original["lastAccessedGatewayId"], d, config) - transformed["last_accessed_gateway_time"] = - flattenCloudIotDeviceGatewayConfigLastAccessedGatewayTime(original["lastAccessedGatewayTime"], d, config) - return []interface{}{transformed} -} -func flattenCloudIotDeviceGatewayConfigGatewayType(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceGatewayConfigGatewayAuthMethod(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceGatewayConfigLastAccessedGatewayId(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceGatewayConfigLastAccessedGatewayTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func expandCloudIotDeviceName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceCredentials(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{}) - - transformedExpirationTime, err := expandCloudIotDeviceCredentialsExpirationTime(original["expiration_time"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedExpirationTime); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["expirationTime"] = transformedExpirationTime - } - - transformedPublicKey, err := expandCloudIotDeviceCredentialsPublicKey(original["public_key"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedPublicKey); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["publicKey"] = transformedPublicKey - } - - req = append(req, transformed) - } - return req, nil -} - -func expandCloudIotDeviceCredentialsExpirationTime(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceCredentialsPublicKey(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{}) - - transformedFormat, err := expandCloudIotDeviceCredentialsPublicKeyFormat(original["format"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedFormat); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["format"] = transformedFormat - } - - transformedKey, err := expandCloudIotDeviceCredentialsPublicKeyKey(original["key"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedKey); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["key"] = transformedKey - } - - return transformed, nil -} - -func expandCloudIotDeviceCredentialsPublicKeyFormat(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceCredentialsPublicKeyKey(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceBlocked(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceLogLevel(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceMetadata(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 -} - -func expandCloudIotDeviceGatewayConfig(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{}) - - transformedGatewayType, err := expandCloudIotDeviceGatewayConfigGatewayType(original["gateway_type"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedGatewayType); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["gatewayType"] = transformedGatewayType - } - - transformedGatewayAuthMethod, err := expandCloudIotDeviceGatewayConfigGatewayAuthMethod(original["gateway_auth_method"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedGatewayAuthMethod); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["gatewayAuthMethod"] = transformedGatewayAuthMethod - } - - transformedLastAccessedGatewayId, err := expandCloudIotDeviceGatewayConfigLastAccessedGatewayId(original["last_accessed_gateway_id"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedLastAccessedGatewayId); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["lastAccessedGatewayId"] = transformedLastAccessedGatewayId - } - - transformedLastAccessedGatewayTime, err := expandCloudIotDeviceGatewayConfigLastAccessedGatewayTime(original["last_accessed_gateway_time"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedLastAccessedGatewayTime); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["lastAccessedGatewayTime"] = transformedLastAccessedGatewayTime - } - - return transformed, nil -} - -func expandCloudIotDeviceGatewayConfigGatewayType(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceGatewayConfigGatewayAuthMethod(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceGatewayConfigLastAccessedGatewayId(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceGatewayConfigLastAccessedGatewayTime(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} diff --git a/google/services/cloudiot/resource_cloudiot_device_generated_test.go b/google/services/cloudiot/resource_cloudiot_device_generated_test.go deleted file mode 100644 index ebc026c3c18..00000000000 --- a/google/services/cloudiot/resource_cloudiot_device_generated_test.go +++ /dev/null @@ -1,170 +0,0 @@ -// 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 cloudiot_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/envvar" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -func TestAccCloudIotDevice_cloudiotDeviceBasicExample(t *testing.T) { - t.Parallel() - - context := map[string]interface{}{ - "project": envvar.GetTestProjectFromEnv(), - "region": envvar.GetTestRegionFromEnv(), - "random_suffix": acctest.RandString(t, 10), - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccCheckCloudIotDeviceDestroyProducer(t), - Steps: []resource.TestStep{ - { - Config: testAccCloudIotDevice_cloudiotDeviceBasicExample(context), - }, - { - ResourceName: "google_cloudiot_device.test-device", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"registry"}, - }, - }, - }) -} - -func testAccCloudIotDevice_cloudiotDeviceBasicExample(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_cloudiot_registry" "registry" { - name = "tf-test-cloudiot-device-registry%{random_suffix}" -} - -resource "google_cloudiot_device" "test-device" { - name = "tf-test-cloudiot-device%{random_suffix}" - registry = google_cloudiot_registry.registry.id -} -`, context) -} - -func TestAccCloudIotDevice_cloudiotDeviceFullExample(t *testing.T) { - t.Parallel() - - context := map[string]interface{}{ - "project": envvar.GetTestProjectFromEnv(), - "region": envvar.GetTestRegionFromEnv(), - "random_suffix": acctest.RandString(t, 10), - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccCheckCloudIotDeviceDestroyProducer(t), - Steps: []resource.TestStep{ - { - Config: testAccCloudIotDevice_cloudiotDeviceFullExample(context), - }, - { - ResourceName: "google_cloudiot_device.test-device", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"registry"}, - }, - }, - }) -} - -func testAccCloudIotDevice_cloudiotDeviceFullExample(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_cloudiot_registry" "registry" { - name = "tf-test-cloudiot-device-registry%{random_suffix}" -} - -resource "google_cloudiot_device" "test-device" { - name = "tf-test-cloudiot-device%{random_suffix}" - registry = google_cloudiot_registry.registry.id - - credentials { - public_key { - format = "RSA_PEM" - key = file("test-fixtures/rsa_public.pem") - } - } - - blocked = false - - log_level = "INFO" - - metadata = { - test_key_1 = "test_value_1" - } - - gateway_config { - gateway_type = "NON_GATEWAY" - } -} -`, context) -} - -func testAccCheckCloudIotDeviceDestroyProducer(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_cloudiot_device" { - continue - } - if strings.HasPrefix(name, "data.") { - continue - } - - config := acctest.GoogleProviderConfig(t) - - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{CloudIotBasePath}}{{registry}}/devices/{{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("CloudIotDevice still exists at %s", url) - } - } - - return nil - } -} diff --git a/google/services/cloudiot/resource_cloudiot_device_registry_id_test.go b/google/services/cloudiot/resource_cloudiot_device_registry_id_test.go deleted file mode 100644 index 710a65f3930..00000000000 --- a/google/services/cloudiot/resource_cloudiot_device_registry_id_test.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 -package cloudiot_test - -import ( - "strings" - "testing" - - "github.com/hashicorp/terraform-provider-google/google/services/cloudiot" - "github.com/hashicorp/terraform-provider-google/google/verify" -) - -func TestValidateCloudIoTDeviceRegistryId(t *testing.T) { - x := []verify.StringValidationTestCase{ - // No errors - {TestName: "basic", Value: "foobar"}, - {TestName: "with numbers", Value: "foobar123"}, - {TestName: "short", Value: "foo"}, - {TestName: "long", Value: "foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarfoo"}, - {TestName: "has a hyphen", Value: "foo-bar"}, - - // With errors - {TestName: "empty", Value: "", ExpectError: true}, - {TestName: "starts with a goog", Value: "googfoobar", ExpectError: true}, - {TestName: "starts with a number", Value: "1foobar", ExpectError: true}, - {TestName: "has an slash", Value: "foo/bar", ExpectError: true}, - {TestName: "has an backslash", Value: "foo\bar", ExpectError: true}, - {TestName: "too long", Value: strings.Repeat("f", 260), ExpectError: true}, - } - - es := verify.TestStringValidationCases(x, cloudiot.ValidateCloudIotDeviceRegistryID) - if len(es) > 0 { - t.Errorf("Failed to validate CloudIoT ID names: %v", es) - } -} diff --git a/google/services/cloudiot/resource_cloudiot_device_sweeper.go b/google/services/cloudiot/resource_cloudiot_device_sweeper.go deleted file mode 100644 index 21c95cd94f6..00000000000 --- a/google/services/cloudiot/resource_cloudiot_device_sweeper.go +++ /dev/null @@ -1,139 +0,0 @@ -// 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 cloudiot - -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("CloudIotDevice", testSweepCloudIotDevice) -} - -// At the time of writing, the CI only passes us-central1 as the region -func testSweepCloudIotDevice(region string) error { - resourceName := "CloudIotDevice" - 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://cloudiot.googleapis.com/v1/{{registry}}/devices", "?")[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["devices"] - 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://cloudiot.googleapis.com/v1/{{registry}}/devices/{{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/google/services/cloudiot/resource_cloudiot_device_update_test.go b/google/services/cloudiot/resource_cloudiot_device_update_test.go deleted file mode 100644 index 94126203393..00000000000 --- a/google/services/cloudiot/resource_cloudiot_device_update_test.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 -package cloudiot_test - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-provider-google/google/acctest" -) - -func TestAccCloudIoTDevice_update(t *testing.T) { - t.Parallel() - - registryName := fmt.Sprintf("psregistry-test-%s", acctest.RandString(t, 10)) - deviceName := fmt.Sprintf("psdevice-test-%s", acctest.RandString(t, 10)) - resourceName := fmt.Sprintf("google_cloudiot_device.%s", deviceName) - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccCheckCloudIotDeviceDestroyProducer(t), - Steps: []resource.TestStep{ - { - Config: testAccCloudIoTDeviceBasic(deviceName, registryName), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - { - Config: testAccCloudIoTDeviceExtended(deviceName, registryName), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - { - Config: testAccCloudIoTDeviceBasic(deviceName, registryName), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func testAccCloudIoTDeviceBasic(deviceName string, registryName string) string { - return fmt.Sprintf(` - -resource "google_cloudiot_registry" "%s" { - name = "%s" -} - -resource "google_cloudiot_device" "%s" { - name = "%s" - registry = google_cloudiot_registry.%s.id - - gateway_config { - gateway_auth_method = "DEVICE_AUTH_TOKEN_ONLY" - gateway_type = "GATEWAY" - } -} - - -`, registryName, registryName, deviceName, deviceName, registryName) -} - -func testAccCloudIoTDeviceExtended(deviceName string, registryName string) string { - return fmt.Sprintf(` - -resource "google_cloudiot_registry" "%s" { - name = "%s" -} - -resource "google_cloudiot_device" "%s" { - name = "%s" - registry = google_cloudiot_registry.%s.id - - credentials { - public_key { - format = "RSA_PEM" - key = file("test-fixtures/rsa_public.pem") - } - } - - blocked = false - - log_level = "INFO" - - metadata = { - test_key_1 = "test_value_1" - } - - gateway_config { - gateway_auth_method = "ASSOCIATION_AND_DEVICE_AUTH_TOKEN" - gateway_type = "GATEWAY" - } -} -`, registryName, registryName, deviceName, deviceName, registryName) -} diff --git a/google/services/cloudiot/resource_cloudiot_registry.go b/google/services/cloudiot/resource_cloudiot_registry.go deleted file mode 100644 index 04a737b6930..00000000000 --- a/google/services/cloudiot/resource_cloudiot_registry.go +++ /dev/null @@ -1,886 +0,0 @@ -// 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 cloudiot - -import ( - "fmt" - "log" - "reflect" - "regexp" - "strings" - "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 expandCloudIotDeviceRegistryHTTPConfig(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - original := v.(map[string]interface{}) - transformed := make(map[string]interface{}) - - transformedHTTPEnabledState, err := expandCloudIotDeviceRegistryHTTPEnabledState(original["http_enabled_state"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedHTTPEnabledState); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["httpEnabledState"] = transformedHTTPEnabledState - } - - return transformed, nil -} - -func expandCloudIotDeviceRegistryHTTPEnabledState(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceRegistryMqttConfig(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - original := v.(map[string]interface{}) - transformed := make(map[string]interface{}) - - transformedMqttEnabledState, err := expandCloudIotDeviceRegistryMqttEnabledState(original["mqtt_enabled_state"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedMqttEnabledState); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["mqttEnabledState"] = transformedMqttEnabledState - } - - return transformed, nil -} - -func expandCloudIotDeviceRegistryMqttEnabledState(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceRegistryStateNotificationConfig(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - original := v.(map[string]interface{}) - transformed := make(map[string]interface{}) - - transformedPubsubTopicName, err := expandCloudIotDeviceRegistryStateNotificationConfigPubsubTopicName(original["pubsub_topic_name"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedPubsubTopicName); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["pubsubTopicName"] = transformedPubsubTopicName - } - - return transformed, nil -} - -func expandCloudIotDeviceRegistryStateNotificationConfigPubsubTopicName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceRegistryCredentials(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{}) - - transformedPublicKeyCertificate, err := expandCloudIotDeviceRegistryCredentialsPublicKeyCertificate(original["public_key_certificate"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedPublicKeyCertificate); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["publicKeyCertificate"] = transformedPublicKeyCertificate - } - - req = append(req, transformed) - } - - return req, nil -} - -func expandCloudIotDeviceRegistryCredentialsPublicKeyCertificate(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - original := v.(map[string]interface{}) - transformed := make(map[string]interface{}) - - transformedFormat, err := expandCloudIotDeviceRegistryPublicKeyCertificateFormat(original["format"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedFormat); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["format"] = transformedFormat - } - - transformedCertificate, err := expandCloudIotDeviceRegistryPublicKeyCertificateCertificate(original["certificate"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedCertificate); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["certificate"] = transformedCertificate - } - - return transformed, nil -} - -func expandCloudIotDeviceRegistryPublicKeyCertificateFormat(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceRegistryPublicKeyCertificateCertificate(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func flattenCloudIotDeviceRegistryCredentials(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - log.Printf("[DEBUG] Flattening device resitry credentials: %q", d.Id()) - if v == nil { - log.Printf("[DEBUG] The credentials array is nil: %q", d.Id()) - return v - } - l := v.([]interface{}) - transformed := make([]interface{}, 0, len(l)) - for _, raw := range l { - original := raw.(map[string]interface{}) - log.Printf("[DEBUG] Original credential: %+v", original) - if len(original) < 1 { - log.Printf("[DEBUG] Excluding empty credential that the API returned. %q", d.Id()) - continue - } - log.Printf("[DEBUG] Credentials array before appending a new credential: %+v", transformed) - transformed = append(transformed, map[string]interface{}{ - "public_key_certificate": flattenCloudIotDeviceRegistryCredentialsPublicKeyCertificate(original["publicKeyCertificate"], d, config), - }) - log.Printf("[DEBUG] Credentials array after appending a new credential: %+v", transformed) - } - return transformed -} - -func flattenCloudIotDeviceRegistryCredentialsPublicKeyCertificate(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - log.Printf("[DEBUG] Flattening device resitry credentials public key certificate: %q", d.Id()) - if v == nil { - log.Printf("[DEBUG] The public key certificate is nil: %q", d.Id()) - return v - } - - original := v.(map[string]interface{}) - log.Printf("[DEBUG] Original public key certificate: %+v", original) - transformed := make(map[string]interface{}) - - transformedPublicKeyCertificateFormat := flattenCloudIotDeviceRegistryPublicKeyCertificateFormat(original["format"], d, config) - transformed["format"] = transformedPublicKeyCertificateFormat - - transformedPublicKeyCertificateCertificate := flattenCloudIotDeviceRegistryPublicKeyCertificateCertificate(original["certificate"], d, config) - transformed["certificate"] = transformedPublicKeyCertificateCertificate - - log.Printf("[DEBUG] Transformed public key certificate: %+v", transformed) - - return transformed -} - -func flattenCloudIotDeviceRegistryPublicKeyCertificateFormat(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceRegistryPublicKeyCertificateCertificate(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceRegistryHTTPConfig(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - if v == nil { - return v - } - - original := v.(map[string]interface{}) - transformed := make(map[string]interface{}) - - transformedHTTPEnabledState := flattenCloudIotDeviceRegistryHTTPConfigHTTPEnabledState(original["httpEnabledState"], d, config) - transformed["http_enabled_state"] = transformedHTTPEnabledState - - return transformed -} - -func flattenCloudIotDeviceRegistryHTTPConfigHTTPEnabledState(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceRegistryMqttConfig(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - if v == nil { - return v - } - - original := v.(map[string]interface{}) - transformed := make(map[string]interface{}) - - transformedMqttEnabledState := flattenCloudIotDeviceRegistryMqttConfigMqttEnabledState(original["mqttEnabledState"], d, config) - transformed["mqtt_enabled_state"] = transformedMqttEnabledState - - return transformed -} - -func flattenCloudIotDeviceRegistryMqttConfigMqttEnabledState(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceRegistryStateNotificationConfig(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - log.Printf("[DEBUG] Flattening state notification config: %+v", v) - if v == nil { - return v - } - - original := v.(map[string]interface{}) - transformed := make(map[string]interface{}) - - transformedPubsubTopicName := flattenCloudIotDeviceRegistryStateNotificationConfigPubsubTopicName(original["pubsubTopicName"], d, config) - if val := reflect.ValueOf(transformedPubsubTopicName); val.IsValid() && !tpgresource.IsEmptyValue(val) { - log.Printf("[DEBUG] pubsub topic name is not null: %v", d.Get("pubsub_topic_name")) - transformed["pubsub_topic_name"] = transformedPubsubTopicName - } - - return transformed -} - -func flattenCloudIotDeviceRegistryStateNotificationConfigPubsubTopicName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func ValidateCloudIotDeviceRegistryID(v interface{}, k string) (warnings []string, errors []error) { - value := v.(string) - if strings.HasPrefix(value, "goog") { - errors = append(errors, fmt.Errorf( - "%q (%q) can not start with \"goog\"", k, value)) - } - if !regexp.MustCompile(verify.CloudIoTIdRegex).MatchString(value) { - errors = append(errors, fmt.Errorf( - "%q (%q) doesn't match regexp %q", k, value, verify.CloudIoTIdRegex)) - } - return -} - -func validateCloudIotDeviceRegistrySubfolderMatch(v interface{}, k string) (warnings []string, errors []error) { - value := v.(string) - if strings.HasPrefix(value, "/") { - errors = append(errors, fmt.Errorf( - "%q (%q) can not start with '/'", k, value)) - } - return -} - -func ResourceCloudIotDeviceRegistry() *schema.Resource { - return &schema.Resource{ - Create: resourceCloudIotDeviceRegistryCreate, - Read: resourceCloudIotDeviceRegistryRead, - Update: resourceCloudIotDeviceRegistryUpdate, - Delete: resourceCloudIotDeviceRegistryDelete, - - Importer: &schema.ResourceImporter{ - State: resourceCloudIotDeviceRegistryImport, - }, - - Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(20 * time.Minute), - Update: schema.DefaultTimeout(20 * time.Minute), - Delete: schema.DefaultTimeout(20 * time.Minute), - }, - - CustomizeDiff: customdiff.All( - tpgresource.DefaultProviderProject, - tpgresource.DefaultProviderRegion, - ), - - Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - ValidateFunc: ValidateCloudIotDeviceRegistryID, - Description: `A unique name for the resource, required by device registry.`, - }, - "event_notification_configs": { - Type: schema.TypeList, - Computed: true, - Optional: true, - Description: `List of configurations for event notifications, such as PubSub topics -to publish device events to.`, - MaxItems: 10, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "pubsub_topic_name": { - Type: schema.TypeString, - Required: true, - DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName, - Description: `PubSub topic name to publish device events.`, - }, - "subfolder_matches": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: validateCloudIotDeviceRegistrySubfolderMatch, - Description: `If the subfolder name matches this string exactly, this -configuration will be used. The string must not include the -leading '/' character. If empty, all strings are matched. Empty -value can only be used for the last 'event_notification_configs' -item.`, - }, - }, - }, - }, - "log_level": { - Type: schema.TypeString, - Optional: true, - ValidateFunc: verify.ValidateEnum([]string{"NONE", "ERROR", "INFO", "DEBUG", ""}), - DiffSuppressFunc: tpgresource.EmptyOrDefaultStringSuppress("NONE"), - Description: `The default logging verbosity for activity from devices in this -registry. Specifies which events should be written to logs. For -example, if the LogLevel is ERROR, only events that terminate in -errors will be logged. LogLevel is inclusive; enabling INFO logging -will also enable ERROR logging. Default value: "NONE" Possible values: ["NONE", "ERROR", "INFO", "DEBUG"]`, - Default: "NONE", - }, - "region": { - Type: schema.TypeString, - Computed: true, - Optional: true, - ForceNew: true, - Description: `The region in which the created registry should reside. -If it is not provided, the provider region is used.`, - }, - "state_notification_config": { - Type: schema.TypeMap, - Description: `A PubSub topic to publish device state updates.`, - Optional: true, - }, - "mqtt_config": { - Type: schema.TypeMap, - Description: `Activate or deactivate MQTT.`, - Computed: true, - Optional: true, - }, - "http_config": { - Type: schema.TypeMap, - Description: `Activate or deactivate HTTP.`, - Computed: true, - Optional: true, - }, - "credentials": { - Type: schema.TypeList, - Description: `List of public key certificates to authenticate devices.`, - Optional: true, - MaxItems: 10, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "public_key_certificate": { - Type: schema.TypeMap, - Description: `A public key certificate format and data.`, - Required: true, - }, - }, - }, - }, - "project": { - Type: schema.TypeString, - Optional: true, - Computed: true, - ForceNew: true, - }, - }, - UseJSONNumber: true, - } -} - -func resourceCloudIotDeviceRegistryCreate(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{}) - idProp, err := expandCloudIotDeviceRegistryName(d.Get("name"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("name"); !tpgresource.IsEmptyValue(reflect.ValueOf(idProp)) && (ok || !reflect.DeepEqual(v, idProp)) { - obj["id"] = idProp - } - eventNotificationConfigsProp, err := expandCloudIotDeviceRegistryEventNotificationConfigs(d.Get("event_notification_configs"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("event_notification_configs"); !tpgresource.IsEmptyValue(reflect.ValueOf(eventNotificationConfigsProp)) && (ok || !reflect.DeepEqual(v, eventNotificationConfigsProp)) { - obj["eventNotificationConfigs"] = eventNotificationConfigsProp - } - logLevelProp, err := expandCloudIotDeviceRegistryLogLevel(d.Get("log_level"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("log_level"); !tpgresource.IsEmptyValue(reflect.ValueOf(logLevelProp)) && (ok || !reflect.DeepEqual(v, logLevelProp)) { - obj["logLevel"] = logLevelProp - } - - obj, err = resourceCloudIotDeviceRegistryEncoder(d, meta, obj) - if err != nil { - return err - } - - url, err := tpgresource.ReplaceVars(d, config, "{{CloudIotBasePath}}projects/{{project}}/locations/{{region}}/registries") - if err != nil { - return err - } - - log.Printf("[DEBUG] Creating new DeviceRegistry: %#v", obj) - billingProject := "" - - project, err := tpgresource.GetProject(d, config) - if err != nil { - return fmt.Errorf("Error fetching project for DeviceRegistry: %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 DeviceRegistry: %s", err) - } - - // Store the ID now - id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/{{region}}/registries/{{name}}") - if err != nil { - return fmt.Errorf("Error constructing id: %s", err) - } - d.SetId(id) - - log.Printf("[DEBUG] Finished creating DeviceRegistry %q: %#v", d.Id(), res) - - return resourceCloudIotDeviceRegistryRead(d, meta) -} - -func resourceCloudIotDeviceRegistryRead(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, "{{CloudIotBasePath}}projects/{{project}}/locations/{{region}}/registries/{{name}}") - if err != nil { - return err - } - - billingProject := "" - - project, err := tpgresource.GetProject(d, config) - if err != nil { - return fmt.Errorf("Error fetching project for DeviceRegistry: %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("CloudIotDeviceRegistry %q", d.Id())) - } - - res, err = resourceCloudIotDeviceRegistryDecoder(d, meta, res) - if err != nil { - return err - } - - if res == nil { - // Decoding the object has resulted in it being gone. It may be marked deleted - log.Printf("[DEBUG] Removing CloudIotDeviceRegistry because it no longer exists.") - d.SetId("") - return nil - } - - if err := d.Set("project", project); err != nil { - return fmt.Errorf("Error reading DeviceRegistry: %s", err) - } - - region, err := tpgresource.GetRegion(d, config) - if err != nil { - return err - } - if err := d.Set("region", region); err != nil { - return fmt.Errorf("Error reading DeviceRegistry: %s", err) - } - - if err := d.Set("name", flattenCloudIotDeviceRegistryName(res["id"], d, config)); err != nil { - return fmt.Errorf("Error reading DeviceRegistry: %s", err) - } - if err := d.Set("event_notification_configs", flattenCloudIotDeviceRegistryEventNotificationConfigs(res["eventNotificationConfigs"], d, config)); err != nil { - return fmt.Errorf("Error reading DeviceRegistry: %s", err) - } - if err := d.Set("log_level", flattenCloudIotDeviceRegistryLogLevel(res["logLevel"], d, config)); err != nil { - return fmt.Errorf("Error reading DeviceRegistry: %s", err) - } - - return nil -} - -func resourceCloudIotDeviceRegistryUpdate(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 DeviceRegistry: %s", err) - } - billingProject = project - - obj := make(map[string]interface{}) - eventNotificationConfigsProp, err := expandCloudIotDeviceRegistryEventNotificationConfigs(d.Get("event_notification_configs"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("event_notification_configs"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, eventNotificationConfigsProp)) { - obj["eventNotificationConfigs"] = eventNotificationConfigsProp - } - logLevelProp, err := expandCloudIotDeviceRegistryLogLevel(d.Get("log_level"), d, config) - if err != nil { - return err - } else if v, ok := d.GetOkExists("log_level"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, logLevelProp)) { - obj["logLevel"] = logLevelProp - } - - obj, err = resourceCloudIotDeviceRegistryEncoder(d, meta, obj) - if err != nil { - return err - } - - url, err := tpgresource.ReplaceVars(d, config, "{{CloudIotBasePath}}projects/{{project}}/locations/{{region}}/registries/{{name}}") - if err != nil { - return err - } - - log.Printf("[DEBUG] Updating DeviceRegistry %q: %#v", d.Id(), obj) - updateMask := []string{} - - if d.HasChange("event_notification_configs") { - updateMask = append(updateMask, "eventNotificationConfigs") - } - - if d.HasChange("log_level") { - updateMask = append(updateMask, "logLevel") - } - // updateMask is a URL parameter but not present in the schema, so ReplaceVars - // won't set it - url, err = transport_tpg.AddQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")}) - if err != nil { - return err - } - log.Printf("[DEBUG] updateMask before adding extra schema entries %q: %v", d.Id(), updateMask) - - log.Printf("[DEBUG] Pre-update on state notification config: %q", d.Id()) - if d.HasChange("state_notification_config") { - log.Printf("[DEBUG] %q stateNotificationConfig.pubsubTopicName has a change. Adding it to the update mask", d.Id()) - updateMask = append(updateMask, "stateNotificationConfig.pubsubTopicName") - } - - log.Printf("[DEBUG] Pre-update on MQTT config: %q", d.Id()) - if d.HasChange("mqtt_config") { - log.Printf("[DEBUG] %q mqttConfig.mqttEnabledState has a change. Adding it to the update mask", d.Id()) - updateMask = append(updateMask, "mqttConfig.mqttEnabledState") - } - - log.Printf("[DEBUG] Pre-update on HTTP config: %q", d.Id()) - if d.HasChange("http_config") { - log.Printf("[DEBUG] %q httpConfig.httpEnabledState has a change. Adding it to the update mask", d.Id()) - updateMask = append(updateMask, "httpConfig.httpEnabledState") - } - - log.Printf("[DEBUG] Pre-update on credentials: %q", d.Id()) - if d.HasChange("credentials") { - log.Printf("[DEBUG] %q credentials has a change. Adding it to the update mask", d.Id()) - updateMask = append(updateMask, "credentials") - } - - log.Printf("[DEBUG] updateMask after adding extra schema entries %q: %v", d.Id(), updateMask) - - // Refreshing updateMask after adding extra schema entries - url, err = transport_tpg.AddQueryParams(url, map[string]string{"updateMask": strings.Join(updateMask, ",")}) - if err != nil { - return err - } - - log.Printf("[DEBUG] Update URL %q: %v", d.Id(), url) - - // 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 DeviceRegistry %q: %s", d.Id(), err) - } else { - log.Printf("[DEBUG] Finished updating DeviceRegistry %q: %#v", d.Id(), res) - } - - return resourceCloudIotDeviceRegistryRead(d, meta) -} - -func resourceCloudIotDeviceRegistryDelete(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 DeviceRegistry: %s", err) - } - billingProject = project - - url, err := tpgresource.ReplaceVars(d, config, "{{CloudIotBasePath}}projects/{{project}}/locations/{{region}}/registries/{{name}}") - if err != nil { - return err - } - - var obj map[string]interface{} - log.Printf("[DEBUG] Deleting DeviceRegistry %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, "DeviceRegistry") - } - - log.Printf("[DEBUG] Finished deleting DeviceRegistry %q: %#v", d.Id(), res) - return nil -} - -func resourceCloudIotDeviceRegistryImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { - config := meta.(*transport_tpg.Config) - if err := tpgresource.ParseImportId([]string{ - "(?P[^/]+)/locations/(?P[^/]+)/registries/(?P[^/]+)", - "(?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}}/locations/{{region}}/registries/{{name}}") - if err != nil { - return nil, fmt.Errorf("Error constructing id: %s", err) - } - d.SetId(id) - - return []*schema.ResourceData{d}, nil -} - -func flattenCloudIotDeviceRegistryName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceRegistryEventNotificationConfigs(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{}{ - "subfolder_matches": flattenCloudIotDeviceRegistryEventNotificationConfigsSubfolderMatches(original["subfolderMatches"], d, config), - "pubsub_topic_name": flattenCloudIotDeviceRegistryEventNotificationConfigsPubsubTopicName(original["pubsubTopicName"], d, config), - }) - } - return transformed -} -func flattenCloudIotDeviceRegistryEventNotificationConfigsSubfolderMatches(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceRegistryEventNotificationConfigsPubsubTopicName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func flattenCloudIotDeviceRegistryLogLevel(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { - return v -} - -func expandCloudIotDeviceRegistryName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceRegistryEventNotificationConfigs(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{}) - - transformedSubfolderMatches, err := expandCloudIotDeviceRegistryEventNotificationConfigsSubfolderMatches(original["subfolder_matches"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedSubfolderMatches); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["subfolderMatches"] = transformedSubfolderMatches - } - - transformedPubsubTopicName, err := expandCloudIotDeviceRegistryEventNotificationConfigsPubsubTopicName(original["pubsub_topic_name"], d, config) - if err != nil { - return nil, err - } else if val := reflect.ValueOf(transformedPubsubTopicName); val.IsValid() && !tpgresource.IsEmptyValue(val) { - transformed["pubsubTopicName"] = transformedPubsubTopicName - } - - req = append(req, transformed) - } - return req, nil -} - -func expandCloudIotDeviceRegistryEventNotificationConfigsSubfolderMatches(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceRegistryEventNotificationConfigsPubsubTopicName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func expandCloudIotDeviceRegistryLogLevel(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { - return v, nil -} - -func resourceCloudIotDeviceRegistryEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) { - config := meta.(*transport_tpg.Config) - - log.Printf("[DEBUG] Resource data before encoding extra schema entries %q: %#v", d.Id(), obj) - - log.Printf("[DEBUG] Encoding state notification config: %q", d.Id()) - stateNotificationConfigProp, err := expandCloudIotDeviceRegistryStateNotificationConfig(d.Get("state_notification_config"), d, config) - if err != nil { - return nil, err - } else if v, ok := d.GetOkExists("state_notification_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(stateNotificationConfigProp)) && (ok || !reflect.DeepEqual(v, stateNotificationConfigProp)) { - log.Printf("[DEBUG] Encoding %q. Setting stateNotificationConfig: %#v", d.Id(), stateNotificationConfigProp) - obj["stateNotificationConfig"] = stateNotificationConfigProp - } - - log.Printf("[DEBUG] Encoding HTTP config: %q", d.Id()) - httpConfigProp, err := expandCloudIotDeviceRegistryHTTPConfig(d.Get("http_config"), d, config) - if err != nil { - return nil, err - } else if v, ok := d.GetOkExists("http_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(httpConfigProp)) && (ok || !reflect.DeepEqual(v, httpConfigProp)) { - log.Printf("[DEBUG] Encoding %q. Setting httpConfig: %#v", d.Id(), httpConfigProp) - obj["httpConfig"] = httpConfigProp - } - - log.Printf("[DEBUG] Encoding MQTT config: %q", d.Id()) - mqttConfigProp, err := expandCloudIotDeviceRegistryMqttConfig(d.Get("mqtt_config"), d, config) - if err != nil { - return nil, err - } else if v, ok := d.GetOkExists("mqtt_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(mqttConfigProp)) && (ok || !reflect.DeepEqual(v, mqttConfigProp)) { - log.Printf("[DEBUG] Encoding %q. Setting mqttConfig: %#v", d.Id(), mqttConfigProp) - obj["mqttConfig"] = mqttConfigProp - } - - log.Printf("[DEBUG] Encoding credentials: %q", d.Id()) - credentialsProp, err := expandCloudIotDeviceRegistryCredentials(d.Get("credentials"), d, config) - if err != nil { - return nil, err - } else if v, ok := d.GetOkExists("credentials"); !tpgresource.IsEmptyValue(reflect.ValueOf(credentialsProp)) && (ok || !reflect.DeepEqual(v, credentialsProp)) { - log.Printf("[DEBUG] Encoding %q. Setting credentials: %#v", d.Id(), credentialsProp) - obj["credentials"] = credentialsProp - } - - log.Printf("[DEBUG] Resource data after encoding extra schema entries %q: %#v", d.Id(), obj) - - return obj, nil -} - -func resourceCloudIotDeviceRegistryDecoder(d *schema.ResourceData, meta interface{}, res map[string]interface{}) (map[string]interface{}, error) { - config := meta.(*transport_tpg.Config) - - log.Printf("[DEBUG] Decoding state notification config: %q", d.Id()) - log.Printf("[DEBUG] State notification config before decoding: %v", d.Get("state_notification_config")) - if err := d.Set("state_notification_config", flattenCloudIotDeviceRegistryStateNotificationConfig(res["stateNotificationConfig"], d, config)); err != nil { - return nil, fmt.Errorf("Error reading DeviceRegistry: %s", err) - } - log.Printf("[DEBUG] State notification config after decoding: %v", d.Get("state_notification_config")) - - log.Printf("[DEBUG] Decoding HTTP config: %q", d.Id()) - log.Printf("[DEBUG] HTTP config before decoding: %v", d.Get("http_config")) - if err := d.Set("http_config", flattenCloudIotDeviceRegistryHTTPConfig(res["httpConfig"], d, config)); err != nil { - return nil, fmt.Errorf("Error reading DeviceRegistry: %s", err) - } - log.Printf("[DEBUG] HTTP config after decoding: %v", d.Get("http_config")) - - log.Printf("[DEBUG] Decoding MQTT config: %q", d.Id()) - log.Printf("[DEBUG] MQTT config before decoding: %v", d.Get("mqtt_config")) - if err := d.Set("mqtt_config", flattenCloudIotDeviceRegistryMqttConfig(res["mqttConfig"], d, config)); err != nil { - return nil, fmt.Errorf("Error reading DeviceRegistry: %s", err) - } - log.Printf("[DEBUG] MQTT config after decoding: %v", d.Get("mqtt_config")) - - log.Printf("[DEBUG] Decoding credentials: %q", d.Id()) - log.Printf("[DEBUG] credentials before decoding: %v", d.Get("credentials")) - if err := d.Set("credentials", flattenCloudIotDeviceRegistryCredentials(res["credentials"], d, config)); err != nil { - return nil, fmt.Errorf("Error reading DeviceRegistry: %s", err) - } - log.Printf("[DEBUG] credentials after decoding: %v", d.Get("credentials")) - - return res, nil -} diff --git a/google/services/cloudiot/resource_cloudiot_registry_generated_test.go b/google/services/cloudiot/resource_cloudiot_registry_generated_test.go deleted file mode 100644 index 2ae7a530a68..00000000000 --- a/google/services/cloudiot/resource_cloudiot_registry_generated_test.go +++ /dev/null @@ -1,229 +0,0 @@ -// 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 cloudiot_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/envvar" - "github.com/hashicorp/terraform-provider-google/google/tpgresource" - transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" -) - -func TestAccCloudIotDeviceRegistry_cloudiotDeviceRegistryBasicExample(t *testing.T) { - t.Parallel() - - context := map[string]interface{}{ - "project": envvar.GetTestProjectFromEnv(), - "region": envvar.GetTestRegionFromEnv(), - "random_suffix": acctest.RandString(t, 10), - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccCheckCloudIotDeviceRegistryDestroyProducer(t), - Steps: []resource.TestStep{ - { - Config: testAccCloudIotDeviceRegistry_cloudiotDeviceRegistryBasicExample(context), - }, - { - ResourceName: "google_cloudiot_registry.test-registry", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"region"}, - }, - }, - }) -} - -func testAccCloudIotDeviceRegistry_cloudiotDeviceRegistryBasicExample(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_cloudiot_registry" "test-registry" { - name = "tf-test-cloudiot-registry%{random_suffix}" -} -`, context) -} - -func TestAccCloudIotDeviceRegistry_cloudiotDeviceRegistrySingleEventNotificationConfigsExample(t *testing.T) { - t.Parallel() - - context := map[string]interface{}{ - "project": envvar.GetTestProjectFromEnv(), - "region": envvar.GetTestRegionFromEnv(), - "random_suffix": acctest.RandString(t, 10), - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccCheckCloudIotDeviceRegistryDestroyProducer(t), - Steps: []resource.TestStep{ - { - Config: testAccCloudIotDeviceRegistry_cloudiotDeviceRegistrySingleEventNotificationConfigsExample(context), - }, - { - ResourceName: "google_cloudiot_registry.test-registry", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"region"}, - }, - }, - }) -} - -func testAccCloudIotDeviceRegistry_cloudiotDeviceRegistrySingleEventNotificationConfigsExample(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_pubsub_topic" "default-telemetry" { - name = "tf-test-default-telemetry%{random_suffix}" -} - -resource "google_cloudiot_registry" "test-registry" { - name = "tf-test-cloudiot-registry%{random_suffix}" - - event_notification_configs { - pubsub_topic_name = google_pubsub_topic.default-telemetry.id - subfolder_matches = "" - } - -} -`, context) -} - -func TestAccCloudIotDeviceRegistry_cloudiotDeviceRegistryFullExample(t *testing.T) { - t.Parallel() - - context := map[string]interface{}{ - "project": envvar.GetTestProjectFromEnv(), - "region": envvar.GetTestRegionFromEnv(), - "random_suffix": acctest.RandString(t, 10), - } - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccCheckCloudIotDeviceRegistryDestroyProducer(t), - Steps: []resource.TestStep{ - { - Config: testAccCloudIotDeviceRegistry_cloudiotDeviceRegistryFullExample(context), - }, - { - ResourceName: "google_cloudiot_registry.test-registry", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"region"}, - }, - }, - }) -} - -func testAccCloudIotDeviceRegistry_cloudiotDeviceRegistryFullExample(context map[string]interface{}) string { - return acctest.Nprintf(` -resource "google_pubsub_topic" "default-devicestatus" { - name = "tf-test-default-devicestatus%{random_suffix}" -} - -resource "google_pubsub_topic" "default-telemetry" { - name = "tf-test-default-telemetry%{random_suffix}" -} - -resource "google_pubsub_topic" "additional-telemetry" { - name = "tf-test-additional-telemetry%{random_suffix}" -} - -resource "google_cloudiot_registry" "test-registry" { - name = "tf-test-cloudiot-registry%{random_suffix}" - - event_notification_configs { - pubsub_topic_name = google_pubsub_topic.additional-telemetry.id - subfolder_matches = "test/path%{random_suffix}" - } - - event_notification_configs { - pubsub_topic_name = google_pubsub_topic.default-telemetry.id - subfolder_matches = "" - } - - state_notification_config = { - pubsub_topic_name = google_pubsub_topic.default-devicestatus.id - } - - mqtt_config = { - mqtt_enabled_state = "MQTT_ENABLED" - } - - http_config = { - http_enabled_state = "HTTP_ENABLED" - } - - log_level = "INFO" - - credentials { - public_key_certificate = { - format = "X509_CERTIFICATE_PEM" - certificate = file("test-fixtures/rsa_cert.pem") - } - } -} -`, context) -} - -func testAccCheckCloudIotDeviceRegistryDestroyProducer(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_cloudiot_registry" { - continue - } - if strings.HasPrefix(name, "data.") { - continue - } - - config := acctest.GoogleProviderConfig(t) - - url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{CloudIotBasePath}}projects/{{project}}/locations/{{region}}/registries/{{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("CloudIotDeviceRegistry still exists at %s", url) - } - } - - return nil - } -} diff --git a/google/services/cloudiot/resource_cloudiot_registry_sweeper.go b/google/services/cloudiot/resource_cloudiot_registry_sweeper.go deleted file mode 100644 index 161314e0e6d..00000000000 --- a/google/services/cloudiot/resource_cloudiot_registry_sweeper.go +++ /dev/null @@ -1,139 +0,0 @@ -// 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 cloudiot - -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("CloudIotDeviceRegistry", testSweepCloudIotDeviceRegistry) -} - -// At the time of writing, the CI only passes us-central1 as the region -func testSweepCloudIotDeviceRegistry(region string) error { - resourceName := "CloudIotDeviceRegistry" - 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://cloudiot.googleapis.com/v1/projects/{{project}}/locations/{{region}}/registries", "?")[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["deviceRegistries"] - 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://cloudiot.googleapis.com/v1/projects/{{project}}/locations/{{region}}/registries/{{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/google/services/cloudiot/resource_cloudiot_registry_update_test.go b/google/services/cloudiot/resource_cloudiot_registry_update_test.go deleted file mode 100644 index baf391318e5..00000000000 --- a/google/services/cloudiot/resource_cloudiot_registry_update_test.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 -package cloudiot_test - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-provider-google/google/acctest" -) - -func TestAccCloudIoTRegistry_update(t *testing.T) { - t.Parallel() - - registryName := fmt.Sprintf("psregistry-test-%s", acctest.RandString(t, 10)) - resourceName := fmt.Sprintf("google_cloudiot_registry.%s", registryName) - deviceStatus := fmt.Sprintf("psregistry-test-devicestatus-%s", acctest.RandString(t, 10)) - defaultTelemetry := fmt.Sprintf("psregistry-test-telemetry-%s", acctest.RandString(t, 10)) - additionalTelemetry := fmt.Sprintf("psregistry-additional-test-telemetry-%s", acctest.RandString(t, 10)) - - acctest.VcrTest(t, resource.TestCase{ - PreCheck: func() { acctest.AccTestPreCheck(t) }, - ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), - CheckDestroy: testAccCheckCloudIotDeviceRegistryDestroyProducer(t), - Steps: []resource.TestStep{ - { - Config: testAccCloudIoTRegistryBasic(registryName), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - { - Config: testAccCloudIoTRegistryExtended(registryName, deviceStatus, defaultTelemetry, additionalTelemetry), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - { - Config: testAccCloudIoTRegistryBasic(registryName), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func testAccCloudIoTRegistryBasic(registryName string) string { - return fmt.Sprintf(` - -resource "google_cloudiot_registry" "%s" { - name = "%s" -} -`, registryName, registryName) -} - -func testAccCloudIoTRegistryExtended(registryName string, deviceStatus string, defaultTelemetry string, additionalTelemetry string) string { - return fmt.Sprintf(` - -resource "google_pubsub_topic" "default-devicestatus" { - name = "psregistry-test-devicestatus-%s" -} - -resource "google_pubsub_topic" "default-telemetry" { - name = "psregistry-test-telemetry-%s" -} - -resource "google_pubsub_topic" "additional-telemetry" { - name = "psregistry-additional-test-telemetry-%s" -} - -resource "google_cloudiot_registry" "%s" { - name = "%s" - - event_notification_configs { - pubsub_topic_name = google_pubsub_topic.additional-telemetry.id - subfolder_matches = "test/directory" - } - - event_notification_configs { - pubsub_topic_name = google_pubsub_topic.default-telemetry.id - subfolder_matches = "" - } - - state_notification_config = { - pubsub_topic_name = google_pubsub_topic.default-devicestatus.id - } - - mqtt_config = { - mqtt_enabled_state = "MQTT_DISABLED" - } - - http_config = { - http_enabled_state = "HTTP_DISABLED" - } - - credentials { - public_key_certificate = { - format = "X509_CERTIFICATE_PEM" - certificate = file("test-fixtures/rsa_cert.pem") - } - } -} -`, deviceStatus, defaultTelemetry, additionalTelemetry, registryName, registryName) -} diff --git a/google/services/cloudiot/test-fixtures/rsa_cert.pem b/google/services/cloudiot/test-fixtures/rsa_cert.pem deleted file mode 100644 index d8a834633c9..00000000000 --- a/google/services/cloudiot/test-fixtures/rsa_cert.pem +++ /dev/null @@ -1,17 +0,0 @@ ------BEGIN CERTIFICATE----- -MIICoDCCAYgCCQDzZ6R7RYs0sTANBgkqhkiG9w0BAQsFADARMQ8wDQYDVQQDDAZ1 -bnVzZWQwIBcNMTgwMTIwMTA0OTIzWhgPNDc1NTEyMTgxMDQ5MjNaMBExDzANBgNV -BAMMBnVudXNlZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMXX/5jI -tvxpst1mFVKVXfyu5S5AOQF+i/ny6Ef+h8py8y42XfsE2AAPSTE3JCIgWemw7NQ/ -xnTQ3f6b7/6+ZsdM4/hoiedwYV8X3LVPB9NRnKe82OHUhzo1psVMJVvHtE3GsD/V -i40ki/L4Xs64E2GJqQfrkgeNfIyCeKev64fR5aMazqOw1cNrVe34mY3L1hgXpn7e -SnO0oqnV86pTh+jTT8EKgo9AI7/QuJbPWpJhnj1/Fm8i3DdCdpQqloX9Fc4f6whA -XlZ2tkma0PsBraxMua5GPglJ7m3RabQIoyAW+4hEYAcu7U0wIhCK+C8WTNgEYZaK -zvp8vK6vOgBIjE0CAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAvVXus7dLikEAM6+I -6xeN7aHEMJRR0h2rigLiYjfl8R9zG/zxUPUunWPAYaKvWOFviXcX/KqpjDqIIeWx -Gm0yNfyalHq476nRCf/0t9AH5X4Qy0KJSW5KfhQLG9X2z/UiJxwHKCwaWZtEEzPu -mGqvwhNXUOL/GuAZCJWPdWrUGM4kHHz3kw5v3UPNS2xA7yMtN9N1b8/pkTQ77XNk -DA4wngA5zc7Ae72SJDrY8XXqLfL4Nagkrn6AOhGK3/Ewvca6hkThMcHI0WF2AqFo -mo3iGUJzR5lOUx+4RiEBC5NNEZsE9GMNEiu8kYvCAS0FMKYmxFPGx1U/kiOeeuIw -W3sOEA== ------END CERTIFICATE----- diff --git a/google/services/cloudiot/test-fixtures/rsa_public.pem b/google/services/cloudiot/test-fixtures/rsa_public.pem deleted file mode 100644 index 2b2acadf676..00000000000 --- a/google/services/cloudiot/test-fixtures/rsa_public.pem +++ /dev/null @@ -1,14 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAv6weC1aT16l2qS6qdYcy -7BOjzP7TwT9zUAiFhWpL256GRqC8yQRdqMsi68Q//762IUyu/qaHbEgQ8WRmQdVV -GDlxkBfrA/iXB2dgujq8jh0HWIV2ev3TerV3aUwvYUlrowhq027SX9U1hbufdGCM -uKsHiF05ErgNvEuR8XAkeJ/YV2DV2+sRq+Wg9y4RwUYbdchdFty1d5SX/s0Yqswg -yOG9VoCdR7baF22ughVR44aRm+83mgtqAZ4M+Rpe7JGRsUGY/pR391Toi0s8En15 -JGiAhqX2W0Uo/FZZry3yuqRfdHYENB+ADuyTMTrUaKZv7eua0lTBz5oom3jSF3gv -I7SQoLdK/jhEVOOq41IjB8D60Sgd69bD7yTI516yvZ/s3AyKzW6f6KnjdbCcZKKT -0GAePNLNhDYfSlA9bwJ8HQS2FenSpSTArKvGiVrsinJuNjbQdPuQHcpWf9x1m3GR -TMvF+TNYM/lp7IL2VMbJRfWPy1iWxm9F1Yr6dkHVoLP7ocYkNRHoPLut5E6IFJtK -lVI2NneUYJGnYSO+1xPV9TqlJeMNwr3uFMAN8N/oB3f4WWwuRYgR0L5g2A+Lvx+g -bbdl+Tb/0CNfslfSuDrFV8Z4n6gVwb9ZPGlNHCvnqRfLUpRFJwmR7UYvzi/E7rXJ -EDkK+tcnPkz2JtjdLKR7qVcCAwEAAQ== ------END PUBLIC KEY----- diff --git a/google/sweeper/gcp_sweeper_test.go b/google/sweeper/gcp_sweeper_test.go index 2b0fde0e8ff..86d2642adc0 100644 --- a/google/sweeper/gcp_sweeper_test.go +++ b/google/sweeper/gcp_sweeper_test.go @@ -33,7 +33,6 @@ import ( _ "github.com/hashicorp/terraform-provider-google/google/services/cloudfunctions2" _ "github.com/hashicorp/terraform-provider-google/google/services/cloudidentity" _ "github.com/hashicorp/terraform-provider-google/google/services/cloudids" - _ "github.com/hashicorp/terraform-provider-google/google/services/cloudiot" _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrun" _ "github.com/hashicorp/terraform-provider-google/google/services/cloudrunv2" _ "github.com/hashicorp/terraform-provider-google/google/services/cloudscheduler" diff --git a/google/transport/config.go b/google/transport/config.go index 200cd36d280..3cbc9ef85cc 100644 --- a/google/transport/config.go +++ b/google/transport/config.go @@ -208,7 +208,6 @@ type Config struct { Cloudfunctions2BasePath string CloudIdentityBasePath string CloudIdsBasePath string - CloudIotBasePath string CloudRunBasePath string CloudRunV2BasePath string CloudSchedulerBasePath string @@ -324,7 +323,6 @@ const CloudFunctionsBasePathKey = "CloudFunctions" const Cloudfunctions2BasePathKey = "Cloudfunctions2" const CloudIdentityBasePathKey = "CloudIdentity" const CloudIdsBasePathKey = "CloudIds" -const CloudIotBasePathKey = "CloudIot" const CloudRunBasePathKey = "CloudRun" const CloudRunV2BasePathKey = "CloudRunV2" const CloudSchedulerBasePathKey = "CloudScheduler" @@ -434,7 +432,6 @@ var DefaultBasePaths = map[string]string{ Cloudfunctions2BasePathKey: "https://cloudfunctions.googleapis.com/v2/", CloudIdentityBasePathKey: "https://cloudidentity.googleapis.com/v1/", CloudIdsBasePathKey: "https://ids.googleapis.com/v1/", - CloudIotBasePathKey: "https://cloudiot.googleapis.com/v1/", CloudRunBasePathKey: "https://{{location}}-run.googleapis.com/", CloudRunV2BasePathKey: "https://run.googleapis.com/v2/", CloudSchedulerBasePathKey: "https://cloudscheduler.googleapis.com/v1/", @@ -711,11 +708,6 @@ func HandleSDKDefaults(d *schema.ResourceData) error { "GOOGLE_CLOUD_IDS_CUSTOM_ENDPOINT", }, DefaultBasePaths[CloudIdsBasePathKey])) } - if d.Get("cloud_iot_custom_endpoint") == "" { - d.Set("cloud_iot_custom_endpoint", MultiEnvDefault([]string{ - "GOOGLE_CLOUD_IOT_CUSTOM_ENDPOINT", - }, DefaultBasePaths[CloudIotBasePathKey])) - } if d.Get("cloud_run_custom_endpoint") == "" { d.Set("cloud_run_custom_endpoint", MultiEnvDefault([]string{ "GOOGLE_CLOUD_RUN_CUSTOM_ENDPOINT", @@ -1922,7 +1914,6 @@ func ConfigureBasePaths(c *Config) { c.Cloudfunctions2BasePath = DefaultBasePaths[Cloudfunctions2BasePathKey] c.CloudIdentityBasePath = DefaultBasePaths[CloudIdentityBasePathKey] c.CloudIdsBasePath = DefaultBasePaths[CloudIdsBasePathKey] - c.CloudIotBasePath = DefaultBasePaths[CloudIotBasePathKey] c.CloudRunBasePath = DefaultBasePaths[CloudRunBasePathKey] c.CloudRunV2BasePath = DefaultBasePaths[CloudRunV2BasePathKey] c.CloudSchedulerBasePath = DefaultBasePaths[CloudSchedulerBasePathKey] diff --git a/website/docs/d/cloudiot_registry_iam_policy.html.markdown b/website/docs/d/cloudiot_registry_iam_policy.html.markdown deleted file mode 100644 index bcf075e10df..00000000000 --- a/website/docs/d/cloudiot_registry_iam_policy.html.markdown +++ /dev/null @@ -1,57 +0,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. -# -# ---------------------------------------------------------------------------- -subcategory: "Cloud IoT Core" -description: |- - A datasource to retrieve the IAM policy state for Cloud IoT Core DeviceRegistry ---- - - -# `google_cloudiot_registry_iam_policy` -Retrieves the current IAM policy data for deviceregistry - - - -## example - -```hcl -data "google_cloudiot_registry_iam_policy" "policy" { - project = google_cloudiot_registry.test-registry.project - region = google_cloudiot_registry.test-registry.region - name = google_cloudiot_registry.test-registry.name -} -``` - -## Argument Reference - -The following arguments are supported: - -* `name` - (Required) Used to find the parent resource to bind the IAM policy to -* `region` - (Optional) The region in which the created registry should reside. -If it is not provided, the provider region is used. - Used to find the parent resource to bind the IAM policy to. If not specified, - the value will be parsed from the identifier of the parent resource. If no region is provided in the parent identifier and no - region is specified, it is taken from the provider configuration. - -* `project` - (Optional) The ID of the project in which the resource belongs. - If it is not provided, the project will be parsed from the identifier of the parent resource. If no project is provided in the parent identifier and no project is specified, the provider project is used. - -## Attributes Reference - -The attributes are exported: - -* `etag` - (Computed) The etag of the IAM policy. - -* `policy_data` - (Required only by `google_cloudiot_registry_iam_policy`) The policy data generated by - a `google_iam_policy` data source. diff --git a/website/docs/r/cloudiot_device.html.markdown b/website/docs/r/cloudiot_device.html.markdown deleted file mode 100644 index b776aa0e690..00000000000 --- a/website/docs/r/cloudiot_device.html.markdown +++ /dev/null @@ -1,262 +0,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. -# -# ---------------------------------------------------------------------------- -subcategory: "Cloud IoT Core" -description: |- - A Google Cloud IoT Core device. ---- - -# google\_cloudiot\_device - -A Google Cloud IoT Core device. - - -To get more information about Device, see: - -* [API documentation](https://cloud.google.com/iot/docs/reference/cloudiot/rest/) -* How-to Guides - * [Official Documentation](https://cloud.google.com/iot/docs/) - -## Example Usage - Cloudiot Device Basic - - -```hcl -resource "google_cloudiot_registry" "registry" { - name = "cloudiot-device-registry" -} - -resource "google_cloudiot_device" "test-device" { - name = "cloudiot-device" - registry = google_cloudiot_registry.registry.id -} -``` -## Example Usage - Cloudiot Device Full - - -```hcl -resource "google_cloudiot_registry" "registry" { - name = "cloudiot-device-registry" -} - -resource "google_cloudiot_device" "test-device" { - name = "cloudiot-device" - registry = google_cloudiot_registry.registry.id - - credentials { - public_key { - format = "RSA_PEM" - key = file("test-fixtures/rsa_public.pem") - } - } - - blocked = false - - log_level = "INFO" - - metadata = { - test_key_1 = "test_value_1" - } - - gateway_config { - gateway_type = "NON_GATEWAY" - } -} -``` - -## Argument Reference - -The following arguments are supported: - - -* `name` - - (Required) - A unique name for the resource. - -* `registry` - - (Required) - The name of the device registry where this device should be created. - - -- - - - - -* `credentials` - - (Optional) - The credentials used to authenticate this device. - Structure is [documented below](#nested_credentials). - -* `blocked` - - (Optional) - If a device is blocked, connections or requests from this device will fail. - -* `log_level` - - (Optional) - The logging verbosity for device activity. - Possible values are: `NONE`, `ERROR`, `INFO`, `DEBUG`. - -* `metadata` - - (Optional) - The metadata key-value pairs assigned to the device. - -* `gateway_config` - - (Optional) - Gateway-related configuration and state. - Structure is [documented below](#nested_gateway_config). - - -The `credentials` block supports: - -* `expiration_time` - - (Optional) - The time at which this credential becomes invalid. - -* `public_key` - - (Required) - A public key used to verify the signature of JSON Web Tokens (JWTs). - Structure is [documented below](#nested_public_key). - - -The `public_key` block supports: - -* `format` - - (Required) - The format of the key. - Possible values are: `RSA_PEM`, `RSA_X509_PEM`, `ES256_PEM`, `ES256_X509_PEM`. - -* `key` - - (Required) - The key data. - -The `gateway_config` block supports: - -* `gateway_type` - - (Optional) - Indicates whether the device is a gateway. - Default value is `NON_GATEWAY`. - Possible values are: `GATEWAY`, `NON_GATEWAY`. - -* `gateway_auth_method` - - (Optional) - Indicates whether the device is a gateway. - Possible values are: `ASSOCIATION_ONLY`, `DEVICE_AUTH_TOKEN_ONLY`, `ASSOCIATION_AND_DEVICE_AUTH_TOKEN`. - -* `last_accessed_gateway_id` - - (Output) - The ID of the gateway the device accessed most recently. - -* `last_accessed_gateway_time` - - (Output) - The most recent time at which the device accessed the gateway specified in last_accessed_gateway. - -## Attributes Reference - -In addition to the arguments listed above, the following computed attributes are exported: - -* `id` - an identifier for the resource with format `{{registry}}/devices/{{name}}` - -* `num_id` - - A server-defined unique numeric ID for the device. - This is a more compact way to identify devices, and it is globally unique. - -* `last_heartbeat_time` - - The last time an MQTT PINGREQ was received. - -* `last_event_time` - - The last time a telemetry event was received. - -* `last_state_time` - - The last time a state event was received. - -* `last_config_ack_time` - - The last time a cloud-to-device config version acknowledgment was received from the device. - -* `last_config_send_time` - - The last time a cloud-to-device config version was sent to the device. - -* `last_error_time` - - The time the most recent error occurred, such as a failure to publish to Cloud Pub/Sub. - -* `last_error_status` - - The error message of the most recent error, such as a failure to publish to Cloud Pub/Sub. - Structure is [documented below](#nested_last_error_status). - -* `config` - - The most recent device configuration, which is eventually sent from Cloud IoT Core to the device. - Structure is [documented below](#nested_config). - -* `state` - - The state most recently received from the device. - Structure is [documented below](#nested_state). - - -The `last_error_status` block contains: - -* `number` - - (Optional) - The status code, which should be an enum value of google.rpc.Code. - -* `message` - - (Optional) - A developer-facing error message, which should be in English. - -* `details` - - (Optional) - A list of messages that carry the error details. - -The `config` block contains: - -* `version` - - (Output) - The version of this update. - -* `cloud_update_time` - - (Output) - The time at which this configuration version was updated in Cloud IoT Core. - -* `device_ack_time` - - (Output) - The time at which Cloud IoT Core received the acknowledgment from the device, - indicating that the device has received this configuration version. - -* `binary_data` - - (Optional) - The device configuration data. - -The `state` block contains: - -* `update_time` - - (Optional) - The time at which this state version was updated in Cloud IoT Core. - -* `binary_data` - - (Optional) - The device state data. - -## Timeouts - -This resource provides the following -[Timeouts](https://developer.hashicorp.com/terraform/plugin/sdkv2/resources/retries-and-customizable-timeouts) configuration options: - -- `create` - Default is 20 minutes. -- `update` - Default is 20 minutes. -- `delete` - Default is 20 minutes. - -## Import - - -Device can be imported using any of these accepted formats: - -``` -$ terraform import google_cloudiot_device.default {{registry}}/devices/{{name}} -``` diff --git a/website/docs/r/cloudiot_registry.html.markdown b/website/docs/r/cloudiot_registry.html.markdown deleted file mode 100644 index e73c01a7e16..00000000000 --- a/website/docs/r/cloudiot_registry.html.markdown +++ /dev/null @@ -1,224 +0,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. -# -# ---------------------------------------------------------------------------- -subcategory: "Cloud IoT Core" -description: |- - A Google Cloud IoT Core device registry. ---- - -# google\_cloudiot\_registry - -A Google Cloud IoT Core device registry. - - -To get more information about DeviceRegistry, see: - -* [API documentation](https://cloud.google.com/iot/docs/reference/cloudiot/rest/) -* How-to Guides - * [Official Documentation](https://cloud.google.com/iot/docs/) - -## Example Usage - Cloudiot Device Registry Basic - - -```hcl -resource "google_cloudiot_registry" "test-registry" { - name = "cloudiot-registry" -} -``` -## Example Usage - Cloudiot Device Registry Single Event Notification Configs - - -```hcl -resource "google_pubsub_topic" "default-telemetry" { - name = "default-telemetry" -} - -resource "google_cloudiot_registry" "test-registry" { - name = "cloudiot-registry" - - event_notification_configs { - pubsub_topic_name = google_pubsub_topic.default-telemetry.id - subfolder_matches = "" - } - -} -``` -## Example Usage - Cloudiot Device Registry Full - - -```hcl -resource "google_pubsub_topic" "default-devicestatus" { - name = "default-devicestatus" -} - -resource "google_pubsub_topic" "default-telemetry" { - name = "default-telemetry" -} - -resource "google_pubsub_topic" "additional-telemetry" { - name = "additional-telemetry" -} - -resource "google_cloudiot_registry" "test-registry" { - name = "cloudiot-registry" - - event_notification_configs { - pubsub_topic_name = google_pubsub_topic.additional-telemetry.id - subfolder_matches = "test/path" - } - - event_notification_configs { - pubsub_topic_name = google_pubsub_topic.default-telemetry.id - subfolder_matches = "" - } - - state_notification_config = { - pubsub_topic_name = google_pubsub_topic.default-devicestatus.id - } - - mqtt_config = { - mqtt_enabled_state = "MQTT_ENABLED" - } - - http_config = { - http_enabled_state = "HTTP_ENABLED" - } - - log_level = "INFO" - - credentials { - public_key_certificate = { - format = "X509_CERTIFICATE_PEM" - certificate = file("test-fixtures/rsa_cert.pem") - } - } -} -``` - -## Argument Reference - -The following arguments are supported: - - -* `name` - - (Required) - A unique name for the resource, required by device registry. - - -- - - - - -* `event_notification_configs` - - (Optional) - List of configurations for event notifications, such as PubSub topics - to publish device events to. - Structure is [documented below](#nested_event_notification_configs). - -* `log_level` - - (Optional) - The default logging verbosity for activity from devices in this - registry. Specifies which events should be written to logs. For - example, if the LogLevel is ERROR, only events that terminate in - errors will be logged. LogLevel is inclusive; enabling INFO logging - will also enable ERROR logging. - Default value is `NONE`. - Possible values are: `NONE`, `ERROR`, `INFO`, `DEBUG`. - -* `region` - - (Optional) - The region in which the created registry should reside. - If it is not provided, the provider region is used. - -* `project` - (Optional) The ID of the project in which the resource belongs. - If it is not provided, the provider project is used. - -* `state_notification_config` - A PubSub topic to publish device state updates. - The structure is documented below. - -* `mqtt_config` - Activate or deactivate MQTT. - The structure is documented below. - -* `http_config` - Activate or deactivate HTTP. - The structure is documented below. - -* `credentials` - List of public key certificates to authenticate devices. - The structure is documented below. - -The `state_notification_config` block supports: - -* `pubsub_topic_name` - PubSub topic name to publish device state updates. - -The `mqtt_config` block supports: - -* `mqtt_enabled_state` - The field allows `MQTT_ENABLED` or `MQTT_DISABLED`. - -The `http_config` block supports: - -* `http_enabled_state` - The field allows `HTTP_ENABLED` or `HTTP_DISABLED`. - -The `credentials` block supports: - -* `public_key_certificate` - A public key certificate format and data. - -The `public_key_certificate` block supports: - -* `format` - The field allows only `X509_CERTIFICATE_PEM`. - -* `certificate` - The certificate data. - -The `event_notification_configs` block supports: - -* `subfolder_matches` - - (Optional) - If the subfolder name matches this string exactly, this - configuration will be used. The string must not include the - leading '/' character. If empty, all strings are matched. Empty - value can only be used for the last `event_notification_configs` - item. - -* `pubsub_topic_name` - - (Required) - PubSub topic name to publish device events. - -## 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/{{region}}/registries/{{name}}` - - -## Timeouts - -This resource provides the following -[Timeouts](https://developer.hashicorp.com/terraform/plugin/sdkv2/resources/retries-and-customizable-timeouts) configuration options: - -- `create` - Default is 20 minutes. -- `update` - Default is 20 minutes. -- `delete` - Default is 20 minutes. - -## Import - - -DeviceRegistry can be imported using any of these accepted formats: - -``` -$ terraform import google_cloudiot_registry.default {{project}}/locations/{{region}}/registries/{{name}} -$ terraform import google_cloudiot_registry.default {{project}}/{{region}}/{{name}} -$ terraform import google_cloudiot_registry.default {{region}}/{{name}} -$ terraform import google_cloudiot_registry.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). diff --git a/website/docs/r/cloudiot_registry_iam.html.markdown b/website/docs/r/cloudiot_registry_iam.html.markdown deleted file mode 100644 index 01d6d7269ca..00000000000 --- a/website/docs/r/cloudiot_registry_iam.html.markdown +++ /dev/null @@ -1,158 +0,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. -# -# ---------------------------------------------------------------------------- -subcategory: "Cloud IoT Core" -description: |- - Collection of resources to manage IAM policy for Cloud IoT Core DeviceRegistry ---- - -# IAM policy for Cloud IoT Core DeviceRegistry -Three different resources help you manage your IAM policy for Cloud IoT Core DeviceRegistry. Each of these resources serves a different use case: - -* `google_cloudiot_registry_iam_policy`: Authoritative. Sets the IAM policy for the deviceregistry and replaces any existing policy already attached. -* `google_cloudiot_registry_iam_binding`: Authoritative for a given role. Updates the IAM policy to grant a role to a list of members. Other roles within the IAM policy for the deviceregistry are preserved. -* `google_cloudiot_registry_iam_member`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the deviceregistry are preserved. - -A data source can be used to retrieve policy data in advent you do not need creation - -* `google_cloudiot_registry_iam_policy`: Retrieves the IAM policy for the deviceregistry - -~> **Note:** `google_cloudiot_registry_iam_policy` **cannot** be used in conjunction with `google_cloudiot_registry_iam_binding` and `google_cloudiot_registry_iam_member` or they will fight over what your policy should be. - -~> **Note:** `google_cloudiot_registry_iam_binding` resources **can be** used in conjunction with `google_cloudiot_registry_iam_member` resources **only if** they do not grant privilege to the same role. - - - - -## google\_cloudiot\_registry\_iam\_policy - -```hcl -data "google_iam_policy" "admin" { - binding { - role = "roles/viewer" - members = [ - "user:jane@example.com", - ] - } -} - -resource "google_cloudiot_registry_iam_policy" "policy" { - project = google_cloudiot_registry.test-registry.project - region = google_cloudiot_registry.test-registry.region - name = google_cloudiot_registry.test-registry.name - policy_data = data.google_iam_policy.admin.policy_data -} -``` - -## google\_cloudiot\_registry\_iam\_binding - -```hcl -resource "google_cloudiot_registry_iam_binding" "binding" { - project = google_cloudiot_registry.test-registry.project - region = google_cloudiot_registry.test-registry.region - name = google_cloudiot_registry.test-registry.name - role = "roles/viewer" - members = [ - "user:jane@example.com", - ] -} -``` - -## google\_cloudiot\_registry\_iam\_member - -```hcl -resource "google_cloudiot_registry_iam_member" "member" { - project = google_cloudiot_registry.test-registry.project - region = google_cloudiot_registry.test-registry.region - name = google_cloudiot_registry.test-registry.name - role = "roles/viewer" - member = "user:jane@example.com" -} -``` - - -## Argument Reference - -The following arguments are supported: - -* `name` - (Required) Used to find the parent resource to bind the IAM policy to -* `region` - (Optional) The region in which the created registry should reside. -If it is not provided, the provider region is used. - Used to find the parent resource to bind the IAM policy to. If not specified, - the value will be parsed from the identifier of the parent resource. If no region is provided in the parent identifier and no - region is specified, it is taken from the provider configuration. - -* `project` - (Optional) The ID of the project in which the resource belongs. - If it is not provided, the project will be parsed from the identifier of the parent resource. If no project is provided in the parent identifier and no project is specified, the provider project is used. - -* `member/members` - (Required) Identities that will be granted the privilege in `role`. - Each entry can have one of the following values: - * **allUsers**: A special identifier that represents anyone who is on the internet; with or without a Google account. - * **allAuthenticatedUsers**: A special identifier that represents anyone who is authenticated with a Google account or a service account. - * **user:{emailid}**: An email address that represents a specific Google account. For example, alice@gmail.com or joe@example.com. - * **serviceAccount:{emailid}**: An email address that represents a service account. For example, my-other-app@appspot.gserviceaccount.com. - * **group:{emailid}**: An email address that represents a Google group. For example, admins@example.com. - * **domain:{domain}**: A G Suite domain (primary, instead of alias) name that represents all the users of that domain. For example, google.com or example.com. - * **projectOwner:projectid**: Owners of the given project. For example, "projectOwner:my-example-project" - * **projectEditor:projectid**: Editors of the given project. For example, "projectEditor:my-example-project" - * **projectViewer:projectid**: Viewers of the given project. For example, "projectViewer:my-example-project" - -* `role` - (Required) The role that should be applied. Only one - `google_cloudiot_registry_iam_binding` can be used per role. Note that custom roles must be of the format - `[projects|organizations]/{parent-name}/roles/{role-name}`. - -* `policy_data` - (Required only by `google_cloudiot_registry_iam_policy`) The policy data generated by - a `google_iam_policy` data source. - -## Attributes Reference - -In addition to the arguments listed above, the following computed attributes are -exported: - -* `etag` - (Computed) The etag of the IAM policy. - -## Import - -For all import syntaxes, the "resource in question" can take any of the following forms: - -* projects/{{project}}/locations/{{location}}/registries/{{name}} -* {{project}}/{{location}}/{{name}} -* {{location}}/{{name}} -* {{name}} - -Any variables not passed in the import command will be taken from the provider configuration. - -Cloud IoT Core deviceregistry IAM resources can be imported using the resource identifiers, role, and member. - -IAM member imports use space-delimited identifiers: the resource in question, the role, and the member identity, e.g. -``` -$ terraform import google_cloudiot_registry_iam_member.editor "projects/{{project}}/locations/{{location}}/registries/{{device_registry}} roles/viewer user:jane@example.com" -``` - -IAM binding imports use space-delimited identifiers: the resource in question and the role, e.g. -``` -$ terraform import google_cloudiot_registry_iam_binding.editor "projects/{{project}}/locations/{{location}}/registries/{{device_registry}} roles/viewer" -``` - -IAM policy imports use the identifier of the resource in question, e.g. -``` -$ terraform import google_cloudiot_registry_iam_policy.editor projects/{{project}}/locations/{{location}}/registries/{{device_registry}} -``` - --> **Custom Roles**: If you're importing a IAM resource with a custom role, make sure to use the - full name of the custom role, e.g. `[projects/my-project|organizations/my-org]/roles/my-custom-role`. - -## User Project Overrides - -This resource supports [User Project Overrides](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#user_project_override).