|
| 1 | +# Cloud SQL Database Example |
| 2 | + |
| 3 | +This example shows how create Cloud SQL databases for for MySQL and PostgreSQL using the Terraform module. |
| 4 | + |
| 5 | +**Figure 1.** *diagram of Google Cloud resources* |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | +## Run Terraform |
| 10 | + |
| 11 | +``` |
| 12 | +terraform init |
| 13 | +terraform plan |
| 14 | +terraform apply |
| 15 | +``` |
| 16 | + |
| 17 | +## Test connection to database |
| 18 | + |
| 19 | +Install the Cloud SQL Proxy: https://cloud.google.com/sql/docs/mysql/sql-proxy#install |
| 20 | + |
| 21 | +Run the Cloud SQL proxy for MySQL instance: |
| 22 | + |
| 23 | +``` |
| 24 | +GOOGLE_PROJECT=$(gcloud config get-value project) |
| 25 | +
|
| 26 | +MYSQL_DB_NAME=$(terraform output -module mysql-db -json | jq -r '.instance_name.value') |
| 27 | +MYSQL_CONN_NAME="${GOOGLE_PROJECT}:us-central1:${MYSQL_DB_NAME}" |
| 28 | +
|
| 29 | +PGSQL_DB_NAME=$(terraform output -module postgresql-db -json | jq -r '.instance_name.value') |
| 30 | +PGSQL_CONN_NAME="${GOOGLE_PROJECT}:us-central1:${PGSQL_DB_NAME}" |
| 31 | +
|
| 32 | +./cloud_sql_proxy -instances=${MYSQL_CONN_NAME}=tcp:3306,${PGSQL_CONN_NAME}=tcp:5432 |
| 33 | +``` |
| 34 | + |
| 35 | +Start Cloud SQL Proxy for Postgres instance: |
| 36 | + |
| 37 | +``` |
| 38 | +GOOGLE_PROJECT=$(gcloud config get-value project) |
| 39 | +
|
| 40 | +PGSQL_DB_NAME=$(terraform output -module postgresql-db -json | jq -r '.instance_name.value') |
| 41 | +PGSQL_CONN_NAME="${GOOGLE_PROJECT}:us-central1:${PGSQL_DB_NAME}" |
| 42 | +
|
| 43 | +./cloud_sql_proxy -instances=${PGSQL_CONN_NAME}=tcp:3306 |
| 44 | +``` |
| 45 | + |
| 46 | +Get the generated password: |
| 47 | + |
| 48 | +``` |
| 49 | +echo MYSQL_PASSWORD=$(terraform output -module mysql-db -json | jq -r '.generated_user_password.value') |
| 50 | +echo PGSQL_PASSWORD=$(terraform output -module postgresql-db -json | jq -r '.generated_user_password.value') |
| 51 | +``` |
| 52 | + |
| 53 | +Test the MySQL connection: |
| 54 | + |
| 55 | +``` |
| 56 | +mysql -udefault -p --host 127.0.0.1 default |
| 57 | +``` |
| 58 | + |
| 59 | +> When prompted, enter the value of MYSQL_PASSWORD |
| 60 | +
|
| 61 | +Test the PostgreSQL connection: |
| 62 | + |
| 63 | +``` |
| 64 | +psql -h 127.0.0.1 --user default |
| 65 | +``` |
| 66 | + |
| 67 | +> When prompted, enter the value of PGSQL_PASSWORD |
0 commit comments