postgresql_user 15.8 KB
Newer Older
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

# 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/>.

19 20 21 22 23
DOCUMENTATION = '''
---
module: postgresql_user
short_description: Adds or removes a users (roles) from a PostgreSQL database.
description:
24 25 26 27 28 29 30
   - Add or remove PostgreSQL users (roles) from a remote host and, optionally,
     grant the users access to an existing database or tables.
   - The fundamental function of the module is to create, or delete, roles from
     a PostgreSQL cluster. Privilege assignment, or removal, is an optional
     step, which works on one database at a time. This allows for the module to
     be called several times in the same module to modify the permissions on
     different databases, or to grant permissions to already existing users.
Jan-Piet Mens committed
31
   - A user cannot be removed until all the privileges have been stripped from
32 33 34 35 36
     the user. In such situation, if the module tries to remove the user it
     will fail. To avoid this from happening the fail_on_user option signals
     the module to try to remove the user, but if not possible keep going; the
     module will report if changes happened and separately if the user was
     removed or not.
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
version_added: "0.6"
options:
  name:
    description:
      - name of the user (role) to add or remove
    required: true
    default: null
  password:
    description:
      - set the user's password
    required: true
    default: null
  db:
    description:
      - name of database where permissions will be granted
    required: false
    default: null
  fail_on_user:
    description:
Jan-Piet Mens committed
56
      - if C(yes), fail when user can't be removed. Otherwise just log and continue
57
    required: false
Michael DeHaan committed
58
    default: 'yes'
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    choices: [ "yes", "no" ]
  login_user:
    description:
      - User (role) used to authenticate with PostgreSQL
    required: false
    default: postgres
  login_password:
    description:
      - Password used to authenticate with PostgreSQL
    required: false
    default: null
  login_host:
    description:
      - Host running PostgreSQL.
    required: false
    default: localhost
  priv:
    description:
77
      - "PostgreSQL privileges string in the format: C(table:priv1,priv2)"
78 79
    required: false
    default: null
80 81 82 83 84 85 86
  role_attr_flags:
    description:
      - "PostgreSQL role attributes string in the format: CREATEDB,CREATEROLE,SUPERUSER"
    required: false
    default: null
    choices: [ "[NO]SUPERUSER","[NO]CREATEROLE", "[NO]CREATEUSER", "[NO]CREATEDB",
                    "[NO]INHERIT", "[NO]LOGIN", "[NO]REPLICATION" ]
87 88
  state:
    description:
89
      - The user (role) state
90 91 92 93
    required: false
    default: present
    choices: [ "present", "absent" ]
notes:
94 95 96 97 98 99 100 101
   - The default authentication assumes that you are either logging in as or
     sudo'ing to the postgres account on the host.
   - This module uses psycopg2, a Python PostgreSQL database adapter. You must
     ensure that psycopg2 is installed on the host before using this module. If
     the remote host is the PostgreSQL server (which is the default case), then
     PostgreSQL must also be installed on the remote host. For Ubuntu-based
     systems, install the postgresql, libpq-dev, and python-psycopg2 packages
     on the remote host before using this module.
102 103 104
   - If you specify PUBLIC as the user, then the privilege changes will apply
     to all users. You may not specify password or role_attr_flags when the
     PUBLIC user is specified.
105 106 107 108
requirements: [ psycopg2 ]
author: Lorin Hochstein
'''

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
EXAMPLES = '''
# Create django user and grant access to database and products table
- postgresql_user: db=acme user=django password=ceec4eif7ya priv=CONNECT/products:ALL

# Create rails user, grant privilege to create other databases and demote rails from super user status
- postgresql_user: user=rails password=secret role_attr_flags=CREATEDB,NOSUPERUSER

# Remove test user privileges from acme
- postgresql_user: db=acme user=test priv=ALL/products:ALL state=absent fail_on_user=no

# Remove test user from test database and the cluster
- postgresql_user: db=test user=test priv=ALL state=absent

# Example privileges string format
INSERT,UPDATE/table:SELECT/anothertable:ALL
'''

126 127
import re

128 129 130 131 132 133 134 135 136 137 138 139 140
try:
    import psycopg2
except ImportError:
    postgresqldb_found = False
else:
    postgresqldb_found = True

# ===========================================
# PostgreSQL module specific support methods.
#


def user_exists(cursor, user):
141 142 143
    # The PUBLIC user is a special case that is always there
    if user == 'PUBLIC':
        return True
144 145 146 147 148
    query = "SELECT rolname FROM pg_roles WHERE rolname=%(user)s"
    cursor.execute(query, {'user': user})
    return cursor.rowcount > 0


149
def user_add(cursor, user, password, role_attr_flags):
150
    """Create a new database user (role)."""
151 152 153 154
    query = 'CREATE USER "%(user)s" WITH PASSWORD %%(password)s %(role_attr_flags)s' % {
        "user": user, "role_attr_flags": role_attr_flags
    }
    cursor.execute(query, {"password": password})
155 156
    return True

157
def user_alter(cursor, user, password, role_attr_flags):
158
    """Change user password and/or attributes. Return True if changed, False otherwise."""
159 160
    changed = False

161 162 163 164 165 166 167 168
    if user == 'PUBLIC':
        if password is not None:
            module.fail_json(msg="cannot change the password for PUBLIC user")
        elif role_attr_flags != '':
            module.fail_json(msg="cannot change the role_attr_flags for PUBLIC user")
        else:
            return False

169
    # Handle passwords.
170 171
    if password is not None or role_attr_flags is not None:
        # Select password and all flag-like columns in order to verify changes.
172 173
        select = "SELECT * FROM pg_authid where rolname=%(user)s"
        cursor.execute(select, {"user": user})
174 175 176 177 178
        # Grab current role attributes.
        current_role_attrs = cursor.fetchone()

        if password is not None:
            # Update the role attributes, including password.
179 180 181 182
            alter = 'ALTER USER "%(user)s" WITH PASSWORD %%(password)s %(role_attr_flags)s' % {
                "user": user, "role_attr_flags": role_attr_flags
            }
            cursor.execute(alter, {"password": password})
183 184
        else:
            # Update the role attributes, excluding password.
185
            alter = "ALTER USER \"%(user)s\" WITH %(role_attr_flags)s"
186 187
            cursor.execute(alter % {"user": user, "role_attr_flags": role_attr_flags})
        # Grab new role attributes.
188
        cursor.execute(select, {"user": user})
189 190 191 192 193 194
        new_role_attrs = cursor.fetchone()

        # Detect any differences between current_ and new_role_attrs.
        for i in range(len(current_role_attrs)):
            if current_role_attrs[i] != new_role_attrs[i]:
                changed = True
195 196 197

    return changed

198 199 200 201
def user_delete(cursor, user):
    """Try to remove a user. Returns True if successful otherwise False"""
    cursor.execute("SAVEPOINT ansible_pgsql_user_delete")
    try:
202
        cursor.execute("DROP USER \"%s\"" % user)
203 204 205 206
    except:
        cursor.execute("ROLLBACK TO SAVEPOINT ansible_pgsql_user_delete")
        cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
        return False
207

208 209 210 211
    cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
    return True

def has_table_privilege(cursor, user, table, priv):
212
    query = 'SELECT has_table_privilege(%s, %s, %s)'
213
    cursor.execute(query, (user, table, priv))
214 215
    return cursor.fetchone()[0]

216 217 218 219 220 221 222 223 224
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()])
225

226

227
def grant_table_privilege(cursor, user, table, priv):
228
    prev_priv = get_table_privileges(cursor, user, table)
229
    query = 'GRANT %s ON TABLE \"%s\" TO \"%s\"' % (priv, table, user)
230
    cursor.execute(query)
231 232
    curr_priv = get_table_privileges(cursor, user, table)
    return len(curr_priv) > len(prev_priv)
233 234

def revoke_table_privilege(cursor, user, table, priv):
235
    prev_priv = get_table_privileges(cursor, user, table)
236
    query = 'REVOKE %s ON TABLE \"%s\" FROM \"%s\"' % (priv, table, user)
237
    cursor.execute(query)
238 239
    curr_priv = get_table_privileges(cursor, user, table)
    return len(curr_priv) < len(prev_priv)
240 241


242 243 244 245 246 247 248 249 250
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]
251 252
    if datacl is None:
        return []
253 254 255 256 257 258 259 260
    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

261
def has_database_privilege(cursor, user, db, priv):
262
    query = 'SELECT has_database_privilege(%s, %s, %s)'
263
    cursor.execute(query, (user, db, priv))
264 265 266
    return cursor.fetchone()[0]

def grant_database_privilege(cursor, user, db, priv):
267
    prev_priv = get_database_privileges(cursor, user, db)
268 269 270 271
    if user == "PUBLIC":
        query = 'GRANT %s ON DATABASE \"%s\" TO PUBLIC' % (priv, db)
    else:
        query = 'GRANT %s ON DATABASE \"%s\" TO \"%s\"' % (priv, db, user)
272
    cursor.execute(query)
273 274
    curr_priv = get_database_privileges(cursor, user, db)
    return len(curr_priv) > len(prev_priv)
275

276
def revoke_database_privilege(cursor, user, db, priv):
277
    prev_priv = get_database_privileges(cursor, user, db)
278 279 280 281
    if user == "PUBLIC":
        query = 'REVOKE %s ON DATABASE \"%s\" FROM PUBLIC' % (priv, db)
    else:
        query = 'REVOKE %s ON DATABASE \"%s\" FROM \"%s\"' % (priv, db, user)
282
    cursor.execute(query)
283 284
    curr_priv = get_database_privileges(cursor, user, db)
    return len(curr_priv) < len(prev_priv)
285

286 287 288
def revoke_privileges(cursor, user, privs):
    if privs is None:
        return False
289

290 291 292 293 294 295
    changed = False
    for type_ in privs:
        revoke_func = {
            'table':revoke_table_privilege,
            'database':revoke_database_privilege
        }[type_]
296
        for name, privileges in privs[type_].iteritems():
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
            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_]
313
        for name, privileges in privs[type_].iteritems():
314 315 316 317 318 319
            for privilege in privileges:
                changed = grant_func(cursor, user, name, privilege)\
                        or changed

    return changed

320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
def parse_role_attrs(role_attr_flags):
    """
    Parse role attributes string for user creation.
    Format:

        attributes[,attributes,...]

    Where:

        attributes := CREATEDB,CREATEROLE,NOSUPERUSER,...
    """
    if ',' not in role_attr_flags:
        return role_attr_flags
    flag_set = role_attr_flags.split(",")
    o_flags = " ".join(flag_set)
    return o_flags

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
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

352
    o_privs = {
353 354 355 356 357 358 359
        'database':{},
        'table':{}
    }
    for token in privs.split('/'):
        if ':' not in token:
            type_ = 'database'
            name = db
360
            priv_set = set(x.strip() for x in token.split(','))
361 362 363
        else:
            type_ = 'table'
            name, privileges = token.split(':', 1)
364
            priv_set = set(x.strip() for x in privileges.split(','))
365

366
        o_privs[type_][name] = priv_set
367

368
    return o_privs
369 370 371 372 373 374 375 376

# ===========================================
# Module execution.
#

def main():
    module = AnsibleModule(
        argument_spec=dict(
377 378 379
            login_user=dict(default="postgres"),
            login_password=dict(default=""),
            login_host=dict(default=""),
380
            user=dict(required=True, aliases=['name']),
381
            password=dict(default=None),
382
            state=dict(default="present", choices=["absent", "present"]),
383 384
            priv=dict(default=None),
            db=dict(default=''),
385
            port=dict(default='5432'),
386 387
            fail_on_user=dict(default='yes'),
            role_attr_flags=dict(default='')
388
        ),
389
        supports_check_mode = True
390
    )
391

392
    user = module.params["user"]
393
    password = module.params["password"]
394
    state = module.params["state"]
Pepe Barbe committed
395
    fail_on_user = module.params["fail_on_user"] == 'yes'
396
    db = module.params["db"]
397 398 399
    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)
400
    port = module.params["port"]
401
    role_attr_flags = parse_role_attrs(module.params["role_attr_flags"])
402 403 404

    if not postgresqldb_found:
        module.fail_json(msg="the python psycopg2 module is required")
405 406

    # To use defaults values, keyword arguments must be absent, so
407 408
    # check which values are empty and don't include in the **kw
    # dictionary
Michael DeHaan committed
409
    params_map = {
410 411
        "login_host":"host",
        "login_user":"user",
412
        "login_password":"password",
413
        "port":"port",
414
        "db":"database"
415
    }
416
    kw = dict( (params_map[k], v) for (k, v) in module.params.iteritems()
417
              if k in params_map and v != "" )
418
    try:
Pepe Barbe committed
419
        db_connection = psycopg2.connect(**kw)
420
        cursor = db_connection.cursor()
421
    except Exception, e:
422
        module.fail_json(msg="unable to connect to database: %s" % e)
423

Pepe Barbe committed
424
    kw = dict(user=user)
425
    changed = False
Pepe Barbe committed
426
    user_removed = False
427
        
428
    if state == "present":
429

430
        if user_exists(cursor, user):
431
            if  module.check_mode:  
432
                kw['changed'] = True 
433 434
                module.exit_json(**kw)

435
            changed = user_alter(cursor, user, password, role_attr_flags)
436
        else:
437 438
            if password is None:
                msg = "password parameter required when adding a user"
439
                module.fail_json(msg=msg)
440 441

            if  module.check_mode:  
442
                kw['changed'] = True 
443 444
                module.exit_json(**kw)

445
            changed = user_add(cursor, user, password, role_attr_flags)
446 447
        changed = grant_privileges(cursor, user, privs) or changed
    else:
448

449
        if user_exists(cursor, user):
450
            if  module.check_mode:  
451
                kw['changed'] = True 
452 453 454
                kw['user_removed'] = True 
                module.exit_json(**kw)

455 456 457
            changed = revoke_privileges(cursor, user, privs)
            user_removed = user_delete(cursor, user)
            changed = changed or user_removed
Pepe Barbe committed
458
            if fail_on_user and not user_removed:
Pepe Barbe committed
459
                msg = "unable to remove user"
Pepe Barbe committed
460 461
                module.fail_json(msg=msg)
            kw['user_removed'] = user_removed
462 463 464

    if changed:
        db_connection.commit()
Pepe Barbe committed
465 466 467

    kw['changed'] = changed
    module.exit_json(**kw)
468 469 470 471

# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()