5

我正在编写一个脚本来使用gcloudSDK 编排 Google Cloud SQL 实例。

SDK 有一个连接命令,它接受用户名,但必须在提示符下输入密码——即不能作为参数传递。

成功验证然后允许执行查询 - 流程如下所示:

$ 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;

我需要以非交互方式执行此操作。我试过了:

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

但它只执行第一个命令。

如何在单个命令中连接、验证和运行查询?

更新:

根据@danlor 链接到这个问题的评论,我两种都试过了:

yes password | gcloud...

printf 'password\n' | gcloud...

但两者仍然提示输入密码。

4

1 回答 1

2

看起来该gcloud sql connect命令无法让您将execute标志传递给 MySQL 命令行实用程序。我建议为此使用Cloud SQL 代理。您的脚本可能如下所示:

./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
于 2019-05-14T21:09:01.577 回答