postgresql_user 16.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
version_added: "0.6"
38 39 40 41 42 43 44 45
options:
  name:
    description:
      - name of the user (role) to add or remove
    required: true
    default: null
  password:
    description:
46
      - set the user's password, before 1.4 this was required.
47
      - "When passing an encrypted password it must be generated with the format C('str[\\"md5\\"] + md5[ password + username ]'), resulting in a total of 35 characters.  An easy way to do this is: C(echo \\"md5`echo -n \\"verysecretpasswordJOE\\" | md5`\\")."
48
    required: false
49 50 51 52 53 54 55 56
    default: null
  db:
    description:
      - name of database where permissions will be granted
    required: false
    default: null
  fail_on_user:
    description:
Jan-Piet Mens committed
57
      - if C(yes), fail when user can't be removed. Otherwise just log and continue
58
    required: false
Michael DeHaan committed
59
    default: 'yes'
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    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:
78
      - "PostgreSQL privileges string in the format: C(table:priv1,priv2)"
79 80
    required: false
    default: null
81 82 83 84 85 86 87
  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" ]
88 89
  state:
    description:
90
      - The user (role) state
91 92 93
    required: false
    default: present
    choices: [ "present", "absent" ]
94 95 96 97 98
  encrypted:
    description:
      - denotes if the password is already encrypted. boolean.
    required: false
    default: false
Brian Coca committed
99
    version_added: '1.4'
100 101 102 103 104
  expires:
    description:
      - sets the user's password expiration.
    required: false
    default: null
Brian Coca committed
105
    version_added: '1.4'
106
notes:
107 108 109 110 111 112 113 114
   - 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.
115 116 117
   - 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.
118 119 120 121
requirements: [ psycopg2 ]
author: Lorin Hochstein
'''

122 123
EXAMPLES = '''
# Create django user and grant access to database and products table
124
- postgresql_user: db=acme name=django password=ceec4eif7ya priv=CONNECT/products:ALL
125 126

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

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

# Remove test user from test database and the cluster
133
- postgresql_user: db=test name=test priv=ALL state=absent
134 135 136

# Example privileges string format
INSERT,UPDATE/table:SELECT/anothertable:ALL
Brian Coca committed
137 138 139

# Remove an existing user's password
- postgresql_user: db=test user=test password=NULL
140 141
'''

142 143
import re

144 145 146 147 148 149 150 151 152 153 154 155 156
try:
    import psycopg2
except ImportError:
    postgresqldb_found = False
else:
    postgresqldb_found = True

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


def user_exists(cursor, user):
157 158 159
    # The PUBLIC user is a special case that is always there
    if user == 'PUBLIC':
        return True
160 161 162 163 164
    query = "SELECT rolname FROM pg_roles WHERE rolname=%(user)s"
    cursor.execute(query, {'user': user})
    return cursor.rowcount > 0


165
def user_add(cursor, user, password, role_attr_flags,  encrypted, expires):
166
    """Create a new database user (role)."""
167
    query_password_data = dict()
168 169
    query = 'CREATE USER "%(user)s"' % { "user": user}
    if password is not None:
170 171 172
        query = query + " WITH %(crypt)s" % { "crypt": encrypted }
        query = query + " PASSWORD %(password)s"
        query_password_data.update(password=password)
173 174 175
    if expires is not None:
        query = query + " VALID UNTIL '%(expires)s'" % { "exipres": expires }
    query = query + " " + role_attr_flags
176
    cursor.execute(query, query_password_data)
177 178
    return True

179
def user_alter(cursor, user, password, role_attr_flags, encrypted, expires):
180
    """Change user password and/or attributes. Return True if changed, False otherwise."""
181 182
    changed = False

183 184 185 186 187 188 189 190
    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

191
    # Handle passwords.
192 193
    if password is not None or role_attr_flags is not None:
        # Select password and all flag-like columns in order to verify changes.
194
        query_password_data = dict()
195 196
        select = "SELECT * FROM pg_authid where rolname=%(user)s"
        cursor.execute(select, {"user": user})
197 198 199
        # Grab current role attributes.
        current_role_attrs = cursor.fetchone()

200
        alter = 'ALTER USER "%(user)s"' % {"user": user}
201
        if password is not None:
202 203 204 205
            query_password_data.update(password=password)
            alter = alter + " WITH %(crypt)s" % {"crypt": encrypted}
            alter = alter + " PASSWORD %(password)s"
            alter = alter + "  %(flags)s" % {'flags': role_attr_flags}
206 207 208 209 210
        elif role_attr_flags:
            alter = alter + ' WITH ' + role_attr_flags
        if expires is not None:
            alter = alter + " VALID UNTIL '%(expires)s'" % { "exipres": expires }

211
        cursor.execute(alter, query_password_data)
212

213
        # Grab new role attributes.
214
        cursor.execute(select, {"user": user})
215 216 217 218 219 220
        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
221 222 223

    return changed

224 225 226 227
def user_delete(cursor, user):
    """Try to remove a user. Returns True if successful otherwise False"""
    cursor.execute("SAVEPOINT ansible_pgsql_user_delete")
    try:
228
        cursor.execute("DROP USER \"%s\"" % user)
229 230 231 232
    except:
        cursor.execute("ROLLBACK TO SAVEPOINT ansible_pgsql_user_delete")
        cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
        return False
233

234 235 236 237
    cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
    return True

def has_table_privilege(cursor, user, table, priv):
238
    query = 'SELECT has_table_privilege(%s, %s, %s)'
239
    cursor.execute(query, (user, table, priv))
240 241
    return cursor.fetchone()[0]

242 243 244 245 246 247 248 249 250
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()])
251

252

253
def grant_table_privilege(cursor, user, table, priv):
254
    prev_priv = get_table_privileges(cursor, user, table)
255
    query = 'GRANT %s ON TABLE \"%s\" TO \"%s\"' % (priv, table, user)
256
    cursor.execute(query)
257 258
    curr_priv = get_table_privileges(cursor, user, table)
    return len(curr_priv) > len(prev_priv)
259 260

def revoke_table_privilege(cursor, user, table, priv):
261
    prev_priv = get_table_privileges(cursor, user, table)
262
    query = 'REVOKE %s ON TABLE \"%s\" FROM \"%s\"' % (priv, table, user)
263
    cursor.execute(query)
264 265
    curr_priv = get_table_privileges(cursor, user, table)
    return len(curr_priv) < len(prev_priv)
266 267


268 269 270 271 272 273 274 275 276
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]
277 278
    if datacl is None:
        return []
279 280 281 282 283 284 285 286
    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

287
def has_database_privilege(cursor, user, db, priv):
288
    query = 'SELECT has_database_privilege(%s, %s, %s)'
289
    cursor.execute(query, (user, db, priv))
290 291 292
    return cursor.fetchone()[0]

def grant_database_privilege(cursor, user, db, priv):
293
    prev_priv = get_database_privileges(cursor, user, db)
294 295 296 297
    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)
298
    cursor.execute(query)
299 300
    curr_priv = get_database_privileges(cursor, user, db)
    return len(curr_priv) > len(prev_priv)
301

302
def revoke_database_privilege(cursor, user, db, priv):
303
    prev_priv = get_database_privileges(cursor, user, db)
304 305 306 307
    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)
308
    cursor.execute(query)
309 310
    curr_priv = get_database_privileges(cursor, user, db)
    return len(curr_priv) < len(prev_priv)
311

312 313 314
def revoke_privileges(cursor, user, privs):
    if privs is None:
        return False
315

316 317 318 319 320 321
    changed = False
    for type_ in privs:
        revoke_func = {
            'table':revoke_table_privilege,
            'database':revoke_database_privilege
        }[type_]
322
        for name, privileges in privs[type_].iteritems():
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
            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_]
339
        for name, privileges in privs[type_].iteritems():
340 341 342 343 344 345
            for privilege in privileges:
                changed = grant_func(cursor, user, name, privilege)\
                        or changed

    return changed

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
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

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
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

378
    o_privs = {
379 380 381 382 383 384 385
        'database':{},
        'table':{}
    }
    for token in privs.split('/'):
        if ':' not in token:
            type_ = 'database'
            name = db
386
            priv_set = set(x.strip() for x in token.split(','))
387 388 389
        else:
            type_ = 'table'
            name, privileges = token.split(':', 1)
390
            priv_set = set(x.strip() for x in privileges.split(','))
391

392
        o_privs[type_][name] = priv_set
393

394
    return o_privs
395 396 397 398 399 400 401 402

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

def main():
    module = AnsibleModule(
        argument_spec=dict(
403 404 405
            login_user=dict(default="postgres"),
            login_password=dict(default=""),
            login_host=dict(default=""),
406
            user=dict(required=True, aliases=['name']),
407
            password=dict(default=None),
408
            state=dict(default="present", choices=["absent", "present"]),
409 410
            priv=dict(default=None),
            db=dict(default=''),
411
            port=dict(default='5432'),
412 413 414 415
            fail_on_user=dict(type='bool', choices=BOOLEANS, default='yes'),
            role_attr_flags=dict(default=''),
            encrypted=dict(type='bool', choices=BOOLEANS, default='no'),
            expires=dict(default=None)
416
        ),
417
        supports_check_mode = True
418
    )
419

420
    user = module.params["user"]
421
    password = module.params["password"]
422
    state = module.params["state"]
423
    fail_on_user = module.params["fail_on_user"]
424
    db = module.params["db"]
425 426 427
    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)
428
    port = module.params["port"]
429
    role_attr_flags = parse_role_attrs(module.params["role_attr_flags"])
430 431 432 433 434
    if module.params["encrypted"]:
        encrypted = "ENCRYPTED"
    else:
        encrypted = "UNENCRYPTED"
    expires = module.params["expires"]
435 436 437

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

    # To use defaults values, keyword arguments must be absent, so
440 441
    # check which values are empty and don't include in the **kw
    # dictionary
Michael DeHaan committed
442
    params_map = {
443 444
        "login_host":"host",
        "login_user":"user",
445
        "login_password":"password",
446
        "port":"port",
447
        "db":"database"
448
    }
449
    kw = dict( (params_map[k], v) for (k, v) in module.params.iteritems()
450
              if k in params_map and v != "" )
451
    try:
Pepe Barbe committed
452
        db_connection = psycopg2.connect(**kw)
453
        cursor = db_connection.cursor()
454
    except Exception, e:
455
        module.fail_json(msg="unable to connect to database: %s" % e)
456

Pepe Barbe committed
457
    kw = dict(user=user)
458
    changed = False
Pepe Barbe committed
459
    user_removed = False
460

461
    if state == "present":
462
        if user_exists(cursor, user):
463
            changed = user_alter(cursor, user, password, role_attr_flags, encrypted, expires)
464
        else:
465
            changed = user_add(cursor, user, password, role_attr_flags, encrypted, expires)
466 467
        changed = grant_privileges(cursor, user, privs) or changed
    else:
468
        if user_exists(cursor, user):
469 470 471 472 473 474 475 476 477 478 479
            if  module.check_mode:
                changed = True
                kw['user_removed'] = True
            else:
                changed = revoke_privileges(cursor, user, privs)
                user_removed = user_delete(cursor, user)
                changed = changed or user_removed
                if fail_on_user and not user_removed:
                    msg = "unable to remove user"
                    module.fail_json(msg=msg)
                kw['user_removed'] = user_removed
480 481

    if changed:
482 483 484 485
        if module.check_mode:
            db_connection.rollback()
        else:
            db_connection.commit()
Pepe Barbe committed
486 487 488

    kw['changed'] = changed
    module.exit_json(**kw)
489

490
# import module snippets
491
from ansible.module_utils.basic import *
492
main()