2012-07-26 17:02:28 +02:00
|
|
|
#!/usr/bin/python
|
2012-08-03 03:29:10 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
2012-07-26 17:02:28 +02:00
|
|
|
|
|
|
|
# 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-08-21 21:25:19 +02:00
|
|
|
import re
|
|
|
|
|
2012-07-26 17:02:28 +02:00
|
|
|
try:
|
|
|
|
import psycopg2
|
|
|
|
except ImportError:
|
|
|
|
postgresqldb_found = False
|
|
|
|
else:
|
|
|
|
postgresqldb_found = True
|
|
|
|
|
|
|
|
# ===========================================
|
|
|
|
# PostgreSQL module specific support methods.
|
|
|
|
#
|
|
|
|
|
|
|
|
|
|
|
|
def user_exists(cursor, user):
|
|
|
|
query = "SELECT rolname FROM pg_roles WHERE rolname=%(user)s"
|
|
|
|
cursor.execute(query, {'user': user})
|
|
|
|
return cursor.rowcount > 0
|
|
|
|
|
|
|
|
|
2012-08-21 18:20:16 +02:00
|
|
|
def user_add(cursor, user, password):
|
2012-07-26 17:02:28 +02:00
|
|
|
"""Create a new user with write access to the database"""
|
2012-07-29 18:47:44 +02:00
|
|
|
query = "CREATE USER %(user)s with PASSWORD '%(password)s'"
|
|
|
|
cursor.execute(query % {"user": user, "password": password})
|
2012-07-26 17:02:28 +02:00
|
|
|
return True
|
|
|
|
|
2012-08-21 18:20:16 +02:00
|
|
|
def user_chpass(cursor, user, password):
|
|
|
|
"""Change user password"""
|
2012-07-26 17:02:28 +02:00
|
|
|
changed = False
|
|
|
|
|
|
|
|
# Handle passwords.
|
2012-07-29 18:47:44 +02:00
|
|
|
if password is not None:
|
2012-07-26 17:02:28 +02:00
|
|
|
select = "SELECT rolpassword FROM pg_authid where rolname=%(user)s"
|
|
|
|
cursor.execute(select, {"user": user})
|
|
|
|
current_pass_hash = cursor.fetchone()[0]
|
|
|
|
# Not sure how to hash the new password, so we just initiate the
|
|
|
|
# change and check if the hash changed
|
2012-07-29 18:47:44 +02:00
|
|
|
alter = "ALTER USER %(user)s WITH PASSWORD '%(password)s'"
|
|
|
|
cursor.execute(alter % {"user": user, "password": password})
|
2012-07-26 17:02:28 +02:00
|
|
|
cursor.execute(select, {"user": user})
|
|
|
|
new_pass_hash = cursor.fetchone()[0]
|
|
|
|
if current_pass_hash != new_pass_hash:
|
|
|
|
changed = True
|
|
|
|
|
|
|
|
return changed
|
|
|
|
|
2012-08-21 18:20:16 +02:00
|
|
|
def user_delete(cursor, user):
|
|
|
|
"""Try to remove a user. Returns True if successful otherwise False"""
|
|
|
|
cursor.execute("SAVEPOINT ansible_pgsql_user_delete")
|
|
|
|
try:
|
|
|
|
cursor.execute("DROP USER %s" % user)
|
|
|
|
except:
|
|
|
|
cursor.execute("ROLLBACK TO SAVEPOINT ansible_pgsql_user_delete")
|
|
|
|
cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
|
|
|
|
return False
|
|
|
|
|
|
|
|
cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
|
|
|
|
return True
|
|
|
|
|
|
|
|
def has_table_privilege(cursor, user, table, priv):
|
|
|
|
query = 'SELECT has_table_privilege(%s, %s, %s)'
|
2012-08-21 21:25:19 +02:00
|
|
|
cursor.execute(query, (user, table, priv))
|
2012-08-21 18:20:16 +02:00
|
|
|
return cursor.fetchone()[0]
|
|
|
|
|
2012-08-21 21:25:19 +02:00
|
|
|
def get_table_privileges(cursor, user, table):
|
|
|
|
if '.' in table:
|
|
|
|
schema, table = table.split('.', 1)
|
|
|
|
else:
|
|
|
|
schema = 'public'
|
|
|
|
query = '''SELECT privilege_type FROM information_schema.role_table_grants
|
|
|
|
WHERE grantee=%s AND table_name=%s AND table_schema=%s'''
|
|
|
|
cursor.execute(query, (user, table, schema))
|
|
|
|
return set([x[0] for x in cursor.fetchall()])
|
|
|
|
|
|
|
|
|
2012-08-21 18:20:16 +02:00
|
|
|
def grant_table_privilege(cursor, user, table, priv):
|
2012-08-21 21:25:19 +02:00
|
|
|
prev_priv = get_table_privileges(cursor, user, table)
|
2012-08-21 18:20:16 +02:00
|
|
|
query = 'GRANT %s ON TABLE %s TO %s' % (priv, table, user)
|
|
|
|
cursor.execute(query)
|
2012-08-21 21:25:19 +02:00
|
|
|
curr_priv = get_table_privileges(cursor, user, table)
|
|
|
|
return len(curr_priv) > len(prev_priv)
|
2012-08-21 18:20:16 +02:00
|
|
|
|
|
|
|
def revoke_table_privilege(cursor, user, table, priv):
|
2012-08-21 21:25:19 +02:00
|
|
|
prev_priv = get_table_privileges(cursor, user, table)
|
2012-08-21 18:20:16 +02:00
|
|
|
query = 'REVOKE %s ON TABLE %s FROM %s' % (priv, table, user)
|
|
|
|
cursor.execute(query)
|
2012-08-21 21:25:19 +02:00
|
|
|
curr_priv = get_table_privileges(cursor, user, table)
|
|
|
|
return len(curr_priv) < len(prev_priv)
|
2012-08-21 18:20:16 +02:00
|
|
|
|
|
|
|
|
2012-08-21 21:25:19 +02:00
|
|
|
def get_database_privileges(cursor, user, db):
|
|
|
|
priv_map = {
|
|
|
|
'C':'CREATE',
|
|
|
|
'T':'TEMPORARY',
|
|
|
|
'c':'CONNECT',
|
|
|
|
}
|
|
|
|
query = 'SELECT datacl FROM pg_database WHERE datname = %s'
|
|
|
|
cursor.execute(query, (db,))
|
|
|
|
datacl = cursor.fetchone()[0]
|
|
|
|
r = re.search('%s=(C?T?c?)/[a-z]+\,?' % user, datacl)
|
|
|
|
if r is None:
|
|
|
|
return []
|
|
|
|
o = []
|
|
|
|
for v in r.group(1):
|
|
|
|
o.append(priv_map[v])
|
|
|
|
return o
|
|
|
|
|
2012-08-21 18:20:16 +02:00
|
|
|
def has_database_privilege(cursor, user, db, priv):
|
|
|
|
query = 'SELECT has_database_privilege(%s, %s, %s)'
|
2012-08-21 21:25:19 +02:00
|
|
|
cursor.execute(query, (user, db, priv))
|
2012-08-21 18:20:16 +02:00
|
|
|
return cursor.fetchone()[0]
|
|
|
|
|
|
|
|
def grant_database_privilege(cursor, user, db, priv):
|
2012-08-21 21:25:19 +02:00
|
|
|
prev_priv = get_database_privileges(cursor, user, db)
|
2012-08-21 18:20:16 +02:00
|
|
|
query = 'GRANT %s ON DATABASE %s TO %s' % (priv, db, user)
|
|
|
|
cursor.execute(query)
|
2012-08-21 21:25:19 +02:00
|
|
|
curr_priv = get_database_privileges(cursor, user, db)
|
|
|
|
return len(curr_priv) > len(prev_priv)
|
2012-07-26 17:02:28 +02:00
|
|
|
|
2012-08-21 18:20:16 +02:00
|
|
|
def revoke_database_privilege(cursor, user, db, priv):
|
2012-08-21 21:25:19 +02:00
|
|
|
prev_priv = get_database_privileges(cursor, user, db)
|
2012-08-21 18:20:16 +02:00
|
|
|
query = 'REVOKE %s ON DATABASE %s FROM %s' % (priv, db, user)
|
|
|
|
cursor.execute(query)
|
2012-08-21 21:25:19 +02:00
|
|
|
curr_priv = get_database_privileges(cursor, user, db)
|
|
|
|
return len(curr_priv) < len(prev_priv)
|
2012-07-26 17:02:28 +02:00
|
|
|
|
2012-08-21 18:20:16 +02:00
|
|
|
def revoke_privileges(cursor, user, privs):
|
|
|
|
if privs is None:
|
|
|
|
return False
|
2012-07-26 17:02:28 +02:00
|
|
|
|
2012-08-21 18:20:16 +02:00
|
|
|
changed = False
|
|
|
|
for type_ in privs:
|
|
|
|
revoke_func = {
|
|
|
|
'table':revoke_table_privilege,
|
|
|
|
'database':revoke_database_privilege
|
|
|
|
}[type_]
|
2012-08-21 21:25:19 +02:00
|
|
|
for name, privileges in privs[type_].iteritems():
|
2012-08-21 18:20:16 +02:00
|
|
|
for privilege in privileges:
|
|
|
|
changed = revoke_func(cursor, user, name, privilege)\
|
|
|
|
or changed
|
|
|
|
|
|
|
|
return changed
|
|
|
|
|
|
|
|
def grant_privileges(cursor, user, privs):
|
|
|
|
if privs is None:
|
|
|
|
return False
|
|
|
|
|
|
|
|
changed = False
|
|
|
|
for type_ in privs:
|
|
|
|
grant_func = {
|
|
|
|
'table':grant_table_privilege,
|
|
|
|
'database':grant_database_privilege
|
|
|
|
}[type_]
|
2012-08-21 21:25:19 +02:00
|
|
|
for name, privileges in privs[type_].iteritems():
|
2012-08-21 18:20:16 +02:00
|
|
|
for privilege in privileges:
|
|
|
|
changed = grant_func(cursor, user, name, privilege)\
|
|
|
|
or changed
|
|
|
|
|
|
|
|
return changed
|
|
|
|
|
|
|
|
def parse_privs(privs, db):
|
|
|
|
"""
|
|
|
|
Parse privilege string to determine permissions for database db.
|
|
|
|
Format:
|
|
|
|
|
|
|
|
privileges[/privileges/...]
|
|
|
|
|
|
|
|
Where:
|
|
|
|
|
|
|
|
privileges := DATABASE_PRIVILEGES[,DATABASE_PRIVILEGES,...] |
|
|
|
|
TABLE_NAME:TABLE_PRIVILEGES[,TABLE_PRIVILEGES,...]
|
|
|
|
"""
|
|
|
|
if privs is None:
|
|
|
|
return privs
|
|
|
|
|
2012-08-21 21:25:19 +02:00
|
|
|
o_privs = {
|
2012-08-21 18:20:16 +02:00
|
|
|
'database':{},
|
|
|
|
'table':{}
|
|
|
|
}
|
|
|
|
for token in privs.split('/'):
|
|
|
|
if ':' not in token:
|
|
|
|
type_ = 'database'
|
|
|
|
name = db
|
2012-08-21 21:25:19 +02:00
|
|
|
priv_set = set(x.strip() for x in token.split(','))
|
2012-08-21 18:20:16 +02:00
|
|
|
else:
|
|
|
|
type_ = 'table'
|
|
|
|
name, privileges = token.split(':', 1)
|
2012-08-21 21:25:19 +02:00
|
|
|
priv_set = set(x.strip() for x in privileges.split(','))
|
2012-08-21 18:20:16 +02:00
|
|
|
|
2012-08-21 21:25:19 +02:00
|
|
|
o_privs[type_][name] = priv_set
|
2012-08-21 18:20:16 +02:00
|
|
|
|
2012-08-21 21:25:19 +02:00
|
|
|
return o_privs
|
2012-07-26 17:02:28 +02:00
|
|
|
|
|
|
|
# ===========================================
|
|
|
|
# Module execution.
|
|
|
|
#
|
|
|
|
|
|
|
|
def main():
|
|
|
|
module = AnsibleModule(
|
|
|
|
argument_spec=dict(
|
2012-07-29 18:47:44 +02:00
|
|
|
login_user=dict(default="postgres"),
|
|
|
|
login_password=dict(default=""),
|
|
|
|
login_host=dict(default=""),
|
2012-08-01 06:21:36 +02:00
|
|
|
user=dict(required=True, aliases=['name']),
|
2012-07-29 18:47:44 +02:00
|
|
|
password=dict(default=None),
|
2012-07-26 17:02:28 +02:00
|
|
|
state=dict(default="present", choices=["absent", "present"]),
|
2012-08-21 18:20:16 +02:00
|
|
|
priv=dict(default=None),
|
|
|
|
db=dict(default=''),
|
2012-08-21 21:23:45 +02:00
|
|
|
fail_on_user=dict(default='yes')
|
2012-07-26 17:02:28 +02:00
|
|
|
)
|
|
|
|
)
|
|
|
|
user = module.params["user"]
|
2012-07-29 18:47:44 +02:00
|
|
|
password = module.params["password"]
|
2012-07-26 17:02:28 +02:00
|
|
|
state = module.params["state"]
|
2012-08-21 21:23:45 +02:00
|
|
|
fail_on_user = module.params["fail_on_user"] == 'yes'
|
2012-07-26 17:02:28 +02:00
|
|
|
db = module.params["db"]
|
2012-08-21 18:20:16 +02:00
|
|
|
if db == '' and module.params["priv"] is not None:
|
|
|
|
module.fail_json(msg="privileges require a database to be specified")
|
|
|
|
privs = parse_privs(module.params["priv"], db)
|
2012-07-26 17:02:28 +02:00
|
|
|
|
|
|
|
if not postgresqldb_found:
|
|
|
|
module.fail_json(msg="the python psycopg2 module is required")
|
2012-08-17 17:37:02 +02:00
|
|
|
|
|
|
|
# To use defaults values, keyword arguments must be absent, so
|
|
|
|
# check which values are empty and don't include in the **kw
|
|
|
|
# dictionary
|
|
|
|
params_map = {
|
|
|
|
"login_host":"host",
|
|
|
|
"login_user":"user",
|
2012-08-21 18:20:16 +02:00
|
|
|
"login_password":"password",
|
|
|
|
"db":"database"
|
2012-08-17 17:37:02 +02:00
|
|
|
}
|
|
|
|
kw = dict( (params_map[k], v) for (k, v) in module.params.iteritems()
|
|
|
|
if k in params_map and v != "" )
|
2012-07-26 17:02:28 +02:00
|
|
|
try:
|
2012-08-21 21:23:45 +02:00
|
|
|
db_connection = psycopg2.connect(**kw)
|
2012-07-26 17:02:28 +02:00
|
|
|
cursor = db_connection.cursor()
|
2012-08-17 17:37:02 +02:00
|
|
|
except Exception, e:
|
2012-07-26 17:02:28 +02:00
|
|
|
module.fail_json(msg="unable to connect to database: %s" % e)
|
2012-08-21 18:20:16 +02:00
|
|
|
|
2012-08-21 21:23:45 +02:00
|
|
|
kw = dict(user=user)
|
2012-08-21 18:20:16 +02:00
|
|
|
changed = False
|
2012-08-21 21:23:45 +02:00
|
|
|
user_removed = False
|
2012-07-26 17:02:28 +02:00
|
|
|
if state == "present":
|
|
|
|
if user_exists(cursor, user):
|
2012-08-21 18:20:16 +02:00
|
|
|
changed = user_chpass(cursor, user, password)
|
2012-07-26 17:02:28 +02:00
|
|
|
else:
|
2012-07-29 18:47:44 +02:00
|
|
|
if password is None:
|
|
|
|
msg = "password parameter required when adding a user"
|
2012-07-26 17:02:28 +02:00
|
|
|
module.fail_json(msg=msg)
|
2012-08-21 18:20:16 +02:00
|
|
|
changed = user_add(cursor, user, password)
|
|
|
|
changed = grant_privileges(cursor, user, privs) or changed
|
|
|
|
else:
|
2012-07-26 17:02:28 +02:00
|
|
|
if user_exists(cursor, user):
|
2012-08-21 18:20:16 +02:00
|
|
|
changed = revoke_privileges(cursor, user, privs)
|
|
|
|
user_removed = user_delete(cursor, user)
|
|
|
|
changed = changed or user_removed
|
2012-08-21 21:23:45 +02:00
|
|
|
if fail_on_user and not user_removed:
|
2012-08-22 19:19:55 +02:00
|
|
|
msg = "unable to remove user"
|
2012-08-21 21:23:45 +02:00
|
|
|
module.fail_json(msg=msg)
|
|
|
|
kw['user_removed'] = user_removed
|
2012-08-21 18:20:16 +02:00
|
|
|
|
|
|
|
if changed:
|
|
|
|
db_connection.commit()
|
2012-08-21 21:23:45 +02:00
|
|
|
|
|
|
|
kw['changed'] = changed
|
|
|
|
module.exit_json(**kw)
|
2012-07-26 17:02:28 +02:00
|
|
|
|
|
|
|
# this is magic, see lib/ansible/module_common.py
|
|
|
|
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
|
|
|
|
main()
|