Execute Google Cloud SQL query in command line non-interactively [duplicate]
Asked Answered
K

1

7

I'm writing a script to orchestrate a Google Cloud SQL instance using the gcloud SDK.

The SDK has a connect command, which takes a username but the password has to be entered at the prompt - ie it cannot be passed as an argument.

Successfully authenticating then allows a query to be executed - the flow looks like this:

$ gcloud sql connect instance-name --user=root
Whitelisting your IP for incoming connection for 5 minutes...done.
Connecting to database with SQL user [root].Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 8054
Server version: 5.7.14-google-log (Google)

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> USE tablename;

I need to do this non-interactively. I've tried:

gcloud sql connect instance-name --user=root && echo "password" && echo "USE tablename;"

But it only executes the first command.

How can I connect, authenticate & run a query in a single command?

Update:

As per the comment from @danlor linking to this question, I've tried both:

yes password | gcloud...

and

printf 'password\n' | gcloud...

but both still prompt for the password.

Knockwurst answered 14/5, 2019 at 9:15 Comment(2)
&& means that the next command will only be executed after the clean exit (success) of the previous command. That's why only the first command is being executed. Check out askubuntu.com/questions/338857/…Wolfgang
Thanks @danlor - I've tried both yes and printf approaches in the linked answer, but neither workKnockwurst
R
4

It doesn't look like the gcloud sql connect command give you the ability to pass in the execute flag to the MySQL command line utility. I would suggest using the Cloud SQL proxy for this instead. Your script will likely look something like the following:

./cloud_sql_proxy -dir=/cloudsql -instances=<INSTANCE_CONNECTION_NAME> &
PID=$!
mysql -u root --password "YOUR-PASSWORD" -S /cloudsql/<INSTANCE_CONNECTION_NAME> --execute "USE tablename;"
kill $PID
Railing answered 14/5, 2019 at 21:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.