arrow_back

Creating Spanner Instances and Databases (CLI and Terraform)

Join Sign in
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

Creating Spanner Instances and Databases (CLI and Terraform)

Lab 1 hour universal_currency_alt 1 Credit show_chart Introductory
Test and share your knowledge with our community!
done
Get access to over 700 hands-on labs, skill badges, and courses

SCBL002

Overview

In this lab, you automate the creation of Spanner instances and databases using the Google Cloud SDK, the Command Line Interface (CLI), and Terraform.

Objectives

In this lab, you learn how to:

  • Create instances and databases using the gcloud CLI.
  • Automate Spanner infrastructure using Terraform.

Setup and Requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. The output contains a line that declares the PROJECT_ID for this session:

Your Cloud Platform project in this session is set to YOUR_PROJECT_ID

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

  2. Your output should now look like this:

Output:

ACTIVE: * ACCOUNT: student-01-xxxxxxxxxxxx@qwiklabs.net To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = <project_ID>

Example output:

[core] project = qwiklabs-gcp-44776a13dea667a6 Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Task 1. Create instances and databases using the gcloud CLI

  1. On the Google Cloud Console title bar, click Activate Cloud Shell (cloud shell icon). If prompted, click Continue.

  2. Run the following command to set your project ID:

gcloud config set project {{{project_0.project_id|placeholder_project_id}}}
  1. From the Cloud Shell prompt, run the following command to create a Spanner instance named test-spanner-instance.

Note the parameters for Spanner configuration and capacity. If you are asked to Authorize the command, then do so.

gcloud spanner instances create test-spanner-instance --config=regional-{{{project_0.default_region|place_holder_text}}} --description="test-spanner-instance" --processing-units=100
  1. The command should not take long. In the Console, navigate to the Spanner service and verify the instance was created.

To see the instance, you could also run the command below. Try that now.

gcloud spanner instances list
  1. Before creating the Pets database, you need a file that contains the DDL code. Type the following command to create the file and open it in the nano code editor.
nano pets-db-schema.sql
  1. Paste the following code into Nano. Type Ctrl+X, then Y, and then press the ENTER key to save the file.
CREATE TABLE Owners ( OwnerID STRING(36) NOT NULL, OwnerName STRING(MAX) NOT NULL ) PRIMARY KEY (OwnerID); CREATE TABLE Pets ( PetID STRING(36) NOT NULL, OwnerID STRING(36) NOT NULL, PetType STRING(MAX) NOT NULL, PetName STRING(MAX) NOT NULL, Breed STRING(MAX) NOT NULL, ) PRIMARY KEY (PetID);
  1. Now that you have the Schema file, run the following command to create the database.
gcloud spanner databases create pets-db --instance=test-spanner-instance --database-dialect=GOOGLE_STANDARD_SQL --ddl-file=./pets-db-schema.sql
  1. Insert an Owner and all of the dogs owned. The primary keys for Owners and Pets use UUIDs. Enter the following command to create a UUID for the owner and store it in a variable.
owner_uuid=$(cat /proc/sys/kernel/random/uuid) echo $owner_uuid
  1. Insert the Owner Doug.
    Note: the --data parameter that allows you to pass the fields in name-value pairs.
gcloud spanner rows insert --table=Owners --database=pets-db --instance=test-spanner-instance --data=OwnerID=$owner_uuid,OwnerName=Doug
  1. Insert all of Doug's dogs with the following commands.
gcloud spanner rows insert --table=Pets --database=pets-db --instance=test-spanner-instance --data=PetID=$(cat /proc/sys/kernel/random/uuid),OwnerID=$owner_uuid,PetName='Rusty',PetType='Dog',Breed='Poodle' gcloud spanner rows insert --table=Pets --database=pets-db --instance=test-spanner-instance --data=PetID=$(cat /proc/sys/kernel/random/uuid),OwnerID=$owner_uuid,PetName='Duchess',PetType='Dog',Breed='Terrier' gcloud spanner rows insert --table=Pets --database=pets-db --instance=test-spanner-instance --data=PetID=$(cat /proc/sys/kernel/random/uuid),OwnerID=$owner_uuid,PetName='Gretyl',PetType='Dog',Breed='Shepherd' gcloud spanner rows insert --table=Pets --database=pets-db --instance=test-spanner-instance --data=PetID=$(cat /proc/sys/kernel/random/uuid),OwnerID=$owner_uuid,PetName='Gigi',PetType='Dog',Breed='Retriever' gcloud spanner rows insert --table=Pets --database=pets-db --instance=test-spanner-instance --data=PetID=$(cat /proc/sys/kernel/random/uuid),OwnerID=$owner_uuid,PetName='Noir',PetType='Dog',Breed='Schnoodle' gcloud spanner rows insert --table=Pets --database=pets-db --instance=test-spanner-instance --data=PetID=$(cat /proc/sys/kernel/random/uuid),OwnerID=$owner_uuid,PetName='Bree',PetType='Dog',Breed='Mutt'
  1. Let's see if it worked. Run the following query.
gcloud spanner databases execute-sql pets-db --instance=test-spanner-instance --sql='SELECT o.OwnerName, p.PetName, p.PetType, p.Breed FROM Owners as o JOIN Pets AS p ON o.OwnerID = p.OwnerID'
  1. You can also go to the Console and view the data. Choose Spanner from the product list. Then select test-spanner-instance > pets-db (under Databases) > Pets (under Tables) > Data from the left menu.

  2. Delete the database with the following command.

gcloud spanner databases delete pets-db --instance=test-spanner-instance
  1. In the Console, verify the database was deleted.

  2. Lastly, delete the instance with the following command.

gcloud spanner instances delete test-spanner-instance --quiet

Note: The --quiet parameter runs the command without prompting the user. This could have been added to the prior command as well. This is useful if you are writing an automated pipeline and there would be no user to ask.

  1. In the Console, verify that the instance was deleted.

Task 2. Automate Spanner infrastructure using Terraform

  1. Create a folder for your Terraform files and change to it using the following commands.
mkdir terraform-spanner cd terraform-spanner
  1. You need a number of files for the Terraform module. Run the following command to create the empty files.
touch main.tf provider.tf terraform.tfvars variables.tf
  1. Click the Open Editor button to open the code editor. From the Explorer pane on the left, find the terraform-spanner folder you just created and expand it. Select the provider.tf file to open it in the editor and add the following code to it.
terraform { required_providers { google = { source = "hashicorp/google" version = "~> 4.0" } } } provider "google" { project = var.project_id region = var.region }

Note: The code in the Terraform block downloads the Google provider from Hashicorp's website. The code in the provider block configures the provider to use the correct Project ID and Region which you set as variables later.

  1. Open the file main.tf and add the following resource block. This code creates the Spanner instance.
resource "google_spanner_instance" "db-instance" { name = "terraform-spanner-instance" config = "regional-${var.region}" display_name = "TF Spanner Instance" processing_units = var.processing_units force_destroy = var.force_destroy }
  1. In the same file, below the previous code, add the following which creates the Pets database. Note the DDL code which defines the tables.
resource "google_spanner_database" "test-database" { instance = google_spanner_instance.db-instance.name name = "pets-db" # Can't run destroy unless set to false deletion_protection = var.deletion_protection ddl = [ "CREATE TABLE Owners (OwnerID STRING(36) NOT NULL, OwnerName STRING(MAX) NOT NULL) PRIMARY KEY (OwnerID)", "CREATE TABLE Pets (PetID STRING(36) NOT NULL, OwnerID STRING(36) NOT NULL, PetType STRING(MAX) NOT NULL, PetName STRING(MAX) NOT NULL, Breed STRING(MAX) NOT NULL) PRIMARY KEY (PetID)", ] }
  1. Open the file variables.tf. In this file, you declare the variables used in the Terraform module. Add the following code.
variable "deletion_protection" { description = "If set to true, you cannot run terraform destroy if there are databases created." type = bool default = false } variable "force_destroy" { description = "If set to true, running terraform destroy will delete all backups." type = bool default = true } variable "processing_units" { type = number default = 100 } variable "project_id" { description = "The GCP Project ID." type = string } variable "region" { type = string }
  1. All the variables except for project_id and region have defaults. You use the terraform.tfvars file to set those variable values. Open that file and add the following.
project_id = "{{{project_0.project_id|placeholder_project_id}}}" region = "{{{project_0.default_region|place_holder_text}}}"
  1. Let's see if it works. Click the Open Terminal button. Note, you may have to switch back to the original tab first if your editor opened a new tab or window. At the command prompt, enter the following.
terraform init
  1. Assuming there were no errors with the previous command, enter the following and analyze the output. It should say that two resources will be added.
terraform plan
  1. Lasty, enter the following command to create the Spanner instance and Pets database. You must type yes when prompted.
terraform apply
  1. Wait for the Terraform command to complete. In the Console, navigate to the Spanner service and verify that the instance and database were created. There is no refresh button, so you may need to click on another product and then return to Spanner to refresh the instances list.

  2. Return to the terminal and enter the following command to delete the Spanner instance.

terraform destroy -auto-approve

Congratulations! You have automated the creation of Spanner instances and databases using the Google Cloud SDK, the Command Line Interface (CLI), and Terraform.

End your lab

When you have completed your lab, click End Lab. Your account and the resources you've used are removed from the lab platform.

You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.

The number of stars indicates the following:

  • 1 star = Very dissatisfied
  • 2 stars = Dissatisfied
  • 3 stars = Neutral
  • 4 stars = Satisfied
  • 5 stars = Very satisfied

You can close the dialog box if you don't want to provide feedback.

For feedback, suggestions, or corrections, please use the Support tab.

Copyright 2023 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.