From c0b82706ee9fe1b742b3fab9f183b183c818d435 Mon Sep 17 00:00:00 2001 From: The Magician Date: Thu, 3 Dec 2020 16:02:00 -0800 Subject: [PATCH] Add resource document to google_firestore (#4279) (#7932) * Add resource firestore document * fix spelling mistake * update tests and api according to comments. * update project reference to be firestore project * go fmt * format fix * ran gofmt manually * comment the purpose of the decoder Signed-off-by: Modular Magician --- .changelog/4279.txt | 3 + google/provider.go | 5 +- google/resource_firestore_document.go | 385 ++++++++++++++++++ ...ource_firestore_document_generated_test.go | 145 +++++++ ...esource_firestore_document_sweeper_test.go | 124 ++++++ google/resource_firestore_document_test.go | 62 +++ .../docs/r/firestore_document.html.markdown | 157 +++++++ website/google.erb | 4 + 8 files changed, 883 insertions(+), 2 deletions(-) create mode 100644 .changelog/4279.txt create mode 100644 google/resource_firestore_document.go create mode 100644 google/resource_firestore_document_generated_test.go create mode 100644 google/resource_firestore_document_sweeper_test.go create mode 100644 google/resource_firestore_document_test.go create mode 100644 website/docs/r/firestore_document.html.markdown diff --git a/.changelog/4279.txt b/.changelog/4279.txt new file mode 100644 index 00000000000..cbab4e84823 --- /dev/null +++ b/.changelog/4279.txt @@ -0,0 +1,3 @@ +```release-note:new-resource +`google_firestore_document` +``` diff --git a/google/provider.go b/google/provider.go index b0415f43e02..08173ddc084 100644 --- a/google/provider.go +++ b/google/provider.go @@ -670,9 +670,9 @@ func Provider() *schema.Provider { return provider } -// Generated resources: 170 +// Generated resources: 171 // Generated IAM resources: 72 -// Total generated resources: 242 +// Total generated resources: 243 func ResourceMap() map[string]*schema.Resource { resourceMap, _ := ResourceMapWithErrors() return resourceMap @@ -829,6 +829,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { "google_dns_policy": resourceDNSPolicy(), "google_filestore_instance": resourceFilestoreInstance(), "google_firestore_index": resourceFirestoreIndex(), + "google_firestore_document": resourceFirestoreDocument(), "google_game_services_realm": resourceGameServicesRealm(), "google_game_services_game_server_cluster": resourceGameServicesGameServerCluster(), "google_game_services_game_server_deployment": resourceGameServicesGameServerDeployment(), diff --git a/google/resource_firestore_document.go b/google/resource_firestore_document.go new file mode 100644 index 00000000000..e61796a2269 --- /dev/null +++ b/google/resource_firestore_document.go @@ -0,0 +1,385 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "encoding/json" + "fmt" + "log" + "reflect" + "regexp" + "time" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/structure" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" +) + +func resourceFirestoreDocument() *schema.Resource { + return &schema.Resource{ + Create: resourceFirestoreDocumentCreate, + Read: resourceFirestoreDocumentRead, + Update: resourceFirestoreDocumentUpdate, + Delete: resourceFirestoreDocumentDelete, + + Importer: &schema.ResourceImporter{ + State: resourceFirestoreDocumentImport, + }, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(4 * time.Minute), + Update: schema.DefaultTimeout(4 * time.Minute), + Delete: schema.DefaultTimeout(4 * time.Minute), + }, + + Schema: map[string]*schema.Schema{ + "collection": { + Type: schema.TypeString, + Required: true, + Description: `The collection ID, relative to database. For example: chatrooms or chatrooms/my-document/private-messages.`, + }, + "document_id": { + Type: schema.TypeString, + Required: true, + Description: `The client-assigned document ID to use for this document during creation.`, + }, + "fields": { + Type: schema.TypeString, + Required: true, + ValidateFunc: validation.StringIsJSON, + StateFunc: func(v interface{}) string { s, _ := structure.NormalizeJsonString(v); return s }, + Description: `The document's [fields](https://cloud.google.com/firestore/docs/reference/rest/v1/projects.databases.documents) formated as a json string.`, + }, + "database": { + Type: schema.TypeString, + Optional: true, + Description: `The Firestore database id. Defaults to '"(default)"'.`, + Default: "(default)", + }, + "create_time": { + Type: schema.TypeString, + Computed: true, + Description: `Creation timestamp in RFC3339 format.`, + }, + "name": { + Type: schema.TypeString, + Computed: true, + Description: `A server defined name for this index. Format: +'projects/{{project_id}}/databases/{{database_id}}/documents/{{path}}/{{document_id}}'`, + }, + "path": { + Type: schema.TypeString, + Computed: true, + Description: `A relative path to the collection this document exists within`, + }, + "update_time": { + Type: schema.TypeString, + Computed: true, + Description: `Last update timestamp in RFC3339 format.`, + }, + "project": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ForceNew: true, + }, + }, + } +} + +func resourceFirestoreDocumentCreate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + obj := make(map[string]interface{}) + fieldsProp, err := expandFirestoreDocumentFields(d.Get("fields"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("fields"); !isEmptyValue(reflect.ValueOf(fieldsProp)) && (ok || !reflect.DeepEqual(v, fieldsProp)) { + obj["fields"] = fieldsProp + } + + url, err := replaceVars(d, config, "{{FirestoreBasePath}}projects/{{project}}/databases/{{database}}/documents/{{collection}}?documentId={{document_id}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Creating new Document: %#v", obj) + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for Document: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "POST", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutCreate)) + if err != nil { + return fmt.Errorf("Error creating Document: %s", err) + } + if err := d.Set("name", flattenFirestoreDocumentName(res["name"], d, config)); err != nil { + return fmt.Errorf(`Error setting computed identity field "name": %s`, err) + } + + // Store the ID now + id, err := replaceVars(d, config, "{{name}}") + if err != nil { + return fmt.Errorf("Error constructing id: %s", err) + } + d.SetId(id) + + log.Printf("[DEBUG] Finished creating Document %q: %#v", d.Id(), res) + + return resourceFirestoreDocumentRead(d, meta) +} + +func resourceFirestoreDocumentRead(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + url, err := replaceVars(d, config, "{{FirestoreBasePath}}{{name}}") + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for Document: %s", err) + } + billingProject = project + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequest(config, "GET", billingProject, url, userAgent, nil) + if err != nil { + return handleNotFoundError(err, d, fmt.Sprintf("FirestoreDocument %q", d.Id())) + } + + res, err = resourceFirestoreDocumentDecoder(d, meta, res) + if err != nil { + return err + } + + if res == nil { + // Decoding the object has resulted in it being gone. It may be marked deleted + log.Printf("[DEBUG] Removing FirestoreDocument because it no longer exists.") + d.SetId("") + return nil + } + + if err := d.Set("project", project); err != nil { + return fmt.Errorf("Error reading Document: %s", err) + } + + if err := d.Set("name", flattenFirestoreDocumentName(res["name"], d, config)); err != nil { + return fmt.Errorf("Error reading Document: %s", err) + } + if err := d.Set("path", flattenFirestoreDocumentPath(res["path"], d, config)); err != nil { + return fmt.Errorf("Error reading Document: %s", err) + } + if err := d.Set("fields", flattenFirestoreDocumentFields(res["fields"], d, config)); err != nil { + return fmt.Errorf("Error reading Document: %s", err) + } + if err := d.Set("create_time", flattenFirestoreDocumentCreateTime(res["createTime"], d, config)); err != nil { + return fmt.Errorf("Error reading Document: %s", err) + } + if err := d.Set("update_time", flattenFirestoreDocumentUpdateTime(res["updateTime"], d, config)); err != nil { + return fmt.Errorf("Error reading Document: %s", err) + } + + return nil +} + +func resourceFirestoreDocumentUpdate(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for Document: %s", err) + } + billingProject = project + + obj := make(map[string]interface{}) + fieldsProp, err := expandFirestoreDocumentFields(d.Get("fields"), d, config) + if err != nil { + return err + } else if v, ok := d.GetOkExists("fields"); !isEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, fieldsProp)) { + obj["fields"] = fieldsProp + } + + url, err := replaceVars(d, config, "{{FirestoreBasePath}}{{name}}") + if err != nil { + return err + } + + log.Printf("[DEBUG] Updating Document %q: %#v", d.Id(), obj) + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "PATCH", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutUpdate)) + + if err != nil { + return fmt.Errorf("Error updating Document %q: %s", d.Id(), err) + } else { + log.Printf("[DEBUG] Finished updating Document %q: %#v", d.Id(), res) + } + + return resourceFirestoreDocumentRead(d, meta) +} + +func resourceFirestoreDocumentDelete(d *schema.ResourceData, meta interface{}) error { + config := meta.(*Config) + userAgent, err := generateUserAgentString(d, config.userAgent) + if err != nil { + return err + } + + billingProject := "" + + project, err := getProject(d, config) + if err != nil { + return fmt.Errorf("Error fetching project for Document: %s", err) + } + billingProject = project + + url, err := replaceVars(d, config, "{{FirestoreBasePath}}{{name}}") + if err != nil { + return err + } + + var obj map[string]interface{} + log.Printf("[DEBUG] Deleting Document %q", d.Id()) + + // err == nil indicates that the billing_project value was found + if bp, err := getBillingProject(d, config); err == nil { + billingProject = bp + } + + res, err := sendRequestWithTimeout(config, "DELETE", billingProject, url, userAgent, obj, d.Timeout(schema.TimeoutDelete)) + if err != nil { + return handleNotFoundError(err, d, "Document") + } + + log.Printf("[DEBUG] Finished deleting Document %q: %#v", d.Id(), res) + return nil +} + +func resourceFirestoreDocumentImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + + config := meta.(*Config) + + // current import_formats can't import fields with forward slashes in their value + if err := parseImportId([]string{"(?P.+)"}, d, config); err != nil { + return nil, err + } + + re := regexp.MustCompile("^projects/([^/]+)/databases/([^/]+)/documents/(.+)/([^/]+)$") + match := re.FindStringSubmatch(d.Get("name").(string)) + if len(match) > 0 { + if err := d.Set("project", match[1]); err != nil { + return nil, fmt.Errorf("Error setting project: %s", err) + } + if err := d.Set("database", match[2]); err != nil { + return nil, fmt.Errorf("Error setting project: %s", err) + } + if err := d.Set("collection", match[3]); err != nil { + return nil, fmt.Errorf("Error setting project: %s", err) + } + if err := d.Set("document_id", match[4]); err != nil { + return nil, fmt.Errorf("Error setting project: %s", err) + } + } else { + return nil, fmt.Errorf("import did not match the regex ^projects/([^/]+)/databases/([^/]+)/documents/(.+)/([^/]+)$") + } + + return []*schema.ResourceData{d}, nil +} + +func flattenFirestoreDocumentName(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenFirestoreDocumentPath(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenFirestoreDocumentFields(v interface{}, d *schema.ResourceData, config *Config) interface{} { + if v == nil { + return nil + } + b, err := json.Marshal(v) + if err != nil { + // TODO: return error once https://github.com/GoogleCloudPlatform/magic-modules/issues/3257 is fixed. + log.Printf("[ERROR] failed to marshal schema to JSON: %v", err) + } + return string(b) +} + +func flattenFirestoreDocumentCreateTime(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func flattenFirestoreDocumentUpdateTime(v interface{}, d *schema.ResourceData, config *Config) interface{} { + return v +} + +func expandFirestoreDocumentFields(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) { + b := []byte(v.(string)) + if len(b) == 0 { + return nil, nil + } + m := make(map[string]interface{}) + if err := json.Unmarshal(b, &m); err != nil { + return nil, err + } + return m, nil +} + +func resourceFirestoreDocumentDecoder(d *schema.ResourceData, meta interface{}, res map[string]interface{}) (map[string]interface{}, error) { + // We use this decoder to add the path field + if name, ok := res["name"]; ok { + re := regexp.MustCompile("^projects/[^/]+/databases/[^/]+/documents/(.+)$") + match := re.FindStringSubmatch(name.(string)) + if len(match) > 0 { + res["path"] = match[1] + } + } + return res, nil +} diff --git a/google/resource_firestore_document_generated_test.go b/google/resource_firestore_document_generated_test.go new file mode 100644 index 00000000000..34c16eda8e9 --- /dev/null +++ b/google/resource_firestore_document_generated_test.go @@ -0,0 +1,145 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "fmt" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" +) + +func TestAccFirestoreDocument_firestoreDocumentBasicExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "project_id": getTestFirestoreProjectFromEnv(t), + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + ExternalProviders: map[string]resource.ExternalProvider{ + "random": {}, + }, + CheckDestroy: testAccCheckFirestoreDocumentDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccFirestoreDocument_firestoreDocumentBasicExample(context), + }, + { + ResourceName: "google_firestore_document.mydoc", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"database", "collection", "document_id"}, + }, + }, + }) +} + +func testAccFirestoreDocument_firestoreDocumentBasicExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_firestore_document" "mydoc" { + project = "%{project_id}" + collection = "somenewcollection" + document_id = "my-doc-%{random_suffix}" + fields = "{\"something\":{\"mapValue\":{\"fields\":{\"akey\":{\"stringValue\":\"avalue\"}}}}}" +} +`, context) +} + +func TestAccFirestoreDocument_firestoreDocumentNestedDocumentExample(t *testing.T) { + t.Parallel() + + context := map[string]interface{}{ + "project_id": getTestFirestoreProjectFromEnv(t), + "random_suffix": randString(t, 10), + } + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + ExternalProviders: map[string]resource.ExternalProvider{ + "random": {}, + }, + CheckDestroy: testAccCheckFirestoreDocumentDestroyProducer(t), + Steps: []resource.TestStep{ + { + Config: testAccFirestoreDocument_firestoreDocumentNestedDocumentExample(context), + }, + { + ResourceName: "google_firestore_document.mydoc", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"database", "collection", "document_id"}, + }, + }, + }) +} + +func testAccFirestoreDocument_firestoreDocumentNestedDocumentExample(context map[string]interface{}) string { + return Nprintf(` +resource "google_firestore_document" "mydoc" { + project = "%{project_id}" + collection = "somenewcollection" + document_id = "my-doc-%{random_suffix}" + fields = "{\"something\":{\"mapValue\":{\"fields\":{\"akey\":{\"stringValue\":\"avalue\"}}}}}" +} + +resource "google_firestore_document" "sub_document" { + project = "%{project_id}" + collection = "${google_firestore_document.mydoc.path}/subdocs" + document_id = "bitcoinkey" + fields = "{\"something\":{\"mapValue\":{\"fields\":{\"ayo\":{\"stringValue\":\"val2\"}}}}}" +} + +resource "google_firestore_document" "sub_sub_document" { + project = "%{project_id}" + collection = "${google_firestore_document.sub_document.path}/subsubdocs" + document_id = "asecret" + fields = "{\"something\":{\"mapValue\":{\"fields\":{\"secret\":{\"stringValue\":\"hithere\"}}}}}" +} +`, context) +} + +func testAccCheckFirestoreDocumentDestroyProducer(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_firestore_document" { + continue + } + if strings.HasPrefix(name, "data.") { + continue + } + + config := googleProviderConfig(t) + + url, err := replaceVarsForTest(config, rs, "{{FirestoreBasePath}}{{name}}") + if err != nil { + return err + } + + _, err = sendRequest(config, "GET", "", url, config.userAgent, nil) + if err == nil { + return fmt.Errorf("FirestoreDocument still exists at %s", url) + } + } + + return nil + } +} diff --git a/google/resource_firestore_document_sweeper_test.go b/google/resource_firestore_document_sweeper_test.go new file mode 100644 index 00000000000..db2d931a332 --- /dev/null +++ b/google/resource_firestore_document_sweeper_test.go @@ -0,0 +1,124 @@ +// ---------------------------------------------------------------------------- +// +// *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +// +// ---------------------------------------------------------------------------- +// +// This file is automatically generated by Magic Modules and manual +// changes will be clobbered when the file is regenerated. +// +// Please read more about how to change this file in +// .github/CONTRIBUTING.md. +// +// ---------------------------------------------------------------------------- + +package google + +import ( + "context" + "log" + "strings" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func init() { + resource.AddTestSweepers("FirestoreDocument", &resource.Sweeper{ + Name: "FirestoreDocument", + F: testSweepFirestoreDocument, + }) +} + +// At the time of writing, the CI only passes us-central1 as the region +func testSweepFirestoreDocument(region string) error { + resourceName := "FirestoreDocument" + log.Printf("[INFO][SWEEPER_LOG] Starting sweeper for %s", resourceName) + + config, err := 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 := getTestBillingAccountFromEnv(t) + + // Setup variables to replace in list template + d := &ResourceDataMock{ + FieldsInSchema: map[string]interface{}{ + "project": config.Project, + "region": region, + "location": region, + "zone": "-", + "billing_account": billingId, + }, + } + + listTemplate := strings.Split("https://firestore.googleapis.com/v1/projects/{{project}}/databases/{{database}}/documents/{{collection}}", "?")[0] + listUrl, err := replaceVars(d, config, listTemplate) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] error preparing sweeper list url: %s", err) + return nil + } + + res, err := sendRequest(config, "GET", config.Project, listUrl, config.userAgent, nil) + if err != nil { + log.Printf("[INFO][SWEEPER_LOG] Error in response from request %s: %s", listUrl, err) + return nil + } + + resourceList, ok := res["documents"] + if !ok { + log.Printf("[INFO][SWEEPER_LOG] Nothing found in response.") + return nil + } + + rl := resourceList.([]interface{}) + + log.Printf("[INFO][SWEEPER_LOG] Found %d items in %s list response.", len(rl), resourceName) + // Keep count of items that aren't sweepable for logging. + nonPrefixCount := 0 + for _, ri := range rl { + obj := ri.(map[string]interface{}) + if obj["name"] == nil { + log.Printf("[INFO][SWEEPER_LOG] %s resource name was nil", resourceName) + return nil + } + + name := GetResourceNameFromSelfLink(obj["name"].(string)) + // Skip resources that shouldn't be sweeped + if !isSweepableTestResource(name) { + nonPrefixCount++ + continue + } + + deleteTemplate := "https://firestore.googleapis.com/v1/{{name}}" + deleteUrl, err := 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 = sendRequest(config, "DELETE", config.Project, deleteUrl, config.userAgent, nil) + 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/resource_firestore_document_test.go b/google/resource_firestore_document_test.go new file mode 100644 index 00000000000..98483cad2a9 --- /dev/null +++ b/google/resource_firestore_document_test.go @@ -0,0 +1,62 @@ +package google + +import ( + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccFirestoreDocument_update(t *testing.T) { + t.Parallel() + + name := fmt.Sprintf("tf-test-%d", randInt(t)) + project := getTestFirestoreProjectFromEnv(t) + + vcrTest(t, resource.TestCase{ + PreCheck: func() { testAccPreCheck(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: testAccFirestoreDocument_update(project, name), + }, + { + ResourceName: "google_firestore_document.instance", + ImportState: true, + ImportStateVerify: true, + }, + { + Config: testAccFirestoreDocument_update2(project, name), + }, + { + ResourceName: "google_firestore_document.instance", + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func testAccFirestoreDocument_update(project, name string) string { + return fmt.Sprintf(` +resource "google_firestore_document" "instance" { + project = "%s" + database = "(default)" + collection = "somenewcollection" + document_id = "%s" + fields = "{\"something\":{\"mapValue\":{\"fields\":{\"yo\":{\"stringValue\":\"val1\"}}}}}" +} +`, project, name) +} + +func testAccFirestoreDocument_update2(project, name string) string { + return fmt.Sprintf(` +resource "google_firestore_document" "instance" { + project = "%s" + database = "(default)" + collection = "somenewcollection" + document_id = "%s" + fields = "{\"something\":{\"mapValue\":{\"fields\":{\"yo\":{\"stringValue\":\"val2\"}}}}}" +} +`, project, name) +} diff --git a/website/docs/r/firestore_document.html.markdown b/website/docs/r/firestore_document.html.markdown new file mode 100644 index 00000000000..a9662449107 --- /dev/null +++ b/website/docs/r/firestore_document.html.markdown @@ -0,0 +1,157 @@ +--- +# ---------------------------------------------------------------------------- +# +# *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** +# +# ---------------------------------------------------------------------------- +# +# 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: "Firestore" +layout: "google" +page_title: "Google: google_firestore_document" +sidebar_current: "docs-google-firestore-document" +description: |- + In Cloud Firestore, the unit of storage is the document. +--- + +# google\_firestore\_document + +In Cloud Firestore, the unit of storage is the document. A document is a lightweight record +that contains fields, which map to values. Each document is identified by a name. + + +To get more information about Document, see: + +* [API documentation](https://cloud.google.com/firestore/docs/reference/rest/v1/projects.databases.documents) +* How-to Guides + * [Official Documentation](https://cloud.google.com/firestore/docs/manage-data/add-data) + +~> **Warning:** This resource creates a Firestore Document on a project that already has +Firestore enabled. If you haven't already enabled it, you can create a +`google_app_engine_application` resource with `database_type` set to +`"CLOUD_FIRESTORE"` to do so. Your Firestore location will be the same as +the App Engine location specified. + + +## Example Usage - Firestore Document Basic + + +```hcl +resource "google_firestore_document" "mydoc" { + project = "my-project-name" + collection = "somenewcollection" + document_id = "my-doc-%{random_suffix}" + fields = "{\"something\":{\"mapValue\":{\"fields\":{\"akey\":{\"stringValue\":\"avalue\"}}}}}" +} +``` + +## Example Usage - Firestore Document Nested Document + + +```hcl +resource "google_firestore_document" "mydoc" { + project = "my-project-name" + collection = "somenewcollection" + document_id = "my-doc-%{random_suffix}" + fields = "{\"something\":{\"mapValue\":{\"fields\":{\"akey\":{\"stringValue\":\"avalue\"}}}}}" +} + +resource "google_firestore_document" "sub_document" { + project = "my-project-name" + collection = "${google_firestore_document.mydoc.path}/subdocs" + document_id = "bitcoinkey" + fields = "{\"something\":{\"mapValue\":{\"fields\":{\"ayo\":{\"stringValue\":\"val2\"}}}}}" +} + +resource "google_firestore_document" "sub_sub_document" { + project = "my-project-name" + collection = "${google_firestore_document.sub_document.path}/subsubdocs" + document_id = "asecret" + fields = "{\"something\":{\"mapValue\":{\"fields\":{\"secret\":{\"stringValue\":\"hithere\"}}}}}" +} +``` + +## Argument Reference + +The following arguments are supported: + + +* `fields` - + (Required) + The document's [fields](https://cloud.google.com/firestore/docs/reference/rest/v1/projects.databases.documents) formated as a json string. + +* `collection` - + (Required) + The collection ID, relative to database. For example: chatrooms or chatrooms/my-document/private-messages. + +* `document_id` - + (Required) + The client-assigned document ID to use for this document during creation. + + +- - - + + +* `database` - + (Optional) + The Firestore database id. Defaults to `"(default)"`. + +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + + +## Attributes Reference + +In addition to the arguments listed above, the following computed attributes are exported: + +* `id` - an identifier for the resource with format `{{name}}` + +* `name` - + A server defined name for this index. Format: + `projects/{{project_id}}/databases/{{database_id}}/documents/{{path}}/{{document_id}}` + +* `path` - + A relative path to the collection this document exists within + +* `create_time` - + Creation timestamp in RFC3339 format. + +* `update_time` - + Last update timestamp in RFC3339 format. + + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 4 minutes. +- `update` - Default is 4 minutes. +- `delete` - Default is 4 minutes. + +## Import + + +Document can be imported using any of these accepted formats: + +``` +$ terraform import google_firestore_document.default {{name}} +``` + +## User Project Overrides + +This resource supports [User Project Overrides](https://www.terraform.io/docs/providers/google/guides/provider_reference.html#user_project_override). diff --git a/website/google.erb b/website/google.erb index 2ab7e7b181e..ab88f54ea42 100644 --- a/website/google.erb +++ b/website/google.erb @@ -2170,6 +2170,10 @@ Resources