Skip to content

Commit 8692bb3

Browse files
committed
Incrementally testing GH action.
1 parent 736d8b7 commit 8692bb3

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

scripts/replicate_db.sh

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#!/bin/bash
2+
# We should already be authenticated with gcloud when entering this script
3+
set -x
4+
5+
# Define variables about GCP.
6+
# For now we use the same DB instance for source and destination.
7+
SOURCE_PROJECT_ID="mobility-feeds-qa"
8+
DEST_PROJECT_ID=$SOURCE_PROJECT_ID
9+
BUCKET_PROJECT_ID="mobility-feeds-dev"
10+
BUCKET_NAME="mobilitydata-database-dump-dev2"
11+
SOURCE_SQL_SERVICE_ACCOUNT="[email protected]"
12+
DEST_SQL_SERVICE_ACCOUNT=$SOURCE_SQL_SERVICE_ACCOUNT
13+
DEST_DATABASE_USER="postgres"
14+
DEST_DATABASE_PASSWORD="...Put password here..."
15+
SOURCE_DATABASE_NAME="MobilityDatabase"
16+
DEST_DATABASE_NAME="MobilityDatabasePreRelease"
17+
GCP_REGION="northamerica-northeast1"
18+
SOURCE_DB_INSTANCE_NAME="mobilitydata-database-instance"
19+
DEST_DB_INSTANCE_NAME=$SOURCE_DB_INSTANCE_NAME
20+
DUMP_FILE_NAME="qa-db.sql"
21+
22+
echo "Service account: $SERVICE_ACCOUNT"
23+
24+
if ! gsutil ls -b "gs://${BUCKET_NAME}" &> /dev/null; then
25+
echo "Bucket doesn't exist. Creating..."
26+
gsutil mb -l $GCP_REGION -p $BUCKET_PROJECT_ID "gs://${BUCKET_NAME}"
27+
else
28+
echo "Bucket already exists."
29+
fi
30+
31+
# Give write permission for the source sql instance to write to the bucket
32+
gsutil iam ch serviceAccount:$SOURCE_SQL_SERVICE_ACCOUNT:objectCreator gs://$BUCKET_NAME
33+
34+
# Give read permission on the bucket to the destination sql instance
35+
gsutil iam ch serviceAccount:$DEST_SQL_SERVICE_ACCOUNT:objectViewer gs://$BUCKET_NAME
36+
37+
# Dump the db
38+
# According to chatgpt,
39+
# This is Google's recommended, safe method and doesn’t require direct access to the DB. It runs the export
40+
# in a way that avoids locking the database and works from GCP itself (so no traffic leaves GCP).
41+
gcloud sql export sql $SOURCE_DB_INSTANCE_NAME gs://$BUCKET_NAME/$DUMP_FILE_NAME --database=$SOURCE_DATABASE_NAME --project=$SOURCE_PROJECT_ID --quiet
42+
43+
# Create a new database
44+
gcloud sql databases create $DEST_DATABASE_NAME --instance=$DEST_DB_INSTANCE_NAME
45+
46+
# Import to the new DB
47+
# The exported sql contains statements that require authentication as user postgres.
48+
# In theory we could dump the DB without these statements, with:
49+
# pg_dump --no-owner --no-privileges -d your_database > clean_dump.sql.
50+
51+
export PGPASSWORD=$DEST_DATABASE_PASSWORD
52+
gcloud sql import sql $DEST_DB_INSTANCE_NAME gs://$BUCKET_NAME/$DUMP_FILE_NAME --project=$DEST_PROJECT_ID --database=$DEST_DATABASE_NAME --user=$DEST_DATABASE_USER --quiet

0 commit comments

Comments
 (0)