How to get IP of Google Cloud SQL instance via CLI

Viewed 889

I use Cloud SQL on Google Cloud Platform.

It is useful to have IP of database as an variable, so it can be used in scripts.

What command can be used to achieve this?

Bash example:

export DP_IP=$(gcloud ................)
3 Answers

Update: please see also answer by @rossco

Basic solution:

export DB_IP=$(gcloud sql instances describe $DATABASE_ID --project $PROJECT_ID --format 'value(ipAddresses.ipAddress)')

Solution using Secrets Manager:

With these Bash commands you can get url and save it in Secrets Manager:

First create empty Secret:

gcloud secrets create "DB_IP" --project $PROJECT_ID --replication-policy=automatic

Then:

gcloud sql instances describe $DATABASE_ID --project $PROJECT_ID --format 'value(ipAddresses.ipAddress)' --project $PROJECT_ID | gcloud secrets versions add "DB_IP" --data-file=- --project $PROJECT_ID

or version with added ":5432"

DB_IP=$(gcloud sql instances describe $DATABASE_ID --project $PROJECT_ID --format 'value(ipAddresses.ipAddress)')   # capture first string.
echo "$DB_IP:5432" | gcloud secrets versions add "DB_IP" --data-file=- --project $PROJECT_ID

And then you can load it as needed from Secrets Manager:

export DB_IP=$(gcloud secrets versions access latest --secret="DB_IP" --project $PROJECT_ID )

The accepted answer will not work when multiple IP addresses are available, such as public, outgoing and private. To select the IP address you are interested in from a specific instance you need to filter on address type.
For example, to get the private IP of a named instance

gcloud sql instances list --filter=name:$DATABASE_ID --format="value(PRIVATE_ADDRESS)"

Change PRIVATE_ADDRESS to PRIMARY_ADDRES if you want the public address

Yoiu can try this:

$ echo $(gcloud sql instances describe [instance id] --format="value(ipAddresses.ipAddress)")
Related