How to connect to Cloud SQL from Cloud Shell?

sthomps picture sthomps · Apr 24, 2016 · Viewed 14.3k times · Source

I'd like to use the Cloud Shell to run database migrations on my 2nd gen Cloud Sql instance.

I found an example in the docs for how to connect using gcloud. But when I run the command Im getting an error:

$ gcloud beta sql connect my-instance --user=root
ERROR: (gcloud.beta.sql.connect) Invalid instance property.

But, even if this does work Im not sure how to connect from my python script that performs my migrations. What connection string would I use? Would I need to manually whitelist the Cloud Shell IP for access?

Answer

Ralph Pina picture Ralph Pina · Apr 25, 2016

Edit

The instructions above did not work, it was showing another message.

The first time you'll need to run the command below: gcloud beta sql connect <instance id> --project <project id>:us-central1 --user root

Also, I switch to my project in the console: gcloud config set project <project id>

However, I am now getting another error: ERROR: (gcloud.beta.sql.connect) The client is not authorized to make this request.

I guess I'll need to allow the clients...

Another Edit re Allowing Clients

To finally connect to the DB I had install Google SQL Proxy.

I set it up with FUSE (I use a Mac). After opening a connection following the instructions in the Google Docs. I was able to connect via the mysql command line. $ mysql -u root -p -S <localtion of cloud sql proxy folder>/<project id>:us-central1:<db instance id>

Original

Just figured this one out. Here's how to do it:

  1. Click on the instance you want to connect

  2. In the Overview section, scroll down to Properties.

  3. In Properties you will see Instance connection name. It will look something like <your project>:us-central1:<instance name>

Use that in the command: $ gcloud beta sql connect <your project>:us-central1:<instance name> --user root