NoSQL Database: Provisioning a Firestore Database
Scenario
Your serverless app requires a flexible, fast, heavily scalable NoSQL document database to store application profiles. Instead of provisioning a heavy Cassandra or MongoDB cluster, you will use Firestore in Native mode, Google's fully managed serverless NoSQL document database.
- Enable the App Engine integration / Firestore database for the project using a google_firestore_database resource.
- Set the location ID (e.g. nam5 for us-central multi-region).
- Set the type to FIRESTORE_NATIVE (as opposed to Datastore mode).
- Ensure you set the database name to (default) as most projects use the default database.
Additional Context
Firestore vs Datastore: Historically, GCP offered "Datastore". They rebuilt it entirely as "Firestore". When you make a database, you must choose whether you want the backwards-compatible "Datastore mode" or the new robust "Native mode". For all new applications, Native mode is highly recommended.
Default Database vs Named Databases: Most older GCP projects could only have ONE Firestore database, named `(default)`. GCP now supports multiple databases per project, but many client SDKs still automatically assume you are interacting with the `(default)` database unless explicitly configured otherwise.
variables.tf
variable "project_id" { type = string }
variable "location_id" { type = string; default = "nam5" } # NA multi-regionmain.tf
provider "google" {
project = var.project_id
}
# The expected App Engine location dependency is sometimes tricky.
# Make sure the project has an App Engine application created if using Datastore mode,
# but for Native mode on new projects, google_firestore_database is sufficient.
resource "google_firestore_database" "database" {
project = var.project_id
# "(default)" is the standard name indicating the primary DB for the project
name = "(default)"
# location_id accepts regions ("us-central1") or multi-regions ("nam5" for multi-region US)
location_id = var.location_id
# FIRESTORE_NATIVE or DATASTORE_MODE. Native is recommended.
type = "FIRESTORE_NATIVE"
# Determines if concurrent connections and transactions are managed
concurrency_mode = "OPTIMISTIC"
}outputs.tf
output "firestore_db_name" {
value = google_firestore_database.database.name
}Workflow Commands
terraform init
terraform apply -var="project_id=my-gcp-project-123"
# Verify Firestore creation by listing databases
gcloud firestore databases list
terraform destroy -var="project_id=my-gcp-project-123"Apply complete! Resources: 1 added, 0 changed, 0 destroyed. Outputs: firestore_db_name = "(default)"

