Last active
January 30, 2018 18:21
-
-
Save kstromeiraos/2af66a52b0d0693029c156cfbee5ced8 to your computer and use it in GitHub Desktop.
Python script to create a dump of a Google Cloud SQL DB and import it into another DB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import google.cloud.storage | |
import random | |
from subprocess import call | |
projectId = 'YOUR_PROJECT_ID'; | |
bucketName = 'sqldumpbucket-' + str(random.randint(100000, 999999)); | |
exportDbInstance = 'YOUR_EXPORT_DB_INSTANCE'; | |
exportDbServiceAccount = 'YOUR_EXPORT_DB_SERVICE_ACCOUNT'; | |
exportDbName = 'YOUR_EXPORT_DB_NAME' | |
importDbInstance = 'YOUR_IMPORT_DB_INSTANCE'; | |
importDbServiceAccount = 'YOUR_IMPORT_DB_SERVICE_ACCOUNT'; | |
importDbName = 'YOUR_IMPORT_DB_NAME' | |
# Create a storage client. | |
storage_client = google.cloud.storage.Client() | |
# Create temp bucket to export DB | |
bucket = storage_client.create_bucket(bucketName) | |
# Add the service account to the bucket ACL as a writer | |
acl = bucket.acl | |
acl.user(exportDbServiceAccount).grant_write() | |
acl.save() | |
# Export database to bucket | |
call(["gcloud", "sql", "instances", "export", exportDbInstance, "gs://" + bucketName + "/sqldumpfile.gz", "--database", exportDbName]) | |
# Add the service account to the bucket ACL as a writer and reader for the dump file | |
acl = bucket.acl | |
acl.user(importDbServiceAccount).grant_write() | |
acl.save() | |
call(["gsutil", "acl", "ch", "-u", importDbServiceAccount + ":R", "gs://" + bucketName + "/sqldumpfile.gz"]) | |
# Import database from bucket | |
call(["gcloud", "sql", "instances", "import", importDbInstance, "gs://" + bucketName + "/sqldumpfile.gz", "--database", importDbName]) | |
# Delete bucket | |
bucket.delete(force=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment