内容
GCP ProjectにSpannerのデータベースを作成します。IaCツールとしてTerraformを利用します。
Spanner Instanceの作り方
SpannerのInstance自体の作り方については以下の記事で解説していますので、こちらをご確認ください。
https://yssy.io/articles/gcp-spanner-create
TerraformソースでSpanner Databaseを追加する
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = "5.8.0"
}
}
}
provider "google" {
project = var.project_id
region = "asia-northeast1"
}
variable "project_id" {
description = "The project ID to deploy into"
}
resource "google_spanner_instance" "this" {
config = "regional-us-central1"
display_name = "Spanner Instance"
num_nodes = 1
}
resource "google_spanner_database" "this" {
instance = google_spanner_instance.this.name
name = "spanner-database"
ddl = [
"CREATE TABLE t1 (t1 INT64 NOT NULL,) PRIMARY KEY(t1)",
]
deletion_protection = false
}
上記がTerraformでSpannerのInstanceとDatabaseを作成するソースコードです。
Spanner Instance
というSpanner Instanceの中に、spanner-database
というデータベースを作成します。
Terraform Applyを実行する
$ terraform apply
google_spanner_instance.this: Refreshing state... [id=project-name/tfgen-spanid-20240506183705168]
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# google_spanner_database.this will be created
# google_spanner_database.this will be created
+ resource "google_spanner_database" "this" {
+ database_dialect = (known after apply)
+ ddl = [
+ "CREATE TABLE t1 (t1 INT64 NOT NULL,) PRIMARY KEY(t1)",
]
+ deletion_protection = false
+ enable_drop_protection = false
+ id = (known after apply)
+ instance = "tfgen-spanid-20240506183705168"
+ name = "spanner-database"
+ project = "project-name"
+ state = (known after apply)
+ version_retention_period = (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
google_spanner_database.this: Creating...
google_spanner_database.this: Still creating... [10s elapsed]
google_spanner_database.this: Still creating... [20s elapsed]
google_spanner_database.this: Still creating... [30s elapsed]
google_spanner_database.this: Still creating... [40s elapsed]
google_spanner_database.this: Creation complete after 48s [id=tfgen-spanid-20240506183705168/spanner-database]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
GCP上で確認する
このようにGCP上でDatabaseが作成されていることを確認できます。
また、ddl
で指定したTableも作成されています。