Cloud SQL for PostgreSQL is a fully-managed PostgreSQL relational database service on Google Cloud Platform. This Terraform configuration will create a Cloud SQL PostgreSQL V9.6 instance in Google Cloud. It can also be used as a Module to instantiate one or more instances quickly.
- A Google Cloud account and project.
Google Cloud SQLandCloud SQL Admin APIAPIs must be enabled on the project. This can be enabled on Google cloud console or CLI.- Google Cloud credentials
.jsonfile from a Service Account is required. This can be obtained by generating a Service Account Key. - Terraform installed on a machine where this configuration will be downloaded and run: Terraform install instructions
- Simple: Provisions an example Cloud SQL instance.
- Prod and Dev: Provisions example Prod and Dev CloudSQL instances.
Download and configure provider:
- Clone this repository via
gitor HTTP and change to working directory:cd terraform-gcp-cloudsql. - Set the following Terraform configuration variables appropriately to setup the Terraform Google Provider.
export TF_VAR_gcp_credentials=$(cat <path-to-gcp-service-account-json>)
export TF_VAR_gcp_project="<gcp-project-name>"
Set Configuration variables:
- Set the following Terraform Configuration variables specified as environment variables with
TF_VARprefix.
export TF_VAR_gcp_sql_root_user_pw=<pw>
export TF_VAR_authorized_network="$(curl whatismyip.akamai.com)/32"
- Note: the
authorized_networkvariable above should be set to the system you will access PostgreSQL from. In this we are assuming Terraform will run from the same machine that PostgreSQL will be accessed from. This assumption will not hold true in case of Terraform Enterprise or a separate Terraform build server. - Adjust any other Terraform configuration variables in variables.tf.
Run terraform:
- Run the terraform commands below to initialize the configuration:
terraform init
terraform plan
- If everything looks good, go ahead with apply:
terraform apply. - To view outputs issue:
terraform output.
(Optional) Connect to PostgreSQL instance:
- To connect to PostgreSQL using the
psqlCLI, please install it on your system (if not already available). - Make a note of the IP address from terraform output:
terraform output. If you havejqinstalled, you can export it to a variable:export sql_ip=$(terraform output -json | jq -r .ip.value) - Adjust the
hostaddrparameter to connect usingpsql:
psql "sslmode=disable dbname=postgres user=root hostaddr=${sql_ip}"
- (Optional): run some sql statements from the
psqlprompt:
CREATE TABLE cities (
name varchar(80),
location char(2)
);
INSERT INTO cities VALUES ('San Francisco', 'CA');
INSERT INTO cities VALUES ('Buffalo', 'NY');
SELECT * from cities;
\q
Cleanup:
- To destroy the Cloud SQL instance, issue:
terraform destroy. - Unset environment variables:
unset TF_VAR_gcp_credentials
unset TF_VAR_gcp_project
unset TF_VAR_gcp_sql_root_user_pw