Ada*_*son 7 mysql bash non-interactive google-cloud-sql
我正在编写一个脚本来使用 SDK 编排 Google Cloud SQL 实例gcloud。
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;
Run Code Online (Sandbox Code Playgroud)
我需要以非交互方式执行此操作。我试过了:
gcloud sql connect instance-name --user=root && echo "password" && echo "USE tablename;"
Run Code Online (Sandbox Code Playgroud)
但它只执行第一个命令。
如何在单个命令中连接、验证和运行查询?
更新:
根据链接到此问题的 @danlor 的评论,我已经尝试了两种方法:
yes password | gcloud...
Run Code Online (Sandbox Code Playgroud)
和
printf 'password\n' | gcloud...
Run Code Online (Sandbox Code Playgroud)
但两者仍然提示输入密码。
该命令似乎无法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
Run Code Online (Sandbox Code Playgroud)