postgresql_user 15.9 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" ]
examples:
94
   - code: "postgresql_user: db=acme user=django password=ceec4eif7ya priv=CONNECT/products:ALL"
95
     description: Create django user and grant access to database and products table
96
   - code: "postgresql_user: user=rails password=secret role_attr_flags=CREATEDB,NOSUPERUSER"
97
     description: Create rails user, grant privilege to create other databases and demote rails from super user status
98
   - code: "postgresql_user: db=acme user=test priv=ALL/products:ALL state=absent fail_on_user=no"
99
     description: Remove test user privileges from acme
100
   - code: "postgresql_user: db=test user=test priv=ALL state=absent"
101 102 103 104
     description: Remove test user from test database and the cluster
   - code: INSERT,UPDATE/table:SELECT/anothertable:ALL
     description: Example privileges string format
notes:
105 106 107 108 109 110 111 112
   - 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.
113 114 115
   - 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.
116 117 118 119
requirements: [ psycopg2 ]
author: Lorin Hochstein
'''

120 121
import re

122 123 124 125 126 127 128 129 130 131 132 133 134
try:
    import psycopg2
except ImportError:
    postgresqldb_found = False
else:
    postgresqldb_found = True

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


def user_exists(cursor, user):
135 136 137
    # The PUBLIC user is a special case that is always there
    if user == 'PUBLIC':
        return True
138 139 140 141 142
    query = "SELECT rolname FROM pg_roles WHERE rolname=%(user)s"
    cursor.execute(query, {'user': user})
    return cursor.rowcount > 0


143
def user_add(cursor, user, password, role_attr_flags):
144
    """Create a new database user (role)."""
145 146 147 148
    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})
149 150
    return True

151
def user_alter(cursor, user, password, role_attr_flags):
152
    """Change user password and/or attributes. Return True if changed, False otherwise."""
153 154
    changed = False

155 156 157 158 159 160 161 162
    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

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

        if password is not None:
            # Update the role attributes, including password.
173 174 175 176
            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})
177 178
        else:
            # Update the role attributes, excluding password.
179
            alter = "ALTER USER \"%(user)s\" WITH %(role_attr_flags)s"
180 181
            cursor.execute(alter % {"user": user, "role_attr_flags": role_attr_flags})
        # Grab new role attributes.
182
        cursor.execute(select, {"user": user})
183 184 185 186 187 188
        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
189 190 191

    return changed

192 193 194 195
def user_delete(cursor, user):
    """Try to remove a user. Returns True if successful otherwise False"""
    cursor.execute("SAVEPOINT ansible_pgsql_user_delete")
    try:
196
        cursor.execute("DROP USER \"%s\"" % user)
197 198 199 200
    except:
        cursor.execute("ROLLBACK TO SAVEPOINT ansible_pgsql_user_delete")
        cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
        return False
201

202 203 204 205
    cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
    return True

def has_table_privilege(cursor, user, table, priv):
206
    query = 'SELECT has_table_privilege(%s, %s, %s)'
207
    cursor.execute(query, (user, table, priv))
208 209
    return cursor.fetchone()[0]

210 211 212 213 214 215 216 217 218
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()])
219

220

221
def grant_table_privilege(cursor, user, table, priv):
222
    prev_priv = get_table_privileges(cursor, user, table)
223
    query = 'GRANT %s ON TABLE \"%s\" TO \"%s\"' % (priv, table, user)
224
    cursor.execute(query)
225 226
    curr_priv = get_table_privileges(cursor, user, table)
    return len(curr_priv) > len(prev_priv)
227 228

def revoke_table_privilege(cursor, user, table, priv):
229
    prev_priv = get_table_privileges(cursor, user, table)
230
    query = 'REVOKE %s ON TABLE \"%s\" FROM \"%s\"' % (priv, table, user)
231
    cursor.execute(query)
232 233
    curr_priv = get_table_privileges(cursor, user, table)
    return len(curr_priv) < len(prev_priv)
234 235


236 237 238 239 240 241 242 243 244
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]
245 246
    if datacl is None:
        return []
247 248 249 250 251 252 253 254
    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

255
def has_database_privilege(cursor, user, db, priv):
256
    query = 'SELECT has_database_privilege(%s, %s, %s)'
257
    cursor.execute(query, (user, db, priv))
258 259 260
    return cursor.fetchone()[0]

def grant_database_privilege(cursor, user, db, priv):
261
    prev_priv = get_database_privileges(cursor, user, db)
262 263 264 265
    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)
266
    cursor.execute(query)
267 268
    curr_priv = get_database_privileges(cursor, user, db)
    return len(curr_priv) > len(prev_priv)
269

270
def revoke_database_privilege(cursor, user, db, priv):
271
    prev_priv = get_database_privileges(cursor, user, db)
272 273 274 275
    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)
276
    cursor.execute(query)
277 278
    curr_priv = get_database_privileges(cursor, user, db)
    return len(curr_priv) < len(prev_priv)
279

280 281 282
def revoke_privileges(cursor, user, privs):
    if privs is None:
        return False
283

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

    return changed

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
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

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
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

346
    o_privs = {
347 348 349 350 351 352 353
        'database':{},
        'table':{}
    }
    for token in privs.split('/'):
        if ':' not in token:
            type_ = 'database'
            name = db
354
            priv_set = set(x.strip() for x in token.split(','))
355 356 357
        else:
            type_ = 'table'
            name, privileges = token.split(':', 1)
358
            priv_set = set(x.strip() for x in privileges.split(','))
359

360
        o_privs[type_][name] = priv_set
361

362
    return o_privs
363 364 365 366 367 368 369 370

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

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

386
    user = module.params["user"]
387
    password = module.params["password"]
388
    state = module.params["state"]
Pepe Barbe committed
389
    fail_on_user = module.params["fail_on_user"] == 'yes'
390
    db = module.params["db"]
391 392 393
    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)
394
    port = module.params["port"]
395
    role_attr_flags = parse_role_attrs(module.params["role_attr_flags"])
396 397 398

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

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

Pepe Barbe committed
418
    kw = dict(user=user)
419
    changed = False
Pepe Barbe committed
420
    user_removed = False
421
        
422
    if state == "present":
423

424
        if user_exists(cursor, user):
425
            if  module.check_mode:  
426
                kw['changed'] = True 
427 428
                module.exit_json(**kw)

429
            changed = user_alter(cursor, user, password, role_attr_flags)
430
        else:
431 432
            if password is None:
                msg = "password parameter required when adding a user"
433
                module.fail_json(msg=msg)
434 435

            if  module.check_mode:  
436
                kw['changed'] = True 
437 438
                module.exit_json(**kw)

439
            changed = user_add(cursor, user, password, role_attr_flags)
440 441
        changed = grant_privileges(cursor, user, privs) or changed
    else:
442

443
        if user_exists(cursor, user):
444
            if  module.check_mode:  
445
                kw['changed'] = True 
446 447 448
                kw['user_removed'] = True 
                module.exit_json(**kw)

449 450 451
            changed = revoke_privileges(cursor, user, privs)
            user_removed = user_delete(cursor, user)
            changed = changed or user_removed
Pepe Barbe committed
452
            if fail_on_user and not user_removed:
Pepe Barbe committed
453
                msg = "unable to remove user"
Pepe Barbe committed
454 455
                module.fail_json(msg=msg)
            kw['user_removed'] = user_removed
456 457 458

    if changed:
        db_connection.commit()
Pepe Barbe committed
459 460 461

    kw['changed'] = changed
    module.exit_json(**kw)
462 463 464 465

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