diff --git a/.changelog/9822.txt b/.changelog/9822.txt new file mode 100644 index 0000000000..db8509e143 --- /dev/null +++ b/.changelog/9822.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_discovery_engine_search_engine` +``` \ No newline at end of file diff --git a/google-beta/provider/provider_mmv1_resources.go b/google-beta/provider/provider_mmv1_resources.go index 9bdfb8f291..1f8dbf85e1 100644 --- a/google-beta/provider/provider_mmv1_resources.go +++ b/google-beta/provider/provider_mmv1_resources.go @@ -427,9 +427,9 @@ var handwrittenIAMDatasources = map[string]*schema.Resource{ } // Resources -// Generated resources: 430 +// Generated resources: 431 // Generated IAM resources: 255 -// Total generated resources: 685 +// Total generated resources: 686 var generatedResources = map[string]*schema.Resource{ "google_folder_access_approval_settings": accessapproval.ResourceAccessApprovalFolderSettings(), "google_organization_access_approval_settings": accessapproval.ResourceAccessApprovalOrganizationSettings(), @@ -786,6 +786,7 @@ var generatedResources = map[string]*schema.Resource{ "google_dialogflow_cx_webhook": dialogflowcx.ResourceDialogflowCXWebhook(), "google_discovery_engine_chat_engine": discoveryengine.ResourceDiscoveryEngineChatEngine(), "google_discovery_engine_data_store": discoveryengine.ResourceDiscoveryEngineDataStore(), + "google_discovery_engine_search_engine": discoveryengine.ResourceDiscoveryEngineSearchEngine(), "google_dns_managed_zone": dns.ResourceDNSManagedZone(), "google_dns_managed_zone_iam_binding": tpgiamresource.ResourceIamBinding(dns.DNSManagedZoneIamSchema, dns.DNSManagedZoneIamUpdaterProducer, dns.DNSManagedZoneIdParseFunc), "google_dns_managed_zone_iam_member": tpgiamresource.ResourceIamMember(dns.DNSManagedZoneIamSchema, dns.DNSManagedZoneIamUpdaterProducer, dns.DNSManagedZoneIdParseFunc), diff --git a/google-beta/services/discoveryengine/resource_discovery_engine_search_engine.go b/google-beta/services/discoveryengine/resource_discovery_engine_search_engine.go new file mode 100644 index 0000000000..013238f507 --- /dev/null +++ b/google-beta/services/discoveryengine/resource_discovery_engine_search_engine.go @@ -0,0 +1,643 @@ +// 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 discoveryengine + +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-beta/google-beta/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/verify" +) + +func ResourceDiscoveryEngineSearchEngine() *schema.Resource { + return &schema.Resource{ + Create: resourceDiscoveryEngineSearchEngineCreate, + Read: resourceDiscoveryEngineSearchEngineRead, + Update: resourceDiscoveryEngineSearchEngineUpdate, + Delete: resourceDiscoveryEngineSearchEngineDelete, + + Importer: &schema.ResourceImporter{ + State: resourceDiscoveryEngineSearchEngineImport, + }, + + 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{ + "collection_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `The collection ID.`, + }, + "data_store_ids": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + Description: `The data stores associated with this engine. For SOLUTION_TYPE_SEARCH type of engines, they can only associate with at most one data store.`, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + "display_name": { + Type: schema.TypeString, + Required: true, + Description: `Required. The display name of the engine. Should be human readable. UTF-8 encoded string with limit of 1024 characters.`, + }, + "engine_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Unique ID to use for Search Engine App.`, + }, + "location": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + Description: `Location.`, + }, + "search_engine_config": { + Type: schema.TypeList, + Required: true, + Description: `Configurations for a Search Engine.`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "search_add_ons": { + Type: schema.TypeList, + Optional: true, + Description: `The add-on that this search engine enables. Possible values: ["SEARCH_ADD_ON_LLM"]`, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: verify.ValidateEnum([]string{"SEARCH_ADD_ON_LLM"}), + }, + }, + "search_tier": { + Type: schema.TypeString, + Optional: true, + ValidateFunc: verify.ValidateEnum([]string{"SEARCH_TIER_STANDARD", "SEARCH_TIER_ENTERPRISE", ""}), + Description: `The search feature tier of this engine. Defaults to SearchTier.SEARCH_TIER_STANDARD if not specified. Default value: "SEARCH_TIER_STANDARD" Possible values: ["SEARCH_TIER_STANDARD", "SEARCH_TIER_ENTERPRISE"]`, + Default: "SEARCH_TIER_STANDARD", + }, + }, + }, + }, + "common_config": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Description: `Common config spec that specifies the metadata of the engine.`, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "company_name": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + Description: `The name of the company, business or entity that is associated with the engine. Setting this may help improve LLM related features.cd`, + }, + }, + }, + }, + "industry_vertical": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: verify.ValidateEnum([]string{"GENERIC", "MEDIA", ""}), + Description: `The industry vertical that the engine registers. The restriction of the Engine industry vertical is based on DataStore: If unspecified, default to GENERIC. Vertical on Engine has to match vertical of the DataStore liniked to the engine. Default value: "GENERIC" Possible values: ["GENERIC", "MEDIA"]`, + Default: "GENERIC", + }, + "create_time": { + Type: schema.TypeString, + Computed: true, + Description: `Timestamp the Engine was created at.`, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: `The unique full resource name of the search engine. Values are of the format +'projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}'. +This field must be a UTF-8 encoded string with a length limit of 1024 +characters.`, + }, + "update_time": { + Type: schema.TypeString, + Computed: true, + Description: `Timestamp the Engine was last updated.`, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + UseJSONNumber: true, + } +} + +func resourceDiscoveryEngineSearchEngineCreate(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{}) + industryVerticalProp, err := expandDiscoveryEngineSearchEngineIndustryVertical(d.Get("industry_vertical"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("industry_vertical"); !tpgresource.IsEmptyValue(reflect.ValueOf(industryVerticalProp)) && (ok || !reflect.DeepEqual(v, industryVerticalProp)) { + obj["industryVertical"] = industryVerticalProp + } + displayNameProp, err := expandDiscoveryEngineSearchEngineDisplayName(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 + } + dataStoreIdsProp, err := expandDiscoveryEngineSearchEngineDataStoreIds(d.Get("data_store_ids"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("data_store_ids"); !tpgresource.IsEmptyValue(reflect.ValueOf(dataStoreIdsProp)) && (ok || !reflect.DeepEqual(v, dataStoreIdsProp)) { + obj["dataStoreIds"] = dataStoreIdsProp + } + searchEngineConfigProp, err := expandDiscoveryEngineSearchEngineSearchEngineConfig(d.Get("search_engine_config"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("search_engine_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(searchEngineConfigProp)) && (ok || !reflect.DeepEqual(v, searchEngineConfigProp)) { + obj["searchEngineConfig"] = searchEngineConfigProp + } + commonConfigProp, err := expandDiscoveryEngineSearchEngineCommonConfig(d.Get("common_config"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("common_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(commonConfigProp)) && (ok || !reflect.DeepEqual(v, commonConfigProp)) { + obj["commonConfig"] = commonConfigProp + } + + obj, err = resourceDiscoveryEngineSearchEngineEncoder(d, meta, obj) + if err != nil { + return err + } + + url, err := tpgresource.ReplaceVars(d, config, "{{DiscoveryEngineBasePath}}projects/{{project}}/locations/{{location}}/collections/{{collection_id}}/engines?engineId={{engine_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new SearchEngine: %#v", obj) + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for SearchEngine: %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 SearchEngine: %s", err) + } + + // Store the ID now + id, err := tpgresource.ReplaceVars(d, config, "projects/{{project}}/locations/{{location}}/collections/{{collection_id}}/engines/{{engine_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 = DiscoveryEngineOperationWaitTimeWithResponse( + config, res, &opRes, project, "Creating SearchEngine", userAgent, + d.Timeout(schema.TimeoutCreate)) + if err != nil { + // The resource didn't actually create + d.SetId("") + + return fmt.Errorf("Error waiting to create SearchEngine: %s", err) + } + + if err := d.Set("name", flattenDiscoveryEngineSearchEngineName(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}}/collections/{{collection_id}}/engines/{{engine_id}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating SearchEngine %q: %#v", d.Id(), res) + + return resourceDiscoveryEngineSearchEngineRead(d, meta) +} + +func resourceDiscoveryEngineSearchEngineRead(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, "{{DiscoveryEngineBasePath}}projects/{{project}}/locations/{{location}}/collections/{{collection_id}}/engines/{{engine_id}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := tpgresource.GetProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for SearchEngine: %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("DiscoveryEngineSearchEngine %q", d.Id())) + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading SearchEngine: %s", err) + } + + if err := d.Set("name", flattenDiscoveryEngineSearchEngineName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading SearchEngine: %s", err) + } + if err := d.Set("industry_vertical", flattenDiscoveryEngineSearchEngineIndustryVertical(res["industryVertical"], d, config)); err != nil { + return fmt.Errorf("Error reading SearchEngine: %s", err) + } + if err := d.Set("display_name", flattenDiscoveryEngineSearchEngineDisplayName(res["displayName"], d, config)); err != nil { + return fmt.Errorf("Error reading SearchEngine: %s", err) + } + if err := d.Set("data_store_ids", flattenDiscoveryEngineSearchEngineDataStoreIds(res["dataStoreIds"], d, config)); err != nil { + return fmt.Errorf("Error reading SearchEngine: %s", err) + } + if err := d.Set("create_time", flattenDiscoveryEngineSearchEngineCreateTime(res["createTime"], d, config)); err != nil { + return fmt.Errorf("Error reading SearchEngine: %s", err) + } + if err := d.Set("update_time", flattenDiscoveryEngineSearchEngineUpdateTime(res["updateTime"], d, config)); err != nil { + return fmt.Errorf("Error reading SearchEngine: %s", err) + } + if err := d.Set("search_engine_config", flattenDiscoveryEngineSearchEngineSearchEngineConfig(res["searchEngineConfig"], d, config)); err != nil { + return fmt.Errorf("Error reading SearchEngine: %s", err) + } + if err := d.Set("common_config", flattenDiscoveryEngineSearchEngineCommonConfig(res["commonConfig"], d, config)); err != nil { + return fmt.Errorf("Error reading SearchEngine: %s", err) + } + + return nil +} + +func resourceDiscoveryEngineSearchEngineUpdate(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 SearchEngine: %s", err) + } + billingProject = project + + obj := make(map[string]interface{}) + displayNameProp, err := expandDiscoveryEngineSearchEngineDisplayName(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 + } + searchEngineConfigProp, err := expandDiscoveryEngineSearchEngineSearchEngineConfig(d.Get("search_engine_config"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("search_engine_config"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, searchEngineConfigProp)) { + obj["searchEngineConfig"] = searchEngineConfigProp + } + + obj, err = resourceDiscoveryEngineSearchEngineEncoder(d, meta, obj) + if err != nil { + return err + } + + url, err := tpgresource.ReplaceVars(d, config, "{{DiscoveryEngineBasePath}}projects/{{project}}/locations/{{location}}/collections/{{collection_id}}/engines/{{engine_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating SearchEngine %q: %#v", d.Id(), obj) + updateMask := []string{} + + if d.HasChange("display_name") { + updateMask = append(updateMask, "displayName") + } + + if d.HasChange("search_engine_config") { + updateMask = append(updateMask, "searchEngineConfig") + } + // 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 SearchEngine %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating SearchEngine %q: %#v", d.Id(), res) + } + + } + + return resourceDiscoveryEngineSearchEngineRead(d, meta) +} + +func resourceDiscoveryEngineSearchEngineDelete(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 SearchEngine: %s", err) + } + billingProject = project + + url, err := tpgresource.ReplaceVars(d, config, "{{DiscoveryEngineBasePath}}projects/{{project}}/locations/{{location}}/collections/{{collection_id}}/engines/{{engine_id}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting SearchEngine %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, "SearchEngine") + } + + err = DiscoveryEngineOperationWaitTime( + config, res, project, "Deleting SearchEngine", userAgent, + d.Timeout(schema.TimeoutDelete)) + + if err != nil { + return err + } + + log.Printf("[DEBUG] Finished deleting SearchEngine %q: %#v", d.Id(), res) + return nil +} + +func resourceDiscoveryEngineSearchEngineImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + config := meta.(*transport_tpg.Config) + if err := tpgresource.ParseImportId([]string{ + "^projects/(?P[^/]+)/locations/(?P[^/]+)/collections/(?P[^/]+)/engines/(?P[^/]+)$", + "^(?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/{{location}}/collections/{{collection_id}}/engines/{{engine_id}}") + if err != nil { + return nil, fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + return []*schema.ResourceData{d}, nil +} + +func flattenDiscoveryEngineSearchEngineName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDiscoveryEngineSearchEngineIndustryVertical(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDiscoveryEngineSearchEngineDisplayName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDiscoveryEngineSearchEngineDataStoreIds(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDiscoveryEngineSearchEngineCreateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDiscoveryEngineSearchEngineUpdateTime(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDiscoveryEngineSearchEngineSearchEngineConfig(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["search_tier"] = + flattenDiscoveryEngineSearchEngineSearchEngineConfigSearchTier(original["searchTier"], d, config) + transformed["search_add_ons"] = + flattenDiscoveryEngineSearchEngineSearchEngineConfigSearchAddOns(original["searchAddOns"], d, config) + return []interface{}{transformed} +} +func flattenDiscoveryEngineSearchEngineSearchEngineConfigSearchTier(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDiscoveryEngineSearchEngineSearchEngineConfigSearchAddOns(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func flattenDiscoveryEngineSearchEngineCommonConfig(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["company_name"] = + flattenDiscoveryEngineSearchEngineCommonConfigCompanyName(original["companyName"], d, config) + return []interface{}{transformed} +} +func flattenDiscoveryEngineSearchEngineCommonConfigCompanyName(v interface{}, d *schema.ResourceData, config *transport_tpg.Config) interface{} { + return v +} + +func expandDiscoveryEngineSearchEngineIndustryVertical(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDiscoveryEngineSearchEngineDisplayName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDiscoveryEngineSearchEngineDataStoreIds(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDiscoveryEngineSearchEngineSearchEngineConfig(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{}) + + transformedSearchTier, err := expandDiscoveryEngineSearchEngineSearchEngineConfigSearchTier(original["search_tier"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedSearchTier); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["searchTier"] = transformedSearchTier + } + + transformedSearchAddOns, err := expandDiscoveryEngineSearchEngineSearchEngineConfigSearchAddOns(original["search_add_ons"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedSearchAddOns); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["searchAddOns"] = transformedSearchAddOns + } + + return transformed, nil +} + +func expandDiscoveryEngineSearchEngineSearchEngineConfigSearchTier(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDiscoveryEngineSearchEngineSearchEngineConfigSearchAddOns(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func expandDiscoveryEngineSearchEngineCommonConfig(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{}) + + transformedCompanyName, err := expandDiscoveryEngineSearchEngineCommonConfigCompanyName(original["company_name"], d, config) + if err != nil { + return nil, err + } else if val := reflect.ValueOf(transformedCompanyName); val.IsValid() && !tpgresource.IsEmptyValue(val) { + transformed["companyName"] = transformedCompanyName + } + + return transformed, nil +} + +func expandDiscoveryEngineSearchEngineCommonConfigCompanyName(v interface{}, d tpgresource.TerraformResourceData, config *transport_tpg.Config) (interface{}, error) { + return v, nil +} + +func resourceDiscoveryEngineSearchEngineEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) { + // hard code solutionType to "SOLUTION_TYPE_SEARCH" for search engine resource + obj["solutionType"] = "SOLUTION_TYPE_SEARCH" + return obj, nil +} diff --git a/google-beta/services/discoveryengine/resource_discovery_engine_search_engine_generated_test.go b/google-beta/services/discoveryengine/resource_discovery_engine_search_engine_generated_test.go new file mode 100644 index 0000000000..8483a5d0d2 --- /dev/null +++ b/google-beta/services/discoveryengine/resource_discovery_engine_search_engine_generated_test.go @@ -0,0 +1,118 @@ +// 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 discoveryengine_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-beta/google-beta/acctest" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" +) + +func TestAccDiscoveryEngineSearchEngine_discoveryengineSearchengineBasicExample(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: testAccCheckDiscoveryEngineSearchEngineDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccDiscoveryEngineSearchEngine_discoveryengineSearchengineBasicExample(context), + }, + { + ResourceName: "google_discovery_engine_search_engine.basic", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"engine_id", "collection_id", "location"}, + }, + }, + }) +} + +func testAccDiscoveryEngineSearchEngine_discoveryengineSearchengineBasicExample(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_discovery_engine_data_store" "basic" { + location = "global" + data_store_id = "tf-test-example-datastore-id%{random_suffix}" + display_name = "tf-test-structured-datastore" + industry_vertical = "GENERIC" + content_config = "NO_CONTENT" + solution_types = ["SOLUTION_TYPE_SEARCH"] + create_advanced_site_search = false +} +resource "google_discovery_engine_search_engine" "basic" { + engine_id = "tf-test-example-engine-id%{random_suffix}" + collection_id = "default_collection" + location = google_discovery_engine_data_store.basic.location + display_name = "Example Display Name" + data_store_ids = [google_discovery_engine_data_store.basic.data_store_id] + search_engine_config { + } +} +`, context) +} + +func testAccCheckDiscoveryEngineSearchEngineDestroyProducer(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_discovery_engine_search_engine" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := acctest.GoogleProviderConfig(t) + + url, err := tpgresource.ReplaceVarsForTest(config, rs, "{{DiscoveryEngineBasePath}}projects/{{project}}/locations/{{location}}/collections/{{collection_id}}/engines/{{engine_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("DiscoveryEngineSearchEngine still exists at %s", url) + } + } + + return nil + } +} diff --git a/google-beta/services/discoveryengine/resource_discovery_engine_search_engine_sweeper.go b/google-beta/services/discoveryengine/resource_discovery_engine_search_engine_sweeper.go new file mode 100644 index 0000000000..565fac5f70 --- /dev/null +++ b/google-beta/services/discoveryengine/resource_discovery_engine_search_engine_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 discoveryengine + +import ( + "context" + "log" + "strings" + "testing" + + "github.com/hashicorp/terraform-provider-google-beta/google-beta/envvar" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/sweeper" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource" + transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport" +) + +func init() { + sweeper.AddTestSweepers("DiscoveryEngineSearchEngine", testSweepDiscoveryEngineSearchEngine) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepDiscoveryEngineSearchEngine(region string) error { + resourceName := "DiscoveryEngineSearchEngine" + 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://{{location}}-discoveryengine.googleapis.com/v1/projects/{{project}}/locations/{{location}}/collections/{{collection_id}}/engines/{{engine_id}}", "?")[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["searchEngines"] + 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://{{location}}-discoveryengine.googleapis.com/v1/projects/{{project}}/locations/{{location}}/collections/{{collection_id}}/engines/{{engine_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-beta/services/discoveryengine/resource_discovery_engine_search_engine_test.go b/google-beta/services/discoveryengine/resource_discovery_engine_search_engine_test.go new file mode 100644 index 0000000000..edf97c9d8a --- /dev/null +++ b/google-beta/services/discoveryengine/resource_discovery_engine_search_engine_test.go @@ -0,0 +1,103 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 +package discoveryengine_test + +import ( + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-provider-google-beta/google-beta/acctest" + "testing" +) + +func TestAccDiscoveryEngineSearchEngine_discoveryengineSearchengineBasicExample_update(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: testAccCheckDiscoveryEngineSearchEngineDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccDiscoveryEngineSearchEngine_discoveryengineSearchengineBasicExample_basic(context), + }, + { + ResourceName: "google_discovery_engine_search_engine.basic", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"engine_id", "collection_id", "location"}, + }, + { + Config: testAccDiscoveryEngineSearchEngine_discoveryengineSearchengineBasicExample_update(context), + }, + { + ResourceName: "google_discovery_engine_search_engine.basic", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"engine_id", "collection_id", "location"}, + }, + }, + }) +} + +func testAccDiscoveryEngineSearchEngine_discoveryengineSearchengineBasicExample_basic(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_discovery_engine_data_store" "basic" { + location = "global" + data_store_id = "tf-test-example-datastore%{random_suffix}" + display_name = "tf-test-structured-datastore" + industry_vertical = "GENERIC" + content_config = "NO_CONTENT" + solution_types = ["SOLUTION_TYPE_SEARCH"] + create_advanced_site_search = false + } +resource "google_discovery_engine_search_engine" "basic" { + engine_id = "tf-test-example-engine-id%{random_suffix}" + collection_id = "default_collection" + location = google_discovery_engine_data_store.basic.location + display_name = "Example Display Name" + data_store_ids = [google_discovery_engine_data_store.basic.data_store_id] + industry_vertical = google_discovery_engine_data_store.basic.industry_vertical + common_config { + company_name = "Example Company Name" + } + search_engine_config { + search_tier = "SEARCH_TIER_ENTERPRISE" + search_add_ons = ["SEARCH_ADD_ON_LLM"] + } +} +`, context) +} + +func testAccDiscoveryEngineSearchEngine_discoveryengineSearchengineBasicExample_update(context map[string]interface{}) string { + return acctest.Nprintf(` +resource "google_discovery_engine_data_store" "basic" { + location = "global" + data_store_id = "tf-test-example-datastore%{random_suffix}" + display_name = "tf-test-structured-datastore" + industry_vertical = "GENERIC" + content_config = "NO_CONTENT" + solution_types = ["SOLUTION_TYPE_SEARCH"] + create_advanced_site_search = false + } +resource "google_discovery_engine_search_engine" "basic" { + engine_id = "tf-test-example-engine-id%{random_suffix}" + collection_id = "default_collection" + location = google_discovery_engine_data_store.basic.location + display_name = "Updated Example Display Name" + data_store_ids = [google_discovery_engine_data_store.basic.data_store_id] + industry_vertical = google_discovery_engine_data_store.basic.industry_vertical + common_config { + company_name = "Updated Example Company Name" + } + search_engine_config { + search_tier = "SEARCH_TIER_STANDARD" + search_add_ons = ["SEARCH_ADD_ON_LLM"] + } +} +`, context) +} diff --git a/website/docs/r/discovery_engine_search_engine.html.markdown b/website/docs/r/discovery_engine_search_engine.html.markdown new file mode 100644 index 0000000000..56c4186598 --- /dev/null +++ b/website/docs/r/discovery_engine_search_engine.html.markdown @@ -0,0 +1,185 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** 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: "Discovery Engine" +description: |- + Vertex AI Search and Conversation can be used to create a search engine or a chat application by connecting it with a datastore +--- + +# google\_discovery\_engine\_search\_engine + +Vertex AI Search and Conversation can be used to create a search engine or a chat application by connecting it with a datastore + + +To get more information about SearchEngine, see: + +* [API documentation](https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1/projects.locations.collections.engines) +* How-to Guides + * [Create a Search Engine](https://cloud.google.com/generative-ai-app-builder/docs/create-engine-es) + + +## Example Usage - Discoveryengine Searchengine Basic + + +```hcl +resource "google_discovery_engine_data_store" "basic" { + location = "global" + data_store_id = "example-datastore-id" + display_name = "tf-test-structured-datastore" + industry_vertical = "GENERIC" + content_config = "NO_CONTENT" + solution_types = ["SOLUTION_TYPE_SEARCH"] + create_advanced_site_search = false +} +resource "google_discovery_engine_search_engine" "basic" { + engine_id = "example-engine-id" + collection_id = "default_collection" + location = google_discovery_engine_data_store.basic.location + display_name = "Example Display Name" + data_store_ids = [google_discovery_engine_data_store.basic.data_store_id] + search_engine_config { + } +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `display_name` - + (Required) + Required. The display name of the engine. Should be human readable. UTF-8 encoded string with limit of 1024 characters. + +* `data_store_ids` - + (Required) + The data stores associated with this engine. For SOLUTION_TYPE_SEARCH type of engines, they can only associate with at most one data store. + +* `search_engine_config` - + (Required) + Configurations for a Search Engine. + Structure is [documented below](#nested_search_engine_config). + +* `engine_id` - + (Required) + Unique ID to use for Search Engine App. + +* `collection_id` - + (Required) + The collection ID. + +* `location` - + (Required) + Location. + + +The `search_engine_config` block supports: + +* `search_tier` - + (Optional) + The search feature tier of this engine. Defaults to SearchTier.SEARCH_TIER_STANDARD if not specified. + Default value is `SEARCH_TIER_STANDARD`. + Possible values are: `SEARCH_TIER_STANDARD`, `SEARCH_TIER_ENTERPRISE`. + +* `search_add_ons` - + (Optional) + The add-on that this search engine enables. + Each value may be one of: `SEARCH_ADD_ON_LLM`. + +- - - + + +* `industry_vertical` - + (Optional) + The industry vertical that the engine registers. The restriction of the Engine industry vertical is based on DataStore: If unspecified, default to GENERIC. Vertical on Engine has to match vertical of the DataStore liniked to the engine. + Default value is `GENERIC`. + Possible values are: `GENERIC`, `MEDIA`. + +* `common_config` - + (Optional) + Common config spec that specifies the metadata of the engine. + Structure is [documented below](#nested_common_config). + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + +The `common_config` block supports: + +* `company_name` - + (Optional) + The name of the company, business or entity that is associated with the engine. Setting this may help improve LLM related features.cd + +## 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}}/collections/{{collection_id}}/engines/{{engine_id}}` + +* `name` - + The unique full resource name of the search engine. Values are of the format + `projects/{project}/locations/{location}/collections/{collection_id}/engines/{engine_id}`. + This field must be a UTF-8 encoded string with a length limit of 1024 + characters. + +* `create_time` - + Timestamp the Engine was created at. + +* `update_time` - + Timestamp the Engine was last updated. + + +## 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 + + +SearchEngine can be imported using any of these accepted formats: + +* `projects/{{project}}/locations/{{location}}/collections/{{collection_id}}/engines/{{engine_id}}` +* `{{project}}/{{location}}/{{collection_id}}/{{engine_id}}` +* `{{location}}/{{collection_id}}/{{engine_id}}` + + +In Terraform v1.5.0 and later, use an [`import` block](https://developer.hashicorp.com/terraform/language/import) to import SearchEngine using one of the formats above. For example: + +```tf +import { + id = "projects/{{project}}/locations/{{location}}/collections/{{collection_id}}/engines/{{engine_id}}" + to = google_discovery_engine_search_engine.default +} +``` + +When using the [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import), SearchEngine can be imported using one of the formats above. For example: + +``` +$ terraform import google_discovery_engine_search_engine.default projects/{{project}}/locations/{{location}}/collections/{{collection_id}}/engines/{{engine_id}} +$ terraform import google_discovery_engine_search_engine.default {{project}}/{{location}}/{{collection_id}}/{{engine_id}} +$ terraform import google_discovery_engine_search_engine.default {{location}}/{{collection_id}}/{{engine_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).