2012-07-12 01:00:55 +02: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-07-25 23:31:12 +02:00
|
|
|
import ConfigParser
|
2012-07-12 01:00:55 +02:00
|
|
|
try:
|
2012-07-22 19:11:39 +02:00
|
|
|
import MySQLdb
|
2012-07-12 01:00:55 +02:00
|
|
|
except ImportError:
|
2012-07-22 19:11:39 +02:00
|
|
|
mysqldb_found = False
|
|
|
|
else:
|
|
|
|
mysqldb_found = True
|
2012-07-12 01:00:55 +02:00
|
|
|
|
|
|
|
# ===========================================
|
|
|
|
# MySQL module specific support methods.
|
|
|
|
#
|
|
|
|
|
2012-07-22 19:11:39 +02:00
|
|
|
def user_exists(cursor, user, host):
|
2012-07-12 01:00:55 +02:00
|
|
|
cursor.execute("SELECT count(*) FROM user WHERE user = %s AND host = %s", (user,host))
|
|
|
|
count = cursor.fetchone()
|
|
|
|
return count[0] > 0
|
|
|
|
|
2012-07-22 19:11:39 +02:00
|
|
|
def user_add(cursor, user, host, passwd, new_priv):
|
2012-07-12 01:00:55 +02:00
|
|
|
cursor.execute("CREATE USER %s@%s IDENTIFIED BY %s", (user,host,passwd))
|
|
|
|
if new_priv is not None:
|
|
|
|
for db_table, priv in new_priv.iteritems():
|
2012-07-22 19:11:39 +02:00
|
|
|
privileges_grant(cursor, user,host,db_table,priv)
|
2012-07-12 01:00:55 +02:00
|
|
|
return True
|
|
|
|
|
2012-07-22 19:11:39 +02:00
|
|
|
def user_mod(cursor, user, host, passwd, new_priv):
|
2012-07-12 01:00:55 +02:00
|
|
|
changed = False
|
|
|
|
|
|
|
|
# Handle passwords.
|
|
|
|
if passwd is not None:
|
|
|
|
cursor.execute("SELECT password FROM user WHERE user = %s AND host = %s", (user,host))
|
|
|
|
current_pass_hash = cursor.fetchone()
|
|
|
|
cursor.execute("SELECT PASSWORD(%s)", (passwd,))
|
|
|
|
new_pass_hash = cursor.fetchone()
|
|
|
|
if current_pass_hash[0] != new_pass_hash[0]:
|
|
|
|
cursor.execute("SET PASSWORD FOR %s@%s = PASSWORD(%s)", (user,host,passwd))
|
|
|
|
changed = True
|
|
|
|
|
|
|
|
# Handle privileges.
|
|
|
|
if new_priv is not None:
|
2012-07-22 19:11:39 +02:00
|
|
|
curr_priv = privileges_get(cursor, user,host)
|
2012-07-12 01:00:55 +02: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():
|
|
|
|
if db_table not in new_priv:
|
2012-07-22 19:11:39 +02:00
|
|
|
privileges_revoke(cursor, user,host,db_table)
|
2012-07-12 01:00:55 +02:00
|
|
|
changed = True
|
|
|
|
|
|
|
|
# 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 19:11:39 +02:00
|
|
|
privileges_grant(cursor, user,host,db_table,priv)
|
2012-07-12 01:00:55 +02: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):
|
2012-07-22 19:11:39 +02:00
|
|
|
privileges_revoke(cursor, user,host,db_table)
|
|
|
|
privileges_grant(cursor, user,host,db_table,new_priv[db_table])
|
2012-07-12 01:00:55 +02:00
|
|
|
changed = True
|
|
|
|
|
|
|
|
return changed
|
|
|
|
|
2012-07-22 19:11:39 +02:00
|
|
|
def user_delete(cursor, user, host):
|
2012-07-12 01:00:55 +02:00
|
|
|
cursor.execute("DROP USER %s@%s", (user,host))
|
|
|
|
return True
|
|
|
|
|
2012-07-22 19:11:39 +02:00
|
|
|
def privileges_get(cursor, user,host):
|
2012-07-12 01:00:55 +02: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()
|
|
|
|
for grant in grants:
|
|
|
|
res = re.match("GRANT\ (.+)\ ON\ (.+)\ TO", grant[0])
|
|
|
|
if res is None:
|
2012-07-22 19:11:39 +02:00
|
|
|
module.fail_json(msg="unable to parse the MySQL grant string")
|
2012-07-12 01:00:55 +02:00
|
|
|
privileges = res.group(1).split(", ")
|
|
|
|
privileges = ['ALL' if x=='ALL PRIVILEGES' else x for x in privileges]
|
|
|
|
db = res.group(2).replace('`', '')
|
|
|
|
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(':')
|
|
|
|
output[pieces[0]] = pieces[1].upper().split(',')
|
|
|
|
|
|
|
|
if '*.*' not in output:
|
|
|
|
output['*.*'] = ['USAGE']
|
|
|
|
|
|
|
|
return output
|
|
|
|
|
2012-07-22 19:11:39 +02:00
|
|
|
def privileges_revoke(cursor, user,host,db_table):
|
2012-07-12 01:00:55 +02:00
|
|
|
query = "REVOKE ALL PRIVILEGES ON %s FROM '%s'@'%s'" % (db_table,user,host)
|
|
|
|
cursor.execute(query)
|
|
|
|
|
2012-07-22 19:11:39 +02:00
|
|
|
def privileges_grant(cursor, user,host,db_table,priv):
|
2012-07-12 01:00:55 +02:00
|
|
|
priv_string = ",".join(priv)
|
|
|
|
query = "GRANT %s ON %s TO '%s'@'%s'" % (priv_string,db_table,user,host)
|
|
|
|
cursor.execute(query)
|
|
|
|
|
2012-07-25 23:31:12 +02:00
|
|
|
def load_mycnf():
|
|
|
|
config = ConfigParser.RawConfigParser()
|
|
|
|
mycnf = os.path.expanduser('~/.my.cnf')
|
|
|
|
try:
|
2012-07-26 15:58:21 +02:00
|
|
|
config.readfp(open(mycnf))
|
2012-07-25 23:31:12 +02:00
|
|
|
creds = dict(user=config.get('client', 'user'),passwd=config.get('client', 'pass'))
|
2012-07-26 15:58:21 +02:00
|
|
|
except (ConfigParser.NoOptionError, IOError):
|
2012-07-25 23:31:12 +02:00
|
|
|
return False
|
|
|
|
return creds
|
|
|
|
|
2012-07-12 01:00:55 +02:00
|
|
|
# ===========================================
|
|
|
|
# Module execution.
|
|
|
|
#
|
|
|
|
|
2012-07-22 19:11:39 +02:00
|
|
|
def main():
|
|
|
|
module = AnsibleModule(
|
|
|
|
argument_spec = dict(
|
2012-07-25 23:31:12 +02:00
|
|
|
loginuser=dict(default=None),
|
2012-07-26 18:10:22 +02:00
|
|
|
loginpasswd=dict(default=None),
|
2012-07-22 19:11:39 +02:00
|
|
|
loginhost=dict(default="localhost"),
|
|
|
|
user=dict(required=True),
|
|
|
|
passwd=dict(default=None),
|
|
|
|
host=dict(default="localhost"),
|
|
|
|
state=dict(default="present", choices=["absent", "present"]),
|
|
|
|
priv=dict(default=None),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
user = module.params["user"]
|
|
|
|
passwd = module.params["passwd"]
|
|
|
|
host = module.params["host"]
|
|
|
|
state = module.params["state"]
|
|
|
|
priv = module.params["priv"]
|
|
|
|
|
|
|
|
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-12 01:00:55 +02:00
|
|
|
|
2012-07-25 23:31:12 +02: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.
|
|
|
|
loginpass = module.params["loginpass"]
|
|
|
|
loginuser = module.params["loginuser"]
|
|
|
|
if loginuser is None and loginpass is None:
|
|
|
|
mycnf_creds = load_mycnf()
|
|
|
|
if mycnf_creds is False:
|
|
|
|
module.fail_json(msg="incomplete login arguments passed and can't find them in ~/.my.cnf")
|
|
|
|
else:
|
|
|
|
loginuser = mycnf_creds["user"]
|
|
|
|
loginpass = mycnf_creds["passwd"]
|
|
|
|
elif loginpass is None or loginuser is None:
|
|
|
|
module.fail_json(msg="when supplying login arguments, both user and pass must be provided")
|
|
|
|
|
2012-07-12 01:00:55 +02:00
|
|
|
try:
|
2012-07-25 23:31:12 +02:00
|
|
|
db_connection = MySQLdb.connect(host=module.params["loginhost"], user=loginuser, passwd=loginpass, db="mysql")
|
2012-07-12 01:00:55 +02:00
|
|
|
cursor = db_connection.cursor()
|
|
|
|
except Exception as e:
|
2012-07-22 19:11:39 +02:00
|
|
|
module.fail_json(msg="unable to connect to database")
|
2012-07-12 01:00:55 +02:00
|
|
|
|
|
|
|
if state == "present":
|
2012-07-22 19:11:39 +02:00
|
|
|
if user_exists(cursor, user, host):
|
|
|
|
changed = user_mod(cursor, user, host, passwd, priv)
|
2012-07-12 01:00:55 +02:00
|
|
|
else:
|
|
|
|
if passwd is None:
|
2012-07-22 19:11:39 +02:00
|
|
|
module.fail_json(msg="passwd parameter required when adding a user")
|
|
|
|
changed = user_add(cursor, user, host, passwd, priv)
|
2012-07-12 01:00:55 +02:00
|
|
|
elif state == "absent":
|
2012-07-22 19:11:39 +02:00
|
|
|
if user_exists(cursor, user, host):
|
|
|
|
changed = user_delete(cursor, user, host)
|
2012-07-12 01:00:55 +02:00
|
|
|
else:
|
|
|
|
changed = False
|
2012-07-22 19:11:39 +02:00
|
|
|
module.exit_json(changed=changed, user=user)
|
2012-07-12 01:00:55 +02:00
|
|
|
|
2012-07-22 19:11:39 +02:00
|
|
|
# this is magic, see lib/ansible/module_common.py
|
|
|
|
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
|
|
|
|
main()
|