Literal simple quote inside jinja2 "set" statement - jinja2

I am trying to get a mysql query to work inside a jinja2 "set" statement (salt context), as :
{% set KEY = salt.cmd.shell("mysql -u user -p'password' -D ann -h ann -B -N -e 'select T from ann.USER where NAME='key''") %}
I've been banging my head for some hours now, so if anyone has a way to achieve this, please go on!
I tried many (I mean MANY) different combination to make this work but I could not.
The best I came up with was this mysql error :
ERROR 1054 (42S22) at line 1: Unknown column 'key' in 'where clause'
Which I can reproduce on the mysql instance by not using simple quotes around "key", so for me this is indeed a quoting problem.
The Jinja2 renderer just remove the simple quote before passing the command to the shell, am I right ?
EDIT :
The sel-fish answer did the trick (thanks a lot for this) but now I realize I need to add some jinja inside the "where clause", and (I guess) because of the quoting (hell ?) the jinja variable cannot get interpreted.
Is there any way to have a correct jinja interpretation for the column name (key) inside the where clause ?
as in :
salt.cmd.shell("mysql -uroot -ppassword -h ann -D ann -B -N -e \'select T from ann.USER where NAME=\"{{ key }}\"\' 2>/dev/null; exit 0")
EDIT 2:
The second proposal to fix the jinja {{ key }} is failing with :
[salt.state :275 ][ERROR ][5947] Unable to manage file: Jinja syntax error: expected token ':', got '}'; line 53
Where line 53 is the line where I put your second proposal.
Here is the actual (sanitized) line I am using :
{% set WEBCRMKEY = salt.cmd.shell("mysql -u{{ mysql_user }} -p{{ mysql_password }} -h {{ ann_NAME|join }}.{{ full_domain }} -D ann -B -N -e \'select P from ann.USER where NAME=\"" + {{ CLIENT }} + "\"\'") %}
I guess it is now time to say welcome to quoting hell.
#sel-fish : Any other hint ? (that would save my week!)
Last word
The latest sel-fish proposition was the good one.
Thanks

Use backslash to escape single quotation.
The shell cmd like below:
salt.cmd.shell("mysql -uroot -ppassword -h ann -D ann -B -N -e \'select T from ann.USER where NAME=\"key\"\' 2>/dev/null; exit 0")
Added 2>/dev/null; exit 0 at the end of cmd, the former is to filter mysql command line tool warning message, the latter is to avoid saltstack warning.
If key is a jinja variable, then:
salt.cmd.shell("mysql -uroot -ppassword -h ann -D ann -B -N -e \'select T from ann.USER where NAME=\"" + {{ key }} + "\"\' 2>/dev/null; exit 0")
If you want to use more variables:
salt.cmd.shell("mysql -u" + mysql_user + " -p" + mysql_password + " -h" + ann_NAME + "." + full_domain + " -D ann -B -N -e \'select T from ann.USER where NAME=\"" + key + "\"\' 2>/dev/null; exit 0")

Related

How can I use a result of command as a var in a child of input

SHELL code as follow:
#!/bin/sh
..// etc
ssh root#127.0.0.1 << EOF
KEYS=$(mysql -h ${DB_IP} -u ${USERNAME} -p${PASSWORD} -P ${DB_PORT} --database bosdb -e "select a from B where id=1");
echo "123";
echo $KEYS;
... // etc
EOF
When I run this script, the output text is
123
(this is a NULL line, that means KEYS is null)
I have tried if I log in to the machine of MYSQL directly, I can get the result of the "MYSQL" command, and the echo $KEYS also shows a string of values. But when I used subcommand as input, it didn't work.
So, how can I get the value of KEYS correctly? I'd really appreciate if someone can help me

Bash contains not working

I have tried this:
http://timmurphy.org/2013/05/13/string-contains-substring-in-bash/
and none of them is working for me.
My code is:
if [[ "$MYSQLRPMSHARED" == *"$MYSQLDB"* ]]; then
echo "True"
else
echo "Failed."
fi
I get the MYSQLRPMSHARED and MYSQLDB variables via these commands:
MYSQLDB=$(mysql -uroot -p -e "select ##version" | sed 's/[^0-9.]//g')
MYSQLRPMSHARED=($(rpm -qa | grep MySQL-shared))
And their results are:
5.5.28
MySQL-shared-compat-5.5.28-1.rhel5
But when I trigger the IF, I get "Failed." When I put 5.5.28 in the IF statement instead of $MYSQLDB then I get the "True" answer instead of "Failed."
Where is the problem? I am using 3.2.25 bash.
You can delete non-numeric line and retain only version using
MYSQLDB=$(mysql -uroot -p -e "select ##version" | awk -F"[ -]" '/[0-9]/{print $1}')

UNIX SHELL SCRIPT - MYSQL issue

Below Unix shell script fails saying unexpected end of file at the mysql line before $selectg line. Not sure what mistake i am doing. Provided part of script below. Could anyone help me out.
#!/bin/bash
ip="77.299.113.81"
pass="-ptest123"
read -d '' selectg <<EOGG SELECT * FROM agstatus ; EOGG
for row in `mysql -h $ip -u root $pass "ruttt" -e "SELECT databasename FROM master.customers"`; do
rownum=$((rownum+1))
echo "Row:$row"
if [ $rownum -ne 1 ]; then
mysql -u tsadm -p'test123' -h 77.299.113.81 Csfgat << eof
$selectg
eof
fi
done
echo "done"
The end token of a here document has to be on a line by itself:
read -d '' selectg <<EOGG
SELECT * FROM agstatus;
EOGG
Alternatively, you can use a here string:
read -d '' selectg <<< "SELECT * FROM agstatus;"
Or in your specific case, a plain ol' assignment:
selectg="SELECT * FROM agstatus;"

Check if mysql user exists in bash script, getting error

I am working on a bash script to check if a mysql user exists, with following commands:
checkuser=`mysql -u $mysqlroot -p$rootpw -e "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$user_name') ;"`
lastchr=${checkuser#${checkuser%?}}
if [ $lastchr == 1 ] ; then
clear
echo "ERROR: mysql user exists"
fi
My problem is, that the terminal always gives me following feedback:
/etc/hosting: line 775: syntax error near unexpected token `('
/etc/hosting: line 775: `checkuser=`mysql -u $mysqlroot -p$rootpw -e "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$user_name') ;"`'
I tried with escaping the "(" and ")", but I didn't success.
What am I doing wrong? I tried all different kinds of escaping, single quotes, ... and it didn't help.
Kind regards
EDIT:
because maybe needed, previous lines:
echo "creating mysql user ..."
echo ""
read -p "enter username: " user_name
if [[ -z "$user_name" ]] ; then
clear
echo "username mustn't be empty!"
create_mysql_user # calls function again
fi
# check username length
if [ ${#my_user} -gt 16 ] ; then
clear
echo "ERROR: the username mustn't be longer than 16 characters"
create_mysql_user
fi
This is an old question but still searchable on internet. I would like to answer it because it doesn't have a proper answer.
To check the existence of mysql user using bash, you can use the following package jq to transform the query result to readable output as list of users in array format:
# Get list of all sql users
sql_users=$(mysql -e "SELECT USER FROM mysql.user;" | jq -rR .)
check_sql_user=$(echo "${sql_users}" | grep "username_to_check")
if [[ -z "${check_sql_user}" ]]; then
echo "No user found"
# Call create user here
else
echo "User found"
fi

Shell script if condition

I'm writing a script which runs the following command
mysql -u root -e "show databases"
and this will display a list of databases.
If this table doesn't contain a database by name "userdb", it should do the following-
if [ ... ]; then
echo "error"
exit
fi
What do i write in the if [ ... ] condition?
You can check with grep if the table name is listed. grep -q will not print anything to the console but will set the exit status according to the result (the exit status will then be checked by if).
if ! mysql -u root -e 'show databases' | grep -q '^userdb$' ; then
echo error
exit
fi
About the regular expression: '^' matches the beginning of the line and '$' matches the end of the line (to avoid a false positive for database names containing userdb, e.g. userdb2)
Try this one:
usedb=DBname
check=`mysql -u root -e "show databases" | grep $userdb`
if [ "$check" != "$userdb" ]; then
echo "error"
exit
fi
But here will be an error if line with database name contain any other information.
Try to workaround it with regexp