From bf69180d1dd9e4309eb6cc0d38b5687d9b1267a5 Mon Sep 17 00:00:00 2001 From: The Magician Date: Wed, 6 Mar 2024 07:20:37 -0800 Subject: [PATCH] Add new resource for Application for Apphub (#10079) (#17499) * Add new resource for Application for Apphub * Add new resource for Application for Apphub * Enable Apphub API in test cases * Fix precheck error * Fix precheck error * Resolve comments * Fix lint error * Fix examples * Remove apphub from teamcity config This causes PR build failures, I'll add it later --------- [upstream:55a1fa855d07e03b0ad43d070f3dc996fd6f2922] Signed-off-by: Modular Magician --- .changelog/10079.txt | 3 + .teamcity/components/inputs/services_beta.kt | 5 + .teamcity/components/inputs/services_ga.kt | 5 + google/fwmodels/provider_model.go | 1 + google/fwprovider/framework_provider.go | 6 + google/fwtransport/framework_config.go | 10 + google/provider/provider.go | 6 + google/provider/provider_mmv1_resources.go | 6 +- google/services/apphub/apphub_operation.go | 92 ++ .../apphub/resource_apphub_application.go | 1003 +++++++++++++++++ ...ource_apphub_application_generated_test.go | 166 +++ .../resource_apphub_application_sweeper.go | 143 +++ .../resource_apphub_application_test.go | 212 ++++ google/sweeper/gcp_sweeper_test.go | 1 + google/transport/config.go | 9 + .../docs/r/apphub_application.html.markdown | 269 +++++ 16 files changed, 1935 insertions(+), 2 deletions(-) create mode 100644 .changelog/10079.txt create mode 100644 google/services/apphub/apphub_operation.go create mode 100644 google/services/apphub/resource_apphub_application.go create mode 100644 google/services/apphub/resource_apphub_application_generated_test.go create mode 100644 google/services/apphub/resource_apphub_application_sweeper.go create mode 100644 google/services/apphub/resource_apphub_application_test.go create mode 100644 website/docs/r/apphub_application.html.markdown diff --git a/.changelog/10079.txt b/.changelog/10079.txt new file mode 100644 index 00000000000..c49185c89a4 --- /dev/null +++ b/.changelog/10079.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +google_apphub_application +``` \ No newline at end of file diff --git a/.teamcity/components/inputs/services_beta.kt b/.teamcity/components/inputs/services_beta.kt index 27550dabce1..443987885a6 100644 --- a/.teamcity/components/inputs/services_beta.kt +++ b/.teamcity/components/inputs/services_beta.kt @@ -48,6 +48,11 @@ var ServicesListBeta = mapOf( "displayName" to "Appengine", "path" to "./google-beta/services/appengine" ), + "apphub" to mapOf( + "name" to "apphub", + "displayName" to "Apphub", + "path" to "./google-beta/services/apphub" + ), "artifactregistry" to mapOf( "name" to "artifactregistry", "displayName" to "Artifactregistry", diff --git a/.teamcity/components/inputs/services_ga.kt b/.teamcity/components/inputs/services_ga.kt index 51f98ed08a0..08ce6c2ee82 100644 --- a/.teamcity/components/inputs/services_ga.kt +++ b/.teamcity/components/inputs/services_ga.kt @@ -48,6 +48,11 @@ var ServicesListGa = mapOf( "displayName" to "Appengine", "path" to "./google/services/appengine" ), + "apphub" to mapOf( + "name" to "apphub", + "displayName" to "Apphub", + "path" to "./google/services/apphub" + ), "artifactregistry" to mapOf( "name" to "artifactregistry", "displayName" to "Artifactregistry", diff --git a/google/fwmodels/provider_model.go b/google/fwmodels/provider_model.go index 5d54d840b6c..55897f70d01 100644 --- a/google/fwmodels/provider_model.go +++ b/google/fwmodels/provider_model.go @@ -34,6 +34,7 @@ type ProviderModel struct { AlloydbCustomEndpoint types.String `tfsdk:"alloydb_custom_endpoint"` ApigeeCustomEndpoint types.String `tfsdk:"apigee_custom_endpoint"` AppEngineCustomEndpoint types.String `tfsdk:"app_engine_custom_endpoint"` + ApphubCustomEndpoint types.String `tfsdk:"apphub_custom_endpoint"` ArtifactRegistryCustomEndpoint types.String `tfsdk:"artifact_registry_custom_endpoint"` BeyondcorpCustomEndpoint types.String `tfsdk:"beyondcorp_custom_endpoint"` BiglakeCustomEndpoint types.String `tfsdk:"biglake_custom_endpoint"` diff --git a/google/fwprovider/framework_provider.go b/google/fwprovider/framework_provider.go index bac2adedba9..4fe8489af09 100644 --- a/google/fwprovider/framework_provider.go +++ b/google/fwprovider/framework_provider.go @@ -178,6 +178,12 @@ func (p *FrameworkProvider) Schema(_ context.Context, _ provider.SchemaRequest, transport_tpg.CustomEndpointValidator(), }, }, + "apphub_custom_endpoint": &schema.StringAttribute{ + Optional: true, + Validators: []validator.String{ + transport_tpg.CustomEndpointValidator(), + }, + }, "artifact_registry_custom_endpoint": &schema.StringAttribute{ Optional: true, Validators: []validator.String{ diff --git a/google/fwtransport/framework_config.go b/google/fwtransport/framework_config.go index 7449d664555..89090b8c1c9 100644 --- a/google/fwtransport/framework_config.go +++ b/google/fwtransport/framework_config.go @@ -57,6 +57,7 @@ type FrameworkProviderConfig struct { AlloydbBasePath string ApigeeBasePath string AppEngineBasePath string + ApphubBasePath string ArtifactRegistryBasePath string BeyondcorpBasePath string BiglakeBasePath string @@ -208,6 +209,7 @@ func (p *FrameworkProviderConfig) LoadAndValidateFramework(ctx context.Context, p.AlloydbBasePath = data.AlloydbCustomEndpoint.ValueString() p.ApigeeBasePath = data.ApigeeCustomEndpoint.ValueString() p.AppEngineBasePath = data.AppEngineCustomEndpoint.ValueString() + p.ApphubBasePath = data.ApphubCustomEndpoint.ValueString() p.ArtifactRegistryBasePath = data.ArtifactRegistryCustomEndpoint.ValueString() p.BeyondcorpBasePath = data.BeyondcorpCustomEndpoint.ValueString() p.BiglakeBasePath = data.BiglakeCustomEndpoint.ValueString() @@ -489,6 +491,14 @@ func (p *FrameworkProviderConfig) HandleDefaults(ctx context.Context, data *fwmo data.AppEngineCustomEndpoint = types.StringValue(customEndpoint.(string)) } } + if data.ApphubCustomEndpoint.IsNull() { + customEndpoint := transport_tpg.MultiEnvDefault([]string{ + "GOOGLE_APPHUB_CUSTOM_ENDPOINT", + }, transport_tpg.DefaultBasePaths[transport_tpg.ApphubBasePathKey]) + if customEndpoint != nil { + data.ApphubCustomEndpoint = types.StringValue(customEndpoint.(string)) + } + } if data.ArtifactRegistryCustomEndpoint.IsNull() { customEndpoint := transport_tpg.MultiEnvDefault([]string{ "GOOGLE_ARTIFACT_REGISTRY_CUSTOM_ENDPOINT", diff --git a/google/provider/provider.go b/google/provider/provider.go index 43ac24f8e84..c8f40b75c83 100644 --- a/google/provider/provider.go +++ b/google/provider/provider.go @@ -175,6 +175,11 @@ func Provider() *schema.Provider { Optional: true, ValidateFunc: transport_tpg.ValidateCustomEndpoint, }, + "apphub_custom_endpoint": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: transport_tpg.ValidateCustomEndpoint, + }, "artifact_registry_custom_endpoint": { Type: schema.TypeString, Optional: true, @@ -925,6 +930,7 @@ func ProviderConfigure(ctx context.Context, d *schema.ResourceData, p *schema.Pr config.AlloydbBasePath = d.Get("alloydb_custom_endpoint").(string) config.ApigeeBasePath = d.Get("apigee_custom_endpoint").(string) config.AppEngineBasePath = d.Get("app_engine_custom_endpoint").(string) + config.ApphubBasePath = d.Get("apphub_custom_endpoint").(string) config.ArtifactRegistryBasePath = d.Get("artifact_registry_custom_endpoint").(string) config.BeyondcorpBasePath = d.Get("beyondcorp_custom_endpoint").(string) config.BiglakeBasePath = d.Get("biglake_custom_endpoint").(string) diff --git a/google/provider/provider_mmv1_resources.go b/google/provider/provider_mmv1_resources.go index 90c52be3b26..7c6e12b0bb3 100644 --- a/google/provider/provider_mmv1_resources.go +++ b/google/provider/provider_mmv1_resources.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/terraform-provider-google/google/services/alloydb" "github.com/hashicorp/terraform-provider-google/google/services/apigee" "github.com/hashicorp/terraform-provider-google/google/services/appengine" + "github.com/hashicorp/terraform-provider-google/google/services/apphub" "github.com/hashicorp/terraform-provider-google/google/services/artifactregistry" "github.com/hashicorp/terraform-provider-google/google/services/beyondcorp" "github.com/hashicorp/terraform-provider-google/google/services/biglake" @@ -388,9 +389,9 @@ var handwrittenIAMDatasources = map[string]*schema.Resource{ } // Resources -// Generated resources: 387 +// Generated resources: 388 // Generated IAM resources: 231 -// Total generated resources: 618 +// Total generated resources: 619 var generatedResources = map[string]*schema.Resource{ "google_folder_access_approval_settings": accessapproval.ResourceAccessApprovalFolderSettings(), "google_organization_access_approval_settings": accessapproval.ResourceAccessApprovalOrganizationSettings(), @@ -441,6 +442,7 @@ var generatedResources = map[string]*schema.Resource{ "google_app_engine_service_network_settings": appengine.ResourceAppEngineServiceNetworkSettings(), "google_app_engine_service_split_traffic": appengine.ResourceAppEngineServiceSplitTraffic(), "google_app_engine_standard_app_version": appengine.ResourceAppEngineStandardAppVersion(), + "google_apphub_application": apphub.ResourceApphubApplication(), "google_artifact_registry_repository": artifactregistry.ResourceArtifactRegistryRepository(), "google_artifact_registry_repository_iam_binding": tpgiamresource.ResourceIamBinding(artifactregistry.ArtifactRegistryRepositoryIamSchema, artifactregistry.ArtifactRegistryRepositoryIamUpdaterProducer, artifactregistry.ArtifactRegistryRepositoryIdParseFunc), "google_artifact_registry_repository_iam_member": tpgiamresource.ResourceIamMember(artifactregistry.ArtifactRegistryRepositoryIamSchema, artifactregistry.ArtifactRegistryRepositoryIamUpdaterProducer, artifactregistry.ArtifactRegistryRepositoryIdParseFunc), diff --git a/google/services/apphub/apphub_operation.go b/google/services/apphub/apphub_operation.go new file mode 100644 index 00000000000..662ee7c875e --- /dev/null +++ b/google/services/apphub/apphub_operation.go @@ -0,0 +1,92 @@ +// 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 apphub + +import ( + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +type ApphubOperationWaiter struct { + Config *transport_tpg.Config + UserAgent string + Project string + tpgresource.CommonOperationWaiter +} + +func (w *ApphubOperationWaiter) QueryOp() (interface{}, error) { + if w == nil { + return nil, fmt.Errorf("Cannot query operation, it's unset or nil.") + } + // Returns the proper get. + url := fmt.Sprintf("%s%s", w.Config.ApphubBasePath, w.CommonOperationWaiter.Op.Name) + + return transport_tpg.SendRequest(transport_tpg.SendRequestOptions{ + Config: w.Config, + Method: "GET", + Project: w.Project, + RawURL: url, + UserAgent: w.UserAgent, + }) +} + +func createApphubWaiter(config *transport_tpg.Config, op map[string]interface{}, project, activity, userAgent string) (*ApphubOperationWaiter, error) { + w := &ApphubOperationWaiter{ + Config: config, + UserAgent: userAgent, + Project: project, + } + if err := w.CommonOperationWaiter.SetOp(op); err != nil { + return nil, err + } + return w, nil +} + +// nolint: deadcode,unused +func ApphubOperationWaitTimeWithResponse(config *transport_tpg.Config, op map[string]interface{}, response *map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error { + w, err := createApphubWaiter(config, op, project, activity, userAgent) + if err != nil { + return err + } + if err := tpgresource.OperationWait(w, activity, timeout, config.PollInterval); err != nil { + return err + } + rawResponse := []byte(w.CommonOperationWaiter.Op.Response) + if len(rawResponse) == 0 { + return errors.New("`resource` not set in operation response") + } + return json.Unmarshal(rawResponse, response) +} + +func ApphubOperationWaitTime(config *transport_tpg.Config, op map[string]interface{}, project, activity, userAgent string, timeout time.Duration) error { + if val, ok := op["name"]; !ok || val == "" { + // This was a synchronous call - there is no operation to wait for. + return nil + } + w, err := createApphubWaiter(config, op, project, activity, userAgent) + if err != nil { + // If w is nil, the op was synchronous. + return err + } + return tpgresource.OperationWait(w, activity, timeout, config.PollInterval) +} diff --git a/google/services/apphub/resource_apphub_application.go b/google/services/apphub/resource_apphub_application.go new file mode 100644 index 00000000000..71213424514 --- /dev/null +++ b/google/services/apphub/resource_apphub_application.go @@ -0,0 +1,1003 @@ +// 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 apphub + +import ( + "fmt" + "log" + "reflect" + "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 ResourceApphubApplication() *schema.Resource { + return &schema.Resource{ + Create: resourceApphubApplicationCreate, + Read: resourceApphubApplicationRead, + Update: resourceApphubApplicationUpdate, + Delete: resourceApphubApplicationDelete, + + Importer: &schema.ResourceImporter{ + State: resourceApphubApplicationImport, + }, + + 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, + ), + + Schema: map[string]*schema.Schema{ + "application_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Required. The Application identifier.`, + }, + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Part of 'parent'. See documentation of 'projectsId'.`, + }, + "scope": { + Type: schema.TypeList, + Required: true, + Description: `Scope of an application.`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidateEnum([]string{"REGIONAL"}), + Description: `Required. Scope Type. + Possible values: +REGIONAL Possible values: ["REGIONAL"]`, + }, + }, + }, + }, + "attributes": { + Type: schema.TypeList, + Optional: true, + Description: `Consumer provided attributes.`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "business_owners": { + Type: schema.TypeList, + Optional: true, + Description: `Optional. Business team that ensures user needs are met and value is delivered`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "email": { + Type: schema.TypeString, + Required: true, + Description: `Required. Email address of the contacts.`, + }, + "display_name": { + Type: schema.TypeString, + Optional: true, + Description: `Optional. Contact's name.`, + }, + }, + }, + }, + "criticality": { + Type: schema.TypeList, + Optional: true, + Description: `Criticality of the Application, Service, or Workload`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidateEnum([]string{"MISSION_CRITICAL", "HIGH", "MEDIUM", "LOW"}), + Description: `Criticality type. Possible values: ["MISSION_CRITICAL", "HIGH", "MEDIUM", "LOW"]`, + }, + }, + }, + }, + "developer_owners": { + Type: schema.TypeList, + Optional: true, + Description: `Optional. Developer team that owns development and coding.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "email": { + Type: schema.TypeString, + Required: true, + Description: `Required. Email address of the contacts.`, + }, + "display_name": { + Type: schema.TypeString, + Optional: true, + Description: `Optional. Contact's name.`, + }, + }, + }, + }, + "environment": { + Type: schema.TypeList, + Optional: true, + Description: `Environment of the Application, Service, or Workload`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "type": { + Type: schema.TypeString, + Required: true, + ValidateFunc: verify.ValidateEnum([]string{"PRODUCTION", "STAGING", "TEST", "DEVELOPMENT"}), + Description: `Environment type. Possible values: ["PRODUCTION", "STAGING", "TEST", "DEVELOPMENT"]`, + }, + }, + }, + }, + "operator_owners": { + Type: schema.TypeList, + Optional: true, + Description: `Optional. Operator team that ensures runtime and operations.`, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "email": { + Type: schema.TypeString, + Required: true, + Description: `Required. Email address of the contacts.`, + }, + "display_name": { + Type: schema.TypeString, + Optional: true, + Description: `Optional. Contact's name.`, + }, + }, + }, + }, + }, + }, + }, + "description": { + Type: schema.TypeString, + Optional: true, + Description: `Optional. User-defined description of an Application.`, + }, + "display_name": { + Type: schema.TypeString, + Optional: true, + Description: `Optional. User-defined name for the Application.`, + }, + "create_time": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. Create time.`, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: `Identifier. The resource name of an Application. Format: +"projects/{host-project-id}/locations/{location}/applications/{application-id}"`, + }, + "state": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. Application state. + Possible values: + STATE_UNSPECIFIED +CREATING +ACTIVE +DELETING`, + }, + "uid": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. A universally unique identifier (in UUID4 format) for the 'Application'.`, + }, + "update_time": { + Type: schema.TypeString, + Computed: true, + Description: `Output only. Update time.`, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceApphubApplicationCreate(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{}) + displayNameProp, err := expandApphubApplicationDisplayName(d.Get("display_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("display_name"); !tpgresource.IsEmptyValue(reflect.ValueOf(displayNameProp)) && (ok || !reflect.DeepEqual(v, displayNameProp)) { + obj["displayName"] = displayNameProp + } + descriptionProp, err := expandApphubApplicationDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !tpgresource.IsEmptyValue(reflect.ValueOf(descriptionProp)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + attributesProp, err := expandApphubApplicationAttributes(d.Get("attributes"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("attributes"); !tpgresource.IsEmptyValue(reflect.ValueOf(attributesProp)) && (ok || !reflect.DeepEqual(v, attributesProp)) { + obj["attributes"] = attributesProp + } + scopeProp, err := expandApphubApplicationScope(d.Get("scope"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("scope"); !tpgresource.IsEmptyValue(reflect.ValueOf(scopeProp)) && (ok || !reflect.DeepEqual(v, scopeProp)) { + obj["scope"] = scopeProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{ApphubBasePath}}projects/{{project}}/locations/{{location}}/applications?applicationId={{application_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new Application: %#v", obj) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for Application: %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 Application: %s", err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/{{location}}/applications/{{application_id}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + // Use the resource in the operation response to populate + // identity fields and d.Id() before read + var opRes map[string]interface{} + err = ApphubOperationWaitTimeWithResponse( + config, res, &opRes, project, "Creating Application", userAgent, + d.Timeout(schema.TimeoutCreate)) + if err != nil { + // The resource didn't actually create + d.SetId("") + + return fmt.Errorf("Error waiting to create Application: %s", err) + } + + if err := d.Set("name", flattenApphubApplicationName(opRes["name"], d, config)); err != nil { + return err + } + + // This may have caused the ID to update - update it if so. + id, err = tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/{{location}}/applications/{{application_id}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating Application %q: %#v", d.Id(), res) + + return resourceApphubApplicationRead(d, meta) +} + +func resourceApphubApplicationRead(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, "{{ApphubBasePath}}projects/{{project}}/locations/{{location}}/applications/{{application_id}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for Application: %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("ApphubApplication %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading Application: %s", err) + } + + if err := d.Set("name", flattenApphubApplicationName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading Application: %s", err) + } + if err := d.Set("display_name", flattenApphubApplicationDisplayName(res["displayName"], d, config)); err != nil { + return fmt.Errorf("Error reading Application: %s", err) + } + if err := d.Set("description", flattenApphubApplicationDescription(res["description"], d, config)); err != nil { + return fmt.Errorf("Error reading Application: %s", err) + } + if err := d.Set("attributes", flattenApphubApplicationAttributes(res["attributes"], d, config)); err != nil { + return fmt.Errorf("Error reading Application: %s", err) + } + if err := d.Set("create_time", flattenApphubApplicationCreateTime(res["createTime"], d, config)); err != nil { + return fmt.Errorf("Error reading Application: %s", err) + } + if err := d.Set("update_time", flattenApphubApplicationUpdateTime(res["updateTime"], d, config)); err != nil { + return fmt.Errorf("Error reading Application: %s", err) + } + if err := d.Set("scope", flattenApphubApplicationScope(res["scope"], d, config)); err != nil { + return fmt.Errorf("Error reading Application: %s", err) + } + if err := d.Set("uid", flattenApphubApplicationUid(res["uid"], d, config)); err != nil { + return fmt.Errorf("Error reading Application: %s", err) + } + if err := d.Set("state", flattenApphubApplicationState(res["state"], d, config)); err != nil { + return fmt.Errorf("Error reading Application: %s", err) + } + + return nil +} + +func resourceApphubApplicationUpdate(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 Application: %s", err) + } + billingProject = project + + obj := make(map[string]interface{}) + displayNameProp, err := expandApphubApplicationDisplayName(d.Get("display_name"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("display_name"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, displayNameProp)) { + obj["displayName"] = displayNameProp + } + descriptionProp, err := expandApphubApplicationDescription(d.Get("description"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("description"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, descriptionProp)) { + obj["description"] = descriptionProp + } + attributesProp, err := expandApphubApplicationAttributes(d.Get("attributes"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("attributes"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, attributesProp)) { + obj["attributes"] = attributesProp + } + scopeProp, err := expandApphubApplicationScope(d.Get("scope"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("scope"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, scopeProp)) { + obj["scope"] = scopeProp + } + + url, err := tpgresource.ReplaceVars(d, config, "{{ApphubBasePath}}projects/{{project}}/locations/{{location}}/applications/{{application_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating Application %q: %#v", d.Id(), obj) + updateMask := []string{} + + if d.HasChange("display_name") { + updateMask = append(updateMask, "displayName") + } + + if d.HasChange("description") { + updateMask = append(updateMask, "description") + } + + if d.HasChange("attributes") { + updateMask = append(updateMask, "attributes") + } + + if d.HasChange("scope") { + updateMask = append(updateMask, "scope") + } + // 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 + } + + // if updateMask is empty we are not updating anything so skip the post + if len(updateMask) > 0 { + 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 Application %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating Application %q: %#v", d.Id(), res) + } + + err = ApphubOperationWaitTime( + config, res, project, "Updating Application", userAgent, + d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return err + } + } + + return resourceApphubApplicationRead(d, meta) +} + +func resourceApphubApplicationDelete(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 Application: %s", err) + } + billingProject = project + + url, err := tpgresource.ReplaceVars(d, config, "{{ApphubBasePath}}projects/{{project}}/locations/{{location}}/applications/{{application_id}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting Application %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, "Application") + } + + err = ApphubOperationWaitTime( + config, res, project, "Deleting Application", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting Application %q: %#v", d.Id(), res) + return nil +} + +func resourceApphubApplicationImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*transport_tpg.Config) + if err := tpgresource.ParseImportId([]string{ + "^projects/(?P[^/]+)/locations/(?P[^/]+)/applications/(?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/{{location}}/applications/{{application_id}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenApphubApplicationName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationDisplayName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationDescription(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationAttributes(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["criticality"] = + flattenApphubApplicationAttributesCriticality(original["criticality"], d, config) + transformed["environment"] = + flattenApphubApplicationAttributesEnvironment(original["environment"], d, config) + transformed["developer_owners"] = + flattenApphubApplicationAttributesDeveloperOwners(original["developerOwners"], d, config) + transformed["operator_owners"] = + flattenApphubApplicationAttributesOperatorOwners(original["operatorOwners"], d, config) + transformed["business_owners"] = + flattenApphubApplicationAttributesBusinessOwners(original["businessOwners"], d, config) + return []interface{}{transformed} +} +func flattenApphubApplicationAttributesCriticality(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["type"] = + flattenApphubApplicationAttributesCriticalityType(original["type"], d, config) + return []interface{}{transformed} +} +func flattenApphubApplicationAttributesCriticalityType(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationAttributesEnvironment(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["type"] = + flattenApphubApplicationAttributesEnvironmentType(original["type"], d, config) + return []interface{}{transformed} +} +func flattenApphubApplicationAttributesEnvironmentType(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationAttributesDeveloperOwners(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{}{ + "display_name": flattenApphubApplicationAttributesDeveloperOwnersDisplayName(original["displayName"], d, config), + "email": flattenApphubApplicationAttributesDeveloperOwnersEmail(original["email"], d, config), + }) + } + return transformed +} +func flattenApphubApplicationAttributesDeveloperOwnersDisplayName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationAttributesDeveloperOwnersEmail(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationAttributesOperatorOwners(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{}{ + "display_name": flattenApphubApplicationAttributesOperatorOwnersDisplayName(original["displayName"], d, config), + "email": flattenApphubApplicationAttributesOperatorOwnersEmail(original["email"], d, config), + }) + } + return transformed +} +func flattenApphubApplicationAttributesOperatorOwnersDisplayName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationAttributesOperatorOwnersEmail(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationAttributesBusinessOwners(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{}{ + "display_name": flattenApphubApplicationAttributesBusinessOwnersDisplayName(original["displayName"], d, config), + "email": flattenApphubApplicationAttributesBusinessOwnersEmail(original["email"], d, config), + }) + } + return transformed +} +func flattenApphubApplicationAttributesBusinessOwnersDisplayName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationAttributesBusinessOwnersEmail(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationCreateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationUpdateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationScope(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["type"] = + flattenApphubApplicationScopeType(original["type"], d, config) + return []interface{}{transformed} +} +func flattenApphubApplicationScopeType(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationUid(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenApphubApplicationState(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandApphubApplicationDisplayName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandApphubApplicationDescription(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandApphubApplicationAttributes(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{}) + + transformedCriticality, err := expandApphubApplicationAttributesCriticality(original["criticality"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedCriticality); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["criticality"] = transformedCriticality + } + + transformedEnvironment, err := expandApphubApplicationAttributesEnvironment(original["environment"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedEnvironment); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["environment"] = transformedEnvironment + } + + transformedDeveloperOwners, err := expandApphubApplicationAttributesDeveloperOwners(original["developer_owners"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedDeveloperOwners); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["developerOwners"] = transformedDeveloperOwners + } + + transformedOperatorOwners, err := expandApphubApplicationAttributesOperatorOwners(original["operator_owners"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedOperatorOwners); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["operatorOwners"] = transformedOperatorOwners + } + + transformedBusinessOwners, err := expandApphubApplicationAttributesBusinessOwners(original["business_owners"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedBusinessOwners); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["businessOwners"] = transformedBusinessOwners + } + + return transformed, nil +} + +func expandApphubApplicationAttributesCriticality(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{}) + + transformedType, err := expandApphubApplicationAttributesCriticalityType(original["type"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedType); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["type"] = transformedType + } + + return transformed, nil +} + +func expandApphubApplicationAttributesCriticalityType(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandApphubApplicationAttributesEnvironment(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{}) + + transformedType, err := expandApphubApplicationAttributesEnvironmentType(original["type"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedType); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["type"] = transformedType + } + + return transformed, nil +} + +func expandApphubApplicationAttributesEnvironmentType(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandApphubApplicationAttributesDeveloperOwners(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{}) + + transformedDisplayName, err := expandApphubApplicationAttributesDeveloperOwnersDisplayName(original["display_name"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedDisplayName); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["displayName"] = transformedDisplayName + } + + transformedEmail, err := expandApphubApplicationAttributesDeveloperOwnersEmail(original["email"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedEmail); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["email"] = transformedEmail + } + + req = append(req, transformed) + } + return req, nil +} + +func expandApphubApplicationAttributesDeveloperOwnersDisplayName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandApphubApplicationAttributesDeveloperOwnersEmail(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandApphubApplicationAttributesOperatorOwners(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{}) + + transformedDisplayName, err := expandApphubApplicationAttributesOperatorOwnersDisplayName(original["display_name"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedDisplayName); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["displayName"] = transformedDisplayName + } + + transformedEmail, err := expandApphubApplicationAttributesOperatorOwnersEmail(original["email"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedEmail); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["email"] = transformedEmail + } + + req = append(req, transformed) + } + return req, nil +} + +func expandApphubApplicationAttributesOperatorOwnersDisplayName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandApphubApplicationAttributesOperatorOwnersEmail(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandApphubApplicationAttributesBusinessOwners(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{}) + + transformedDisplayName, err := expandApphubApplicationAttributesBusinessOwnersDisplayName(original["display_name"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedDisplayName); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["displayName"] = transformedDisplayName + } + + transformedEmail, err := expandApphubApplicationAttributesBusinessOwnersEmail(original["email"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedEmail); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["email"] = transformedEmail + } + + req = append(req, transformed) + } + return req, nil +} + +func expandApphubApplicationAttributesBusinessOwnersDisplayName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandApphubApplicationAttributesBusinessOwnersEmail(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandApphubApplicationScope(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{}) + + transformedType, err := expandApphubApplicationScopeType(original["type"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedType); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["type"] = transformedType + } + + return transformed, nil +} + +func expandApphubApplicationScopeType(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} diff --git a/google/services/apphub/resource_apphub_application_generated_test.go b/google/services/apphub/resource_apphub_application_generated_test.go new file mode 100644 index 00000000000..bf90441dc41 --- /dev/null +++ b/google/services/apphub/resource_apphub_application_generated_test.go @@ -0,0 +1,166 @@ +// 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 apphub_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" + + "github.com/hashicorp/terraform-provider-google/google/acctest" + "github.com/hashicorp/terraform-provider-google/google/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport" +) + +func TestAccApphubApplication_applicationBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckApphubApplicationDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccApphubApplication_applicationBasicExample(context), + }, + { + ResourceName: "google_apphub_application.example", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "application_id"}, + }, + }, + }) +} + +func testAccApphubApplication_applicationBasicExample(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_apphub_application" "example" { + location = "us-east1" + application_id = "tf-test-example-application%{random_suffix}" + scope { + type = "REGIONAL" + } +} +`, context) +} + +func TestAccApphubApplication_applicationFullExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckApphubApplicationDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccApphubApplication_applicationFullExample(context), + }, + { + ResourceName: "google_apphub_application.example2", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "application_id"}, + }, + }, + }) +} + +func testAccApphubApplication_applicationFullExample(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_apphub_application" "example2" { + location = "us-east1" + application_id = "tf-test-example-application%{random_suffix}" + display_name = "Application Full%{random_suffix}" + scope { + type = "REGIONAL" + } + description = "Application for testing%{random_suffix}" + attributes { + environment { + type = "STAGING" + } + criticality { + type = "MISSION_CRITICAL" + } + business_owners { + display_name = "Alice%{random_suffix}" + email = "alice@google.com%{random_suffix}" + } + developer_owners { + display_name = "Bob%{random_suffix}" + email = "bob@google.com%{random_suffix}" + } + operator_owners { + display_name = "Charlie%{random_suffix}" + email = "charlie@google.com%{random_suffix}" + } + } +} +`, context) +} + +func testAccCheckApphubApplicationDestroyProducer(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_apphub_application" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := acctest.GoogleProviderConfig(t) + + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{ApphubBasePath}}projects/{{project}}/locations/{{location}}/applications/{{application_id}}") + 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("ApphubApplication still exists at %s", url) + } + } + + return nil + } +} diff --git a/google/services/apphub/resource_apphub_application_sweeper.go b/google/services/apphub/resource_apphub_application_sweeper.go new file mode 100644 index 00000000000..3281d31b8b8 --- /dev/null +++ b/google/services/apphub/resource_apphub_application_sweeper.go @@ -0,0 +1,143 @@ +// 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 apphub + +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("ApphubApplication", testSweepApphubApplication) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepApphubApplication(region string) error { + resourceName := "ApphubApplication" + 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://apphub.googleapis.com/v1/projects/{{project}}/locations/{{location}}/applications", "?")[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["applications"] + 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{}) + var name string + // Id detected in the delete URL, attempt to use id. + if obj["id"] != nil { + name = tpgresource.GetResourceNameFromSelfLink(obj["id"].(string)) + } else if obj["name"] != nil { + name = tpgresource.GetResourceNameFromSelfLink(obj["name"].(string)) + } else { + log.Printf("[INFO][SWEEPER_LOG] %s resource name and id were nil", resourceName) + return nil + } + // Skip resources that shouldn't be sweeped + if !sweeper.IsSweepableTestResource(name) { + nonPrefixCount++ + continue + } + + deleteTemplate := "https://apphub.googleapis.com/v1/projects/{{project}}/locations/{{location}}/applications/{{application_id}}" + 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/apphub/resource_apphub_application_test.go b/google/services/apphub/resource_apphub_application_test.go new file mode 100644 index 00000000000..f4de19d6ebd --- /dev/null +++ b/google/services/apphub/resource_apphub_application_test.go @@ -0,0 +1,212 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 +package apphub_test + +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + + "github.com/hashicorp/terraform-provider-google/google/acctest" +) + +func TestAccApphubApplication_applicationUpdateFull(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "random_suffix": acctest.RandString(t, 10), + } + + acctest.VcrTest(t, resource.TestCase{ + PreCheck: func() { acctest.AccTestPreCheck(t) }, + ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories(t), + CheckDestroy: testAccCheckApphubApplicationDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccApphubApplication_applicationFullExample(context), + }, + { + ResourceName: "google_apphub_application.example2", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "application_id"}, + }, + { + Config: testAccApphubApplication_applicationUpdateDisplayName(context), + }, + { + ResourceName: "google_apphub_application.example2", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "application_id"}, + }, + { + Config: testAccApphubApplication_applicationUpdateEnvironment(context), + }, + { + ResourceName: "google_apphub_application.example2", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "application_id"}, + }, + { + Config: testAccApphubApplication_applicationUpdateCriticality(context), + }, + { + ResourceName: "google_apphub_application.example2", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "application_id"}, + }, + { + Config: testAccApphubApplication_applicationUpdateOwners(context), + }, + { + ResourceName: "google_apphub_application.example2", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"location", "application_id"}, + }, + }, + }) +} + +func testAccApphubApplication_applicationUpdateDisplayName(context map[string]interface{}) string { + return acctest.Nprintf(` + +resource "google_apphub_application" "example2" { + location = "us-east1" + application_id = "tf-test-example-application%{random_suffix}" + display_name = "Application Full New%{random_suffix}" + scope { + type = "REGIONAL" + } + attributes { + environment { + type = "STAGING" + } + criticality { + type = "MISSION_CRITICAL" + } + business_owners { + display_name = "Alice%{random_suffix}" + email = "alice@google.com%{random_suffix}" + } + developer_owners { + display_name = "Bob%{random_suffix}" + email = "bob@google.com%{random_suffix}" + } + operator_owners { + display_name = "Charlie%{random_suffix}" + email = "charlie@google.com%{random_suffix}" + } + } +} +`, context) +} + +func testAccApphubApplication_applicationUpdateEnvironment(context map[string]interface{}) string { + return acctest.Nprintf(` + +resource "google_apphub_application" "example2" { + location = "us-east1" + application_id = "tf-test-example-application%{random_suffix}" + display_name = "Application Full New%{random_suffix}" + scope { + type = "REGIONAL" + } + attributes { + environment { + type = "TEST" + } + criticality { + type = "MISSION_CRITICAL" + } + business_owners { + display_name = "Alice%{random_suffix}" + email = "alice@google.com%{random_suffix}" + } + developer_owners { + display_name = "Bob%{random_suffix}" + email = "bob@google.com%{random_suffix}" + } + operator_owners { + display_name = "Charlie%{random_suffix}" + email = "charlie@google.com%{random_suffix}" + } + } +} +`, context) +} + +func testAccApphubApplication_applicationUpdateCriticality(context map[string]interface{}) string { + return acctest.Nprintf(` + +resource "google_apphub_application" "example2" { + location = "us-east1" + application_id = "tf-test-example-application%{random_suffix}" + display_name = "Application Full New%{random_suffix}" + scope { + type = "REGIONAL" + } + attributes { + environment { + type = "TEST" + } + criticality { + type = "MEDIUM" + } + business_owners { + display_name = "Alice%{random_suffix}" + email = "alice@google.com%{random_suffix}" + } + developer_owners { + display_name = "Bob%{random_suffix}" + email = "bob@google.com%{random_suffix}" + } + operator_owners { + display_name = "Charlie%{random_suffix}" + email = "charlie@google.com%{random_suffix}" + } + } +} +`, context) +} + +func testAccApphubApplication_applicationUpdateOwners(context map[string]interface{}) string { + return acctest.Nprintf(` + +resource "google_apphub_application" "example2" { + location = "us-east1" + application_id = "tf-test-example-application%{random_suffix}" + display_name = "Application Full New%{random_suffix}" + scope { + type = "REGIONAL" + } + attributes { + environment { + type = "TEST" + } + criticality { + type = "MEDIUM" + } + business_owners { + display_name = "Alice%{random_suffix}" + email = "alice@google.com%{random_suffix}" + } + developer_owners { + display_name = "Bob%{random_suffix}" + email = "bob@google.com%{random_suffix}" + } + developer_owners { + display_name = "Derek%{random_suffix}" + email = "derek@google.com%{random_suffix}" + } + operator_owners { + display_name = "Charlie%{random_suffix}" + email = "charlie@google.com%{random_suffix}" + } + } +} +`, context) +} diff --git a/google/sweeper/gcp_sweeper_test.go b/google/sweeper/gcp_sweeper_test.go index 0b40be0f0f2..a711d551968 100644 --- a/google/sweeper/gcp_sweeper_test.go +++ b/google/sweeper/gcp_sweeper_test.go @@ -13,6 +13,7 @@ import ( _ "github.com/hashicorp/terraform-provider-google/google/services/alloydb" _ "github.com/hashicorp/terraform-provider-google/google/services/apigee" _ "github.com/hashicorp/terraform-provider-google/google/services/appengine" + _ "github.com/hashicorp/terraform-provider-google/google/services/apphub" _ "github.com/hashicorp/terraform-provider-google/google/services/artifactregistry" _ "github.com/hashicorp/terraform-provider-google/google/services/beyondcorp" _ "github.com/hashicorp/terraform-provider-google/google/services/biglake" diff --git a/google/transport/config.go b/google/transport/config.go index 53079ebaa22..6e8732cbdeb 100644 --- a/google/transport/config.go +++ b/google/transport/config.go @@ -193,6 +193,7 @@ type Config struct { AlloydbBasePath string ApigeeBasePath string AppEngineBasePath string + ApphubBasePath string ArtifactRegistryBasePath string BeyondcorpBasePath string BiglakeBasePath string @@ -326,6 +327,7 @@ const ActiveDirectoryBasePathKey = "ActiveDirectory" const AlloydbBasePathKey = "Alloydb" const ApigeeBasePathKey = "Apigee" const AppEngineBasePathKey = "AppEngine" +const ApphubBasePathKey = "Apphub" const ArtifactRegistryBasePathKey = "ArtifactRegistry" const BeyondcorpBasePathKey = "Beyondcorp" const BiglakeBasePathKey = "Biglake" @@ -453,6 +455,7 @@ var DefaultBasePaths = map[string]string{ AlloydbBasePathKey: "https://alloydb.googleapis.com/v1/", ApigeeBasePathKey: "https://apigee.googleapis.com/v1/", AppEngineBasePathKey: "https://appengine.googleapis.com/v1/", + ApphubBasePathKey: "https://apphub.googleapis.com/v1/", ArtifactRegistryBasePathKey: "https://artifactregistry.googleapis.com/v1/", BeyondcorpBasePathKey: "https://beyondcorp.googleapis.com/v1/", BiglakeBasePathKey: "https://biglake.googleapis.com/v1/", @@ -675,6 +678,11 @@ func SetEndpointDefaults(d *schema.ResourceData) error { "GOOGLE_APP_ENGINE_CUSTOM_ENDPOINT", }, DefaultBasePaths[AppEngineBasePathKey])) } + if d.Get("apphub_custom_endpoint") == "" { + d.Set("apphub_custom_endpoint", MultiEnvDefault([]string{ + "GOOGLE_APPHUB_CUSTOM_ENDPOINT", + }, DefaultBasePaths[ApphubBasePathKey])) + } if d.Get("artifact_registry_custom_endpoint") == "" { d.Set("artifact_registry_custom_endpoint", MultiEnvDefault([]string{ "GOOGLE_ARTIFACT_REGISTRY_CUSTOM_ENDPOINT", @@ -2071,6 +2079,7 @@ func ConfigureBasePaths(c *Config) { c.AlloydbBasePath = DefaultBasePaths[AlloydbBasePathKey] c.ApigeeBasePath = DefaultBasePaths[ApigeeBasePathKey] c.AppEngineBasePath = DefaultBasePaths[AppEngineBasePathKey] + c.ApphubBasePath = DefaultBasePaths[ApphubBasePathKey] c.ArtifactRegistryBasePath = DefaultBasePaths[ArtifactRegistryBasePathKey] c.BeyondcorpBasePath = DefaultBasePaths[BeyondcorpBasePathKey] c.BiglakeBasePath = DefaultBasePaths[BiglakeBasePathKey] diff --git a/website/docs/r/apphub_application.html.markdown b/website/docs/r/apphub_application.html.markdown new file mode 100644 index 00000000000..48ddde4291b --- /dev/null +++ b/website/docs/r/apphub_application.html.markdown @@ -0,0 +1,269 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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: "App Hub" +description: |- + Application is a functional grouping of Services and Workloads that helps achieve a desired end-to-end business functionality. +--- + +# google\_apphub\_application + +Application is a functional grouping of Services and Workloads that helps achieve a desired end-to-end business functionality. Services and Workloads are owned by the Application. + + + + +## Example Usage - Application Basic + + +```hcl +resource "google_apphub_application" "example" { + location = "us-east1" + application_id = "example-application" + scope { + type = "REGIONAL" + } +} +``` + +## Example Usage - Application Full + + +```hcl +resource "google_apphub_application" "example2" { + location = "us-east1" + application_id = "example-application" + display_name = "Application Full" + scope { + type = "REGIONAL" + } + description = "Application for testing" + attributes { + environment { + type = "STAGING" + } + criticality { + type = "MISSION_CRITICAL" + } + business_owners { + display_name = "Alice" + email = "alice@google.com" + } + developer_owners { + display_name = "Bob" + email = "bob@google.com" + } + operator_owners { + display_name = "Charlie" + email = "charlie@google.com" + } + } +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `scope` - + (Required) + Scope of an application. + Structure is [documented below](#nested_scope). + +* `location` - + (Required) + Part of `parent`. See documentation of `projectsId`. + +* `application_id` - + (Required) + Required. The Application identifier. + + +The `scope` block supports: + +* `type` - + (Required) + Required. Scope Type. + Possible values: + REGIONAL + Possible values are: `REGIONAL`. + +- - - + + +* `display_name` - + (Optional) + Optional. User-defined name for the Application. + +* `description` - + (Optional) + Optional. User-defined description of an Application. + +* `attributes` - + (Optional) + Consumer provided attributes. + Structure is [documented below](#nested_attributes). + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + +The `attributes` block supports: + +* `criticality` - + (Optional) + Criticality of the Application, Service, or Workload + Structure is [documented below](#nested_criticality). + +* `environment` - + (Optional) + Environment of the Application, Service, or Workload + Structure is [documented below](#nested_environment). + +* `developer_owners` - + (Optional) + Optional. Developer team that owns development and coding. + Structure is [documented below](#nested_developer_owners). + +* `operator_owners` - + (Optional) + Optional. Operator team that ensures runtime and operations. + Structure is [documented below](#nested_operator_owners). + +* `business_owners` - + (Optional) + Optional. Business team that ensures user needs are met and value is delivered + Structure is [documented below](#nested_business_owners). + + +The `criticality` block supports: + +* `type` - + (Required) + Criticality type. + Possible values are: `MISSION_CRITICAL`, `HIGH`, `MEDIUM`, `LOW`. + +The `environment` block supports: + +* `type` - + (Required) + Environment type. + Possible values are: `PRODUCTION`, `STAGING`, `TEST`, `DEVELOPMENT`. + +The `developer_owners` block supports: + +* `display_name` - + (Optional) + Optional. Contact's name. + +* `email` - + (Required) + Required. Email address of the contacts. + +The `operator_owners` block supports: + +* `display_name` - + (Optional) + Optional. Contact's name. + +* `email` - + (Required) + Required. Email address of the contacts. + +The `business_owners` block supports: + +* `display_name` - + (Optional) + Optional. Contact's name. + +* `email` - + (Required) + Required. Email address of the contacts. + +## 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/{{location}}/applications/{{application_id}}` + +* `name` - + Identifier. The resource name of an Application. Format: + "projects/{host-project-id}/locations/{location}/applications/{application-id}" + +* `create_time` - + Output only. Create time. + +* `update_time` - + Output only. Update time. + +* `uid` - + Output only. A universally unique identifier (in UUID4 format) for the `Application`. + +* `state` - + Output only. Application state. + Possible values: + STATE_UNSPECIFIED + CREATING + ACTIVE + DELETING + + +## 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 + + +Application can be imported using any of these accepted formats: + +* `projects/{{project}}/locations/{{location}}/applications/{{application_id}}` +* `{{project}}/{{location}}/{{application_id}}` +* `{{location}}/{{application_id}}` + + +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import Application using one of the formats above. For example: + +```tf +import { + id = "projects/{{project}}/locations/{{location}}/applications/{{application_id}}" + to = google_apphub_application.default +} +``` + +When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), Application can be imported using one of the formats above. For example: + +``` +$ terraform import google_apphub_application.default projects/{{project}}/locations/{{location}}/applications/{{application_id}} +$ terraform import google_apphub_application.default {{project}}/{{location}}/{{application_id}} +$ terraform import google_apphub_application.default {{location}}/{{application_id}} +``` + +## User Project Overrides + +This resource supports [User Project Overrides](https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference#user_project_override).