cdist/cdist/conf/type/__mysql_user/gencode-remote

89 lines
2.5 KiB
Bash
Executable File

#!/bin/sh -e
#
# 2020 Ander Punnar (ander-at-kvlt-dot-ee)
#
# This file is part of cdist.
#
# cdist is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cdist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
#
state_should="$( cat "$__object/parameter/state" )"
if [ -f "$__object/parameter/name" ]
then
name="$( cat "$__object/parameter/name" )"
else
name="$__object_id"
fi
host="$( cat "$__object/parameter/host" )"
if [ -f "$__object/parameter/password" ]
then
password="$( cat "$__object/parameter/password" )"
else
if [ "$state_should" = 'present' ]
then
echo '--password needed' >&2
exit 1
else
password=''
fi
fi
# Current state
# Not an exploerer, to avoid issues with mysql not installed YET
check_user="$( $__remote_exec "$__target_host" "mysql -B -N -e \"select user from mysql.user where user = '$name' and host = '$host'\"" )"
if [ -n "$check_user" ]
then
if [ -n "$password" ]
then
check_password="$( $__remote_exec "$__target_host" "mysql -B -N -e \"select user from mysql.user where user = '$name' and host = '$host' and password = password( '$password' )\"" )"
fi
if [ -n "$password" ] && [ -z "$check_password" ]
then
state_is='change-password'
else
state_is='present'
fi
else
state_is='absent'
fi
if [ "$state_is" = "$state_should" ]
then
exit 0
fi
if [ "$state_is" = 'absent' ] && [ "$state_should" = 'present' ]
then
echo "mysql -e 'create user \`$name\`@\`$host\` identified by \"$password\"'"
echo "create user $name@$host" >> "$__messages_out"
elif [ "$state_is" != 'absent' ] && [ "$state_should" = 'absent' ]
then
echo "mysql -e 'drop user \`$name\`@\`$host\`'"
echo "drop user $name@$host" >> "$__messages_out"
elif [ "$state_is" = 'change-password' ]
then
# this only works with MySQL 5.7.6 and later or MariaDB 10.1.20 and later
echo "mysql -e 'alter user \`$name\`@\`$host\` identified by \"$password\"'"
echo "mysql -e 'flush privileges'"
echo "change password $name@$host" >> "$__messages_out"
fi