2012-07-11 23:00:55 +00:00
|
|
|
#!/usr/bin/python
|
|
|
|
|
|
|
|
# (c) 2012, Mark Theunissen <mark.theunissen@gmail.com>
|
|
|
|
# Sponsored by Four Kitchens http://fourkitchens.com.
|
|
|
|
#
|
|
|
|
# This file is part of Ansible
|
|
|
|
#
|
|
|
|
# Ansible 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.
|
|
|
|
#
|
|
|
|
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2012-09-29 14:15:41 +00:00
|
|
|
DOCUMENTATION = '''
|
|
|
|
---
|
|
|
|
module: mysql_user
|
|
|
|
short_description: Adds or removes a user from a MySQL database.
|
|
|
|
description:
|
|
|
|
- Adds or removes a user from a MySQL database.
|
2013-11-28 02:23:03 +00:00
|
|
|
version_added: "0.6"
|
2012-09-29 14:15:41 +00:00
|
|
|
options:
|
|
|
|
name:
|
|
|
|
description:
|
|
|
|
- name of the user (role) to add or remove
|
|
|
|
required: true
|
|
|
|
default: null
|
|
|
|
password:
|
|
|
|
description:
|
|
|
|
- set the user's password
|
|
|
|
required: false
|
|
|
|
default: null
|
|
|
|
host:
|
|
|
|
description:
|
|
|
|
- the 'host' part of the MySQL username
|
|
|
|
required: false
|
|
|
|
default: localhost
|
|
|
|
login_user:
|
|
|
|
description:
|
|
|
|
- The username used to authenticate with
|
|
|
|
required: false
|
|
|
|
default: null
|
|
|
|
login_password:
|
|
|
|
description:
|
2012-09-30 10:21:35 +00:00
|
|
|
- The password used to authenticate with
|
2012-09-29 14:15:41 +00:00
|
|
|
required: false
|
|
|
|
default: null
|
|
|
|
login_host:
|
|
|
|
description:
|
|
|
|
- Host running the database
|
|
|
|
required: false
|
|
|
|
default: localhost
|
2013-09-05 15:25:34 +00:00
|
|
|
login_port:
|
|
|
|
description:
|
|
|
|
- Port of the MySQL server
|
|
|
|
required: false
|
|
|
|
default: 3306
|
2013-10-11 13:14:00 +00:00
|
|
|
version_added: '1.4'
|
2013-03-15 15:40:54 +00:00
|
|
|
login_unix_socket:
|
|
|
|
description:
|
|
|
|
- The path to a Unix domain socket for local connections
|
|
|
|
required: false
|
|
|
|
default: null
|
2012-09-29 14:15:41 +00:00
|
|
|
priv:
|
|
|
|
description:
|
2012-09-30 10:21:35 +00:00
|
|
|
- "MySQL privileges string in the format: C(db.table:priv1,priv2)"
|
2012-09-29 14:15:41 +00:00
|
|
|
required: false
|
|
|
|
default: null
|
2013-10-03 11:00:17 +00:00
|
|
|
append_privs:
|
|
|
|
description:
|
|
|
|
- Append the privileges defined by priv to the existing ones for this
|
|
|
|
user instead of overwriting existing ones.
|
|
|
|
required: false
|
|
|
|
choices: [ "yes", "no" ]
|
|
|
|
default: "no"
|
|
|
|
version_added: "1.4"
|
2012-09-29 14:15:41 +00:00
|
|
|
state:
|
|
|
|
description:
|
2013-07-29 21:48:49 +00:00
|
|
|
- Whether the user should exist. When C(absent), removes
|
|
|
|
the user.
|
2012-09-29 14:15:41 +00:00
|
|
|
required: false
|
|
|
|
default: present
|
|
|
|
choices: [ "present", "absent" ]
|
2013-07-01 10:56:04 +00:00
|
|
|
check_implicit_admin:
|
|
|
|
description:
|
|
|
|
- Check if mysql allows login as root/nopassword before trying supplied credentials.
|
|
|
|
required: false
|
|
|
|
default: false
|
2013-07-20 16:33:42 +00:00
|
|
|
version_added: "1.3"
|
2012-09-29 14:15:41 +00:00
|
|
|
notes:
|
2012-10-01 07:18:54 +00:00
|
|
|
- Requires the MySQLdb Python package on the remote host. For Ubuntu, this
|
|
|
|
is as easy as apt-get install python-mysqldb.
|
|
|
|
- Both C(login_password) and C(login_username) are required when you are
|
|
|
|
passing credentials. If none are present, the module will attempt to read
|
|
|
|
the credentials from C(~/.my.cnf), and finally fall back to using the MySQL
|
|
|
|
default login of 'root' with no password.
|
2013-03-01 22:17:00 +00:00
|
|
|
- "MySQL server installs with default login_user of 'root' and no password. To secure this user
|
2013-02-28 16:25:09 +00:00
|
|
|
as part of an idempotent playbook, you must create at least two tasks: the first must change the root user's password,
|
|
|
|
without providing any login_user/login_password details. The second must drop a ~/.my.cnf file containing
|
|
|
|
the new root credentials. Subsequent runs of the playbook will then succeed by reading the new credentials from
|
2013-03-01 22:17:00 +00:00
|
|
|
the file."
|
2013-02-28 16:25:09 +00:00
|
|
|
|
2012-10-01 07:18:54 +00:00
|
|
|
requirements: [ "ConfigParser", "MySQLdb" ]
|
2012-09-29 14:15:41 +00:00
|
|
|
author: Mark Theunissen
|
|
|
|
'''
|
|
|
|
|
2013-03-15 14:58:27 +00:00
|
|
|
EXAMPLES = """
|
2013-06-14 09:53:43 +00:00
|
|
|
# Create database user with name 'bob' and password '12345' with all database privileges
|
|
|
|
- mysql_user: name=bob password=12345 priv=*.*:ALL state=present
|
|
|
|
|
2014-01-14 12:00:25 +00:00
|
|
|
# Creates database user 'bob' and password '12345' with all database privileges and 'WITH GRANT OPTION'
|
|
|
|
- mysql_user: name=bob password=12345 priv=*.*:ALL,GRANT state=present
|
|
|
|
|
2013-06-14 09:53:43 +00:00
|
|
|
# Ensure no user named 'sally' exists, also passing in the auth credentials.
|
|
|
|
- mysql_user: login_user=root login_password=123456 name=sally state=absent
|
|
|
|
|
2014-05-20 18:41:18 +00:00
|
|
|
# Specify grants composed of more than one word
|
|
|
|
- mysql_user: name=replication password=12345 priv=*.*:"REPLICATION CLIENT" state=present
|
|
|
|
|
2013-06-14 09:53:43 +00:00
|
|
|
# Example privileges string format
|
|
|
|
mydb.*:INSERT,UPDATE/anotherdb.*:SELECT/yetanotherdb.*:ALL
|
|
|
|
|
|
|
|
# Example using login_unix_socket to connect to server
|
|
|
|
- mysql_user: name=root password=abc123 login_unix_socket=/var/run/mysqld/mysqld.sock
|
|
|
|
|
2013-03-15 14:58:27 +00:00
|
|
|
# Example .my.cnf file for setting the root password
|
|
|
|
# Note: don't use quotes around the password, because the mysql_user module
|
|
|
|
# will include them in the password but the mysql client will not
|
2013-06-14 09:53:43 +00:00
|
|
|
|
2013-03-15 14:58:27 +00:00
|
|
|
[client]
|
|
|
|
user=root
|
|
|
|
password=n<_665{vS43y
|
|
|
|
"""
|
|
|
|
|
2012-07-25 21:31:12 +00:00
|
|
|
import ConfigParser
|
2013-03-15 14:58:27 +00:00
|
|
|
import getpass
|
2013-10-18 21:42:40 +00:00
|
|
|
import tempfile
|
2012-07-11 23:00:55 +00:00
|
|
|
try:
|
2012-07-22 17:11:39 +00:00
|
|
|
import MySQLdb
|
2012-07-11 23:00:55 +00:00
|
|
|
except ImportError:
|
2012-07-22 17:11:39 +00:00
|
|
|
mysqldb_found = False
|
|
|
|
else:
|
|
|
|
mysqldb_found = True
|
2012-07-11 23:00:55 +00:00
|
|
|
|
|
|
|
# ===========================================
|
|
|
|
# MySQL module specific support methods.
|
|
|
|
#
|
|
|
|
|
2012-07-22 17:11:39 +00:00
|
|
|
def user_exists(cursor, user, host):
|
2012-07-11 23:00:55 +00:00
|
|
|
cursor.execute("SELECT count(*) FROM user WHERE user = %s AND host = %s", (user,host))
|
|
|
|
count = cursor.fetchone()
|
|
|
|
return count[0] > 0
|
|
|
|
|
2012-07-30 22:15:24 +00:00
|
|
|
def user_add(cursor, user, host, password, new_priv):
|
|
|
|
cursor.execute("CREATE USER %s@%s IDENTIFIED BY %s", (user,host,password))
|
2012-07-11 23:00:55 +00:00
|
|
|
if new_priv is not None:
|
|
|
|
for db_table, priv in new_priv.iteritems():
|
2012-07-22 17:11:39 +00:00
|
|
|
privileges_grant(cursor, user,host,db_table,priv)
|
2012-07-11 23:00:55 +00:00
|
|
|
return True
|
|
|
|
|
2013-10-03 11:00:17 +00:00
|
|
|
def user_mod(cursor, user, host, password, new_priv, append_privs):
|
2012-07-11 23:00:55 +00:00
|
|
|
changed = False
|
Only revoke GRANT OPTION when user actually has it
When revoking privileges from a user, the GRANT OPTION is always
revoked, even if the user doesn't have it. If the user exists, this
doesn't give an error, but if the user doesn't exist, it does:
mysql> GRANT ALL ON test.* TO 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE ALL ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
ERROR 1141 (42000): There is no such grant defined for user 'test' on
host 'localhost'
Additionally, in MySQL 5.6 this breaks replication because of
http://bugs.mysql.com/bug.php?id=68892.
Rather than revoking the GRANT OPTION and catching the error, check if
the user actually has it and only revoke it when he does.
2013-07-23 11:00:29 +00:00
|
|
|
grant_option = False
|
2012-07-11 23:00:55 +00:00
|
|
|
|
|
|
|
# Handle passwords.
|
2012-07-30 22:15:24 +00:00
|
|
|
if password is not None:
|
2012-07-11 23:00:55 +00:00
|
|
|
cursor.execute("SELECT password FROM user WHERE user = %s AND host = %s", (user,host))
|
|
|
|
current_pass_hash = cursor.fetchone()
|
2012-07-30 22:15:24 +00:00
|
|
|
cursor.execute("SELECT PASSWORD(%s)", (password,))
|
2012-07-11 23:00:55 +00:00
|
|
|
new_pass_hash = cursor.fetchone()
|
|
|
|
if current_pass_hash[0] != new_pass_hash[0]:
|
2012-07-30 22:15:24 +00:00
|
|
|
cursor.execute("SET PASSWORD FOR %s@%s = PASSWORD(%s)", (user,host,password))
|
2012-07-11 23:00:55 +00:00
|
|
|
changed = True
|
|
|
|
|
|
|
|
# Handle privileges.
|
|
|
|
if new_priv is not None:
|
2012-07-22 17:11:39 +00:00
|
|
|
curr_priv = privileges_get(cursor, user,host)
|
2012-07-11 23:00:55 +00:00
|
|
|
|
|
|
|
# If the user has privileges on a db.table that doesn't appear at all in
|
|
|
|
# the new specification, then revoke all privileges on it.
|
|
|
|
for db_table, priv in curr_priv.iteritems():
|
Only revoke GRANT OPTION when user actually has it
When revoking privileges from a user, the GRANT OPTION is always
revoked, even if the user doesn't have it. If the user exists, this
doesn't give an error, but if the user doesn't exist, it does:
mysql> GRANT ALL ON test.* TO 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE ALL ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
ERROR 1141 (42000): There is no such grant defined for user 'test' on
host 'localhost'
Additionally, in MySQL 5.6 this breaks replication because of
http://bugs.mysql.com/bug.php?id=68892.
Rather than revoking the GRANT OPTION and catching the error, check if
the user actually has it and only revoke it when he does.
2013-07-23 11:00:29 +00:00
|
|
|
# If the user has the GRANT OPTION on a db.table, revoke it first.
|
|
|
|
if "GRANT" in priv:
|
|
|
|
grant_option = True
|
2012-07-11 23:00:55 +00:00
|
|
|
if db_table not in new_priv:
|
2013-10-03 11:00:17 +00:00
|
|
|
if user != "root" and "PROXY" not in priv and not append_privs:
|
Only revoke GRANT OPTION when user actually has it
When revoking privileges from a user, the GRANT OPTION is always
revoked, even if the user doesn't have it. If the user exists, this
doesn't give an error, but if the user doesn't exist, it does:
mysql> GRANT ALL ON test.* TO 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE ALL ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
ERROR 1141 (42000): There is no such grant defined for user 'test' on
host 'localhost'
Additionally, in MySQL 5.6 this breaks replication because of
http://bugs.mysql.com/bug.php?id=68892.
Rather than revoking the GRANT OPTION and catching the error, check if
the user actually has it and only revoke it when he does.
2013-07-23 11:00:29 +00:00
|
|
|
privileges_revoke(cursor, user,host,db_table,grant_option)
|
2013-06-11 12:37:30 +00:00
|
|
|
changed = True
|
2012-07-11 23:00:55 +00:00
|
|
|
|
|
|
|
# If the user doesn't currently have any privileges on a db.table, then
|
|
|
|
# we can perform a straight grant operation.
|
|
|
|
for db_table, priv in new_priv.iteritems():
|
|
|
|
if db_table not in curr_priv:
|
2012-07-22 17:11:39 +00:00
|
|
|
privileges_grant(cursor, user,host,db_table,priv)
|
2012-07-11 23:00:55 +00:00
|
|
|
changed = True
|
|
|
|
|
|
|
|
# If the db.table specification exists in both the user's current privileges
|
|
|
|
# and in the new privileges, then we need to see if there's a difference.
|
|
|
|
db_table_intersect = set(new_priv.keys()) & set(curr_priv.keys())
|
|
|
|
for db_table in db_table_intersect:
|
|
|
|
priv_diff = set(new_priv[db_table]) ^ set(curr_priv[db_table])
|
|
|
|
if (len(priv_diff) > 0):
|
Only revoke GRANT OPTION when user actually has it
When revoking privileges from a user, the GRANT OPTION is always
revoked, even if the user doesn't have it. If the user exists, this
doesn't give an error, but if the user doesn't exist, it does:
mysql> GRANT ALL ON test.* TO 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE ALL ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
ERROR 1141 (42000): There is no such grant defined for user 'test' on
host 'localhost'
Additionally, in MySQL 5.6 this breaks replication because of
http://bugs.mysql.com/bug.php?id=68892.
Rather than revoking the GRANT OPTION and catching the error, check if
the user actually has it and only revoke it when he does.
2013-07-23 11:00:29 +00:00
|
|
|
privileges_revoke(cursor, user,host,db_table,grant_option)
|
2012-07-22 17:11:39 +00:00
|
|
|
privileges_grant(cursor, user,host,db_table,new_priv[db_table])
|
2012-07-11 23:00:55 +00:00
|
|
|
changed = True
|
|
|
|
|
|
|
|
return changed
|
|
|
|
|
2012-07-22 17:11:39 +00:00
|
|
|
def user_delete(cursor, user, host):
|
2012-07-11 23:00:55 +00:00
|
|
|
cursor.execute("DROP USER %s@%s", (user,host))
|
|
|
|
return True
|
|
|
|
|
2012-07-22 17:11:39 +00:00
|
|
|
def privileges_get(cursor, user,host):
|
2012-07-11 23:00:55 +00:00
|
|
|
""" MySQL doesn't have a better method of getting privileges aside from the
|
|
|
|
SHOW GRANTS query syntax, which requires us to then parse the returned string.
|
|
|
|
Here's an example of the string that is returned from MySQL:
|
|
|
|
|
|
|
|
GRANT USAGE ON *.* TO 'user'@'localhost' IDENTIFIED BY 'pass';
|
|
|
|
|
|
|
|
This function makes the query and returns a dictionary containing the results.
|
|
|
|
The dictionary format is the same as that returned by privileges_unpack() below.
|
|
|
|
"""
|
|
|
|
output = {}
|
|
|
|
cursor.execute("SHOW GRANTS FOR %s@%s", (user,host))
|
|
|
|
grants = cursor.fetchall()
|
2012-11-15 01:02:39 +00:00
|
|
|
|
|
|
|
def pick(x):
|
|
|
|
if x == 'ALL PRIVILEGES':
|
|
|
|
return 'ALL'
|
|
|
|
else:
|
|
|
|
return x
|
|
|
|
|
2012-07-11 23:00:55 +00:00
|
|
|
for grant in grants:
|
2012-10-24 12:32:49 +00:00
|
|
|
res = re.match("GRANT (.+) ON (.+) TO '.+'@'.+'( IDENTIFIED BY PASSWORD '.+')? ?(.*)", grant[0])
|
2012-07-11 23:00:55 +00:00
|
|
|
if res is None:
|
2012-07-22 17:11:39 +00:00
|
|
|
module.fail_json(msg="unable to parse the MySQL grant string")
|
2012-07-11 23:00:55 +00:00
|
|
|
privileges = res.group(1).split(", ")
|
2012-11-15 01:02:39 +00:00
|
|
|
privileges = [ pick(x) for x in privileges]
|
2012-10-24 12:32:49 +00:00
|
|
|
if "WITH GRANT OPTION" in res.group(4):
|
2012-10-31 00:42:07 +00:00
|
|
|
privileges.append('GRANT')
|
2013-08-26 16:16:34 +00:00
|
|
|
db = res.group(2)
|
2012-07-11 23:00:55 +00:00
|
|
|
output[db] = privileges
|
|
|
|
return output
|
|
|
|
|
|
|
|
def privileges_unpack(priv):
|
|
|
|
""" Take a privileges string, typically passed as a parameter, and unserialize
|
|
|
|
it into a dictionary, the same format as privileges_get() above. We have this
|
|
|
|
custom format to avoid using YAML/JSON strings inside YAML playbooks. Example
|
|
|
|
of a privileges string:
|
|
|
|
|
|
|
|
mydb.*:INSERT,UPDATE/anotherdb.*:SELECT/yetanother.*:ALL
|
|
|
|
|
|
|
|
The privilege USAGE stands for no privileges, so we add that in on *.* if it's
|
|
|
|
not specified in the string, as MySQL will always provide this by default.
|
|
|
|
"""
|
|
|
|
output = {}
|
|
|
|
for item in priv.split('/'):
|
|
|
|
pieces = item.split(':')
|
2014-01-23 15:02:17 +00:00
|
|
|
if '.' in pieces[0]:
|
2013-09-06 14:28:30 +00:00
|
|
|
pieces[0] = pieces[0].split('.')
|
|
|
|
for idx, piece in enumerate(pieces):
|
|
|
|
if pieces[0][idx] != "*":
|
|
|
|
pieces[0][idx] = "`" + pieces[0][idx] + "`"
|
|
|
|
pieces[0] = '.'.join(pieces[0])
|
2013-08-26 16:16:34 +00:00
|
|
|
|
2012-07-11 23:00:55 +00:00
|
|
|
output[pieces[0]] = pieces[1].upper().split(',')
|
|
|
|
|
|
|
|
if '*.*' not in output:
|
|
|
|
output['*.*'] = ['USAGE']
|
|
|
|
|
|
|
|
return output
|
|
|
|
|
Only revoke GRANT OPTION when user actually has it
When revoking privileges from a user, the GRANT OPTION is always
revoked, even if the user doesn't have it. If the user exists, this
doesn't give an error, but if the user doesn't exist, it does:
mysql> GRANT ALL ON test.* TO 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE ALL ON test.* FROM 'test'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> REVOKE GRANT OPTION ON test.* FROM 'test'@'localhost';
ERROR 1141 (42000): There is no such grant defined for user 'test' on
host 'localhost'
Additionally, in MySQL 5.6 this breaks replication because of
http://bugs.mysql.com/bug.php?id=68892.
Rather than revoking the GRANT OPTION and catching the error, check if
the user actually has it and only revoke it when he does.
2013-07-23 11:00:29 +00:00
|
|
|
def privileges_revoke(cursor, user,host,db_table,grant_option):
|
|
|
|
if grant_option:
|
|
|
|
query = "REVOKE GRANT OPTION ON %s FROM '%s'@'%s'" % (db_table,user,host)
|
|
|
|
cursor.execute(query)
|
2012-07-11 23:00:55 +00:00
|
|
|
query = "REVOKE ALL PRIVILEGES ON %s FROM '%s'@'%s'" % (db_table,user,host)
|
|
|
|
cursor.execute(query)
|
|
|
|
|
2012-07-22 17:11:39 +00:00
|
|
|
def privileges_grant(cursor, user,host,db_table,priv):
|
2012-10-18 17:27:18 +00:00
|
|
|
|
|
|
|
priv_string = ",".join(filter(lambda x: x != 'GRANT', priv))
|
2012-07-11 23:00:55 +00:00
|
|
|
query = "GRANT %s ON %s TO '%s'@'%s'" % (priv_string,db_table,user,host)
|
2012-10-18 17:27:18 +00:00
|
|
|
if 'GRANT' in priv:
|
2012-10-31 00:42:07 +00:00
|
|
|
query = query + " WITH GRANT OPTION"
|
2012-07-11 23:00:55 +00:00
|
|
|
cursor.execute(query)
|
|
|
|
|
2013-03-25 13:53:04 +00:00
|
|
|
|
|
|
|
def strip_quotes(s):
|
|
|
|
""" Remove surrounding single or double quotes
|
|
|
|
|
|
|
|
>>> print strip_quotes('hello')
|
|
|
|
hello
|
|
|
|
>>> print strip_quotes('"hello"')
|
|
|
|
hello
|
|
|
|
>>> print strip_quotes("'hello'")
|
|
|
|
hello
|
|
|
|
>>> print strip_quotes("'hello")
|
|
|
|
'hello
|
|
|
|
|
|
|
|
"""
|
|
|
|
single_quote = "'"
|
|
|
|
double_quote = '"'
|
|
|
|
|
|
|
|
if s.startswith(single_quote) and s.endswith(single_quote):
|
|
|
|
s = s.strip(single_quote)
|
|
|
|
elif s.startswith(double_quote) and s.endswith(double_quote):
|
|
|
|
s = s.strip(double_quote)
|
|
|
|
return s
|
|
|
|
|
|
|
|
|
|
|
|
def config_get(config, section, option):
|
|
|
|
""" Calls ConfigParser.get and strips quotes
|
|
|
|
|
|
|
|
See: http://dev.mysql.com/doc/refman/5.0/en/option-files.html
|
|
|
|
"""
|
|
|
|
return strip_quotes(config.get(section, option))
|
|
|
|
|
|
|
|
|
2013-10-18 21:42:40 +00:00
|
|
|
def _safe_cnf_load(config, path):
|
|
|
|
|
|
|
|
data = {'user':'', 'password':''}
|
|
|
|
|
|
|
|
# read in user/pass
|
|
|
|
f = open(path, 'r')
|
|
|
|
for line in f.readlines():
|
|
|
|
line = line.strip()
|
|
|
|
if line.startswith('user='):
|
|
|
|
data['user'] = line.split('=', 1)[1].strip()
|
|
|
|
if line.startswith('password=') or line.startswith('pass='):
|
|
|
|
data['password'] = line.split('=', 1)[1].strip()
|
|
|
|
f.close()
|
|
|
|
|
|
|
|
# write out a new cnf file with only user/pass
|
|
|
|
fh, newpath = tempfile.mkstemp(prefix=path + '.')
|
|
|
|
f = open(newpath, 'wb')
|
|
|
|
f.write('[client]\n')
|
|
|
|
f.write('user=%s\n' % data['user'])
|
|
|
|
f.write('password=%s\n' % data['password'])
|
|
|
|
f.close()
|
|
|
|
|
|
|
|
config.readfp(open(newpath))
|
|
|
|
os.remove(newpath)
|
|
|
|
return config
|
|
|
|
|
2012-07-25 21:31:12 +00:00
|
|
|
def load_mycnf():
|
|
|
|
config = ConfigParser.RawConfigParser()
|
|
|
|
mycnf = os.path.expanduser('~/.my.cnf')
|
2012-07-26 16:30:22 +00:00
|
|
|
if not os.path.exists(mycnf):
|
|
|
|
return False
|
2012-07-25 21:31:12 +00:00
|
|
|
try:
|
2012-07-26 13:58:21 +00:00
|
|
|
config.readfp(open(mycnf))
|
2013-02-26 22:27:23 +00:00
|
|
|
except (IOError):
|
|
|
|
return False
|
2013-10-18 21:42:40 +00:00
|
|
|
except:
|
|
|
|
config = _safe_cnf_load(config, mycnf)
|
|
|
|
|
2013-02-26 22:27:23 +00:00
|
|
|
# We support two forms of passwords in .my.cnf, both pass= and password=,
|
|
|
|
# as these are both supported by MySQL.
|
|
|
|
try:
|
2013-03-25 13:53:04 +00:00
|
|
|
passwd = config_get(config, 'client', 'password')
|
2013-02-26 22:27:23 +00:00
|
|
|
except (ConfigParser.NoOptionError):
|
|
|
|
try:
|
2013-03-25 13:53:04 +00:00
|
|
|
passwd = config_get(config, 'client', 'pass')
|
2013-02-26 22:27:23 +00:00
|
|
|
except (ConfigParser.NoOptionError):
|
|
|
|
return False
|
2013-03-15 14:58:27 +00:00
|
|
|
|
|
|
|
# If .my.cnf doesn't specify a user, default to user login name
|
2013-02-26 22:27:23 +00:00
|
|
|
try:
|
2013-03-25 13:53:04 +00:00
|
|
|
user = config_get(config, 'client', 'user')
|
2013-02-26 22:27:23 +00:00
|
|
|
except (ConfigParser.NoOptionError):
|
2013-03-15 14:58:27 +00:00
|
|
|
user = getpass.getuser()
|
|
|
|
creds = dict(user=user,passwd=passwd)
|
2012-07-25 21:31:12 +00:00
|
|
|
return creds
|
|
|
|
|
2013-07-01 10:56:04 +00:00
|
|
|
def connect(module, login_user, login_password):
|
|
|
|
if module.params["login_unix_socket"]:
|
|
|
|
db_connection = MySQLdb.connect(host=module.params["login_host"], unix_socket=module.params["login_unix_socket"], user=login_user, passwd=login_password, db="mysql")
|
|
|
|
else:
|
2013-09-05 15:25:34 +00:00
|
|
|
db_connection = MySQLdb.connect(host=module.params["login_host"], port=int(module.params["login_port"]), user=login_user, passwd=login_password, db="mysql")
|
2013-07-01 10:56:04 +00:00
|
|
|
return db_connection.cursor()
|
|
|
|
|
2012-07-11 23:00:55 +00:00
|
|
|
# ===========================================
|
|
|
|
# Module execution.
|
|
|
|
#
|
|
|
|
|
2012-07-22 17:11:39 +00:00
|
|
|
def main():
|
|
|
|
module = AnsibleModule(
|
|
|
|
argument_spec = dict(
|
2012-07-30 22:15:24 +00:00
|
|
|
login_user=dict(default=None),
|
|
|
|
login_password=dict(default=None),
|
|
|
|
login_host=dict(default="localhost"),
|
2013-09-05 15:25:34 +00:00
|
|
|
login_port=dict(default="3306"),
|
2012-08-03 10:35:18 +00:00
|
|
|
login_unix_socket=dict(default=None),
|
2012-08-01 04:21:36 +00:00
|
|
|
user=dict(required=True, aliases=['name']),
|
2012-07-30 22:15:24 +00:00
|
|
|
password=dict(default=None),
|
2012-07-22 17:11:39 +00:00
|
|
|
host=dict(default="localhost"),
|
|
|
|
state=dict(default="present", choices=["absent", "present"]),
|
|
|
|
priv=dict(default=None),
|
2013-10-03 11:00:17 +00:00
|
|
|
append_privs=dict(type="bool", default="no"),
|
2013-07-01 10:56:04 +00:00
|
|
|
check_implicit_admin=dict(default=False),
|
2012-07-22 17:11:39 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
user = module.params["user"]
|
2012-07-30 22:15:24 +00:00
|
|
|
password = module.params["password"]
|
2012-07-22 17:11:39 +00:00
|
|
|
host = module.params["host"]
|
|
|
|
state = module.params["state"]
|
|
|
|
priv = module.params["priv"]
|
2013-07-01 10:56:04 +00:00
|
|
|
check_implicit_admin = module.params['check_implicit_admin']
|
2013-10-03 11:00:17 +00:00
|
|
|
append_privs = module.boolean(module.params["append_privs"])
|
2012-07-22 17:11:39 +00:00
|
|
|
|
|
|
|
if not mysqldb_found:
|
|
|
|
module.fail_json(msg="the python mysqldb module is required")
|
|
|
|
|
|
|
|
if priv is not None:
|
|
|
|
try:
|
|
|
|
priv = privileges_unpack(priv)
|
|
|
|
except:
|
|
|
|
module.fail_json(msg="invalid privileges string")
|
2012-07-11 23:00:55 +00:00
|
|
|
|
2012-07-25 21:31:12 +00:00
|
|
|
# Either the caller passes both a username and password with which to connect to
|
|
|
|
# mysql, or they pass neither and allow this module to read the credentials from
|
|
|
|
# ~/.my.cnf.
|
2012-07-30 22:15:24 +00:00
|
|
|
login_password = module.params["login_password"]
|
|
|
|
login_user = module.params["login_user"]
|
|
|
|
if login_user is None and login_password is None:
|
2012-07-25 21:31:12 +00:00
|
|
|
mycnf_creds = load_mycnf()
|
|
|
|
if mycnf_creds is False:
|
2012-07-30 22:15:24 +00:00
|
|
|
login_user = "root"
|
|
|
|
login_password = ""
|
2012-07-25 21:31:12 +00:00
|
|
|
else:
|
2012-07-30 22:15:24 +00:00
|
|
|
login_user = mycnf_creds["user"]
|
2013-02-28 19:55:22 +00:00
|
|
|
login_password = mycnf_creds["passwd"]
|
2012-07-30 22:15:24 +00:00
|
|
|
elif login_password is None or login_user is None:
|
|
|
|
module.fail_json(msg="when supplying login arguments, both login_user and login_password must be provided")
|
2012-07-25 21:31:12 +00:00
|
|
|
|
2013-07-01 10:56:04 +00:00
|
|
|
cursor = None
|
2012-07-11 23:00:55 +00:00
|
|
|
try:
|
2013-07-01 10:56:04 +00:00
|
|
|
if check_implicit_admin:
|
|
|
|
try:
|
|
|
|
cursor = connect(module, 'root', '')
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
|
|
|
|
if not cursor:
|
|
|
|
cursor = connect(module, login_user, login_password)
|
2012-11-09 13:28:21 +00:00
|
|
|
except Exception, e:
|
2012-07-30 22:15:24 +00:00
|
|
|
module.fail_json(msg="unable to connect to database, check login_user and login_password are correct or ~/.my.cnf has the credentials")
|
2012-07-11 23:00:55 +00:00
|
|
|
|
|
|
|
if state == "present":
|
2012-07-22 17:11:39 +00:00
|
|
|
if user_exists(cursor, user, host):
|
2013-10-03 11:00:17 +00:00
|
|
|
changed = user_mod(cursor, user, host, password, priv, append_privs)
|
2012-07-11 23:00:55 +00:00
|
|
|
else:
|
2012-07-30 22:15:24 +00:00
|
|
|
if password is None:
|
|
|
|
module.fail_json(msg="password parameter required when adding a user")
|
|
|
|
changed = user_add(cursor, user, host, password, priv)
|
2012-07-11 23:00:55 +00:00
|
|
|
elif state == "absent":
|
2012-07-22 17:11:39 +00:00
|
|
|
if user_exists(cursor, user, host):
|
|
|
|
changed = user_delete(cursor, user, host)
|
2012-07-11 23:00:55 +00:00
|
|
|
else:
|
|
|
|
changed = False
|
2012-07-22 17:11:39 +00:00
|
|
|
module.exit_json(changed=changed, user=user)
|
2012-07-11 23:00:55 +00:00
|
|
|
|
2013-12-02 20:13:49 +00:00
|
|
|
# import module snippets
|
2013-12-02 20:11:23 +00:00
|
|
|
from ansible.module_utils.basic import *
|
2012-07-22 17:11:39 +00:00
|
|
|
main()
|