As part of data migration I needed to export a PostgreSQL database from Google Cloud Platform Cloud SQL instance. This was quite easy to do with the following steps, and of course I run the export in a serverless way. Serverless exports cost money, so make sure to review the pricing. I run all the commands on Cloud Shell, so no local installs needed.
-
Make sure you set the correct project
my-project
before running any other commands:gcloud config set project my-project
-
Create a Cloud Storage bucket for the export data, let’s call it
postgres-export-bucket
:gcloud storage buckets create gs://postgres-export-bucket \ --default-storage-class=STANDARD \ --location=EUROPE-NORTH1 \ --uniform-bucket-level-access
-
Get the Cloud SQL instance
my-psql-instance
service account:gcloud sql instances describe my-psql-instance
From the response, look for the service account, which looks something like this:
some-random-string@gcp-sa-cloud-sql.iam.gserviceaccount.com
. -
Give the service account IAM role which allows it to write to the bucket:
# All one line gsutil iam ch serviceAccount:some-random-string@gcp-sa-cloud-sql.iam.gserviceaccount.com:roles/storage.objectAdmin gs://postgres-export-bucket
-
Finally, run the export job for the database
my-db
:gcloud sql export sql my-psql-instance \ gs://postgres-export-bucket/sqldumpfile.gz \ --database=my-db \ --offload
-
Download the database dump from the bucket, and do what you need with it.
Further reading
- https://cloud.google.com/sql/pricing
- https://cloud.google.com/sdk/gcloud/reference/config/set
- https://cloud.google.com/storage/docs/creating-buckets#storage-create-bucket-cli
- https://cloud.google.com/iam/docs/principal-identifiers
- https://cloud.google.com/storage/docs/access-control/using-iam-permissions#gsutil
- https://cloud.google.com/sql/docs/postgres/import-export/import-export-sql#gcloud