Check if MySQL User Exists on Command Line (and in Puppet)

If you are using Linux, there is simple way to check if a user exists in MySQL:

echo `mysql -u root -p[your root password] -e ‘use mysql; SELECT user FROM user;’` | grep ‘[user name]

Executing this command will exit with return code 0 if the user exists and otherwise exit with 1.

This is very useful for building puppet scripts. The following execution will create a user if it doesn’t exist.

exec { “add user if not exist”:

unless => “echo `mysql -u root -p[psw] -e ‘use mysql; SELECT user FROM user;’` | grep ‘[username]‘”,
path => [“/bin”, “/usr/bin”],
command => “mysql -u root -p$mysql_password -e \”[Create User/Grant Rights Here]\””,
require => Service[“mysqld”],
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s