我想创建一个shell脚本,在docker CLI中运行,并创建一个MySQL用户,主机IP作为命令行变量传递。
所以我的脚本就是./create_user.sh 172.17.0.1
我尝试从仅在sql语句部分插入变量并使用类似的东西开始:
#!/bin/sh
docker exec -i atb-mariadb bash <<'EOF'
mysql -uroot -pmypass
set @ip='172.17.0.1';
CREATE USER 'exporter'@@ip IDENTIFIED BY 'mypass';
GRANT PROCESS, REPLICATION CLIENT ON *.* TO 'exporter'@'172.17.0.1';
GRANT SELECT ON performance_schema.* TO 'exporter'@'172.17.0.1';
SELECT user, host FROM mysql.user;
exit
EOF
这导致语法错误,以及我尝试过的其他一些错误:
CREATE USER CONCAT_WS('exporter','@',@ip) IDENTIFIED BY 'mypass';
CREATE USER 'exporter'@CONCAT_WS('',@ip) IDENTIFIED BY 'mypass';
这当然只是脚本的sql语句部分中的变量。在整个shell脚本中使用一个变量并将其传递给sql bash是一个我甚至都无法解决的问题。
提前感谢您的帮助!
已更新
我尝试了Raymond Nijland的解决方案,它适用于sql变量部分。但是,尝试通过命令行传递变量值仍然无法执行以下脚本:
#!/bin/sh
echo script received $1
docker exec -e ipa=$1 -i atb-mariadb bash <<'EOF'
echo exec received $ipa
mysql -uroot -pmypass -e "
SET @ip='${ipa}';
SET @createUser = 'CONCAT("CREATE USER exporter@",@ip,"IDENTIFIED BY'mypass'")';
PREPARE smtpCreateUser FROM @createUser;
EXECUTE smtpCreateUser;";
exit
EOF
输出
$ ./create_user.sh 172.18.0.5
script received 172.18.0.5
exec received 172.18.0.5
mysql Ver 15.1 Distrib 10.2.9-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Usage: mysql [OPTIONS] [database]
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf
The following groups are read: mysql client client-server client-mariadb
The following options may be given as the first argument:
--print-defaults Print the program argument list and exit.
......and so on
我认为通常的方法是使用-e句柄运行单独的.sql脚本文件,但不幸的是,将此文件绑定到默认的mariadb容器或创建自定义映像都不可能在给定当前要求的情况下进行appraoc。 / p>
答案 0 :(得分:2)
您应该能够使用CONCAT,PREPARE生成动态SQL语句并执行它们。
<强>查询强>
SET @ip = '172.17.0.1';
SET @createUser = CONCAT(
"CREATE USER exporter@",@ip, " IDENTIFIED BY 'mypass'"
);
PREPARE smtpCreateUser FROM @createUser;
EXECUTE smtpCreateUser;
答案 1 :(得分:0)
您需要先从shell中获取变量,然后才能在查询中使用它。我认为你正在寻找类似的东西(确保从EOF中删除引号):
#!/bin/sh
docker exec -i atb-mariadb bash <<EOF
ip="${1:-127.0.0.1}"
echo mysql -uroot -pmypass
echo CREATE USER 'exporter'@'${ip}' IDENTIFIED BY 'mypass';
GRANT PROCESS, REPLICATION CLIENT ON *.* TO 'exporter'@'172.17.0.1';
GRANT SELECT ON performance_schema.* TO 'exporter'@'172.17.0.1';
SELECT user, host FROM mysql.user;
exit
EOF