postgresql_user 18 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
    choices: [ "yes", "no" ]
61 62 63 64 65
  port:
    description:
      - Database port to connect to.
    required: false
    default: 5432
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  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:
83
      - "PostgreSQL privileges string in the format: C(table:priv1,priv2)"
84 85
    required: false
    default: null
86 87 88 89 90 91 92
  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" ]
93 94
  state:
    description:
95
      - The user (role) state
96 97 98
    required: false
    default: present
    choices: [ "present", "absent" ]
99 100 101 102 103
  encrypted:
    description:
      - denotes if the password is already encrypted. boolean.
    required: false
    default: false
Brian Coca committed
104
    version_added: '1.4'
105 106 107 108 109
  expires:
    description:
      - sets the user's password expiration.
    required: false
    default: null
Brian Coca committed
110
    version_added: '1.4'
111
notes:
112 113 114 115 116 117 118 119
   - 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.
120 121 122
   - 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.
123 124 125 126
requirements: [ psycopg2 ]
author: Lorin Hochstein
'''

127 128
EXAMPLES = '''
# Create django user and grant access to database and products table
129
- postgresql_user: db=acme name=django password=ceec4eif7ya priv=CONNECT/products:ALL
130 131

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

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

# Remove test user from test database and the cluster
138
- postgresql_user: db=test name=test priv=ALL state=absent
139 140 141

# Example privileges string format
INSERT,UPDATE/table:SELECT/anothertable:ALL
Brian Coca committed
142 143 144

# Remove an existing user's password
- postgresql_user: db=test user=test password=NULL
145 146
'''

147 148
import re

149 150 151 152 153 154 155 156 157 158 159 160 161
try:
    import psycopg2
except ImportError:
    postgresqldb_found = False
else:
    postgresqldb_found = True

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


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


170
def user_add(cursor, user, password, role_attr_flags,  encrypted, expires):
171
    """Create a new database user (role)."""
172
    query_password_data = dict()
173 174
    query = 'CREATE USER "%(user)s"' % { "user": user}
    if password is not None:
175 176 177
        query = query + " WITH %(crypt)s" % { "crypt": encrypted }
        query = query + " PASSWORD %(password)s"
        query_password_data.update(password=password)
178
    if expires is not None:
Kyle Kelley committed
179
        query = query + " VALID UNTIL '%(expires)s'" % { "expires": expires }
180
    query = query + " " + role_attr_flags
181
    cursor.execute(query, query_password_data)
182 183
    return True

184
def user_alter(cursor, module, user, password, role_attr_flags, encrypted, expires):
185
    """Change user password and/or attributes. Return True if changed, False otherwise."""
186 187
    changed = False

188 189 190 191 192 193 194 195
    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

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

205
        alter = 'ALTER USER "%(user)s"' % {"user": user}
206
        if password is not None:
207 208 209 210
            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}
211 212 213 214 215
        elif role_attr_flags:
            alter = alter + ' WITH ' + role_attr_flags
        if expires is not None:
            alter = alter + " VALID UNTIL '%(expires)s'" % { "exipres": expires }

216
        try:
217
            cursor.execute(alter, query_password_data)
218 219 220 221 222 223 224 225 226
        except psycopg2.InternalError, e:
            if e.pgcode == '25006':
                # Handle errors due to read-only transactions indicated by pgcode 25006
                # ERROR:  cannot execute ALTER ROLE in a read-only transaction
                changed = False
                module.fail_json(msg=e.pgerror)
                return changed
            else:
                raise psycopg2.InternalError, e
227

228
        # Grab new role attributes.
229
        cursor.execute(select, {"user": user})
230 231 232 233 234 235
        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
236 237 238

    return changed

239 240 241 242
def user_delete(cursor, user):
    """Try to remove a user. Returns True if successful otherwise False"""
    cursor.execute("SAVEPOINT ansible_pgsql_user_delete")
    try:
243
        cursor.execute("DROP USER \"%s\"" % user)
244 245 246 247
    except:
        cursor.execute("ROLLBACK TO SAVEPOINT ansible_pgsql_user_delete")
        cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
        return False
248

249 250 251 252
    cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
    return True

def has_table_privilege(cursor, user, table, priv):
253
    query = 'SELECT has_table_privilege(%s, %s, %s)'
254
    cursor.execute(query, (user, table, priv))
255 256
    return cursor.fetchone()[0]

257 258 259 260 261 262 263 264 265
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()])
266

267

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
def quote_pg_identifier(identifier):
    """
    quote postgresql identifiers involving zero or more namespaces
    """

    if '"' in identifier:
        # the user has supplied their own quoting. we have to hope they're
        # doing it right.  Maybe they have an unfortunately named table
        # containing a period in the name, such as: "public"."users.2013"
        return identifier

    tokens = identifier.strip().split(".")
    quoted_tokens = []
    for token in tokens:
        quoted_tokens.append('"%s"' % (token, ))
    return ".".join(quoted_tokens)

285
def grant_table_privilege(cursor, user, table, priv):
286
    prev_priv = get_table_privileges(cursor, user, table)
287 288
    query = 'GRANT %s ON TABLE %s TO %s' % (
        priv, quote_pg_identifier(table), quote_pg_identifier(user), )
289
    cursor.execute(query)
290 291
    curr_priv = get_table_privileges(cursor, user, table)
    return len(curr_priv) > len(prev_priv)
292 293

def revoke_table_privilege(cursor, user, table, priv):
294
    prev_priv = get_table_privileges(cursor, user, table)
295 296
    query = 'REVOKE %s ON TABLE %s FROM %s' % (
        priv, quote_pg_identifier(table), quote_pg_identifier(user), )
297
    cursor.execute(query)
298 299
    curr_priv = get_table_privileges(cursor, user, table)
    return len(curr_priv) < len(prev_priv)
300 301


302 303 304 305 306 307 308 309 310
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]
311 312
    if datacl is None:
        return []
313 314 315 316 317 318 319 320
    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

321
def has_database_privilege(cursor, user, db, priv):
322
    query = 'SELECT has_database_privilege(%s, %s, %s)'
323
    cursor.execute(query, (user, db, priv))
324 325 326
    return cursor.fetchone()[0]

def grant_database_privilege(cursor, user, db, priv):
327
    prev_priv = get_database_privileges(cursor, user, db)
328 329 330 331
    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)
332
    cursor.execute(query)
333 334
    curr_priv = get_database_privileges(cursor, user, db)
    return len(curr_priv) > len(prev_priv)
335

336
def revoke_database_privilege(cursor, user, db, priv):
337
    prev_priv = get_database_privileges(cursor, user, db)
338 339 340 341
    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)
342
    cursor.execute(query)
343 344
    curr_priv = get_database_privileges(cursor, user, db)
    return len(curr_priv) < len(prev_priv)
345

346 347 348
def revoke_privileges(cursor, user, privs):
    if privs is None:
        return False
349

350 351 352 353 354 355
    changed = False
    for type_ in privs:
        revoke_func = {
            'table':revoke_table_privilege,
            'database':revoke_database_privilege
        }[type_]
356
        for name, privileges in privs[type_].iteritems():
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
            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_]
373
        for name, privileges in privs[type_].iteritems():
374 375 376 377 378 379
            for privilege in privileges:
                changed = grant_func(cursor, user, name, privilege)\
                        or changed

    return changed

380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
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

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
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

412
    o_privs = {
413 414 415 416 417 418 419
        'database':{},
        'table':{}
    }
    for token in privs.split('/'):
        if ':' not in token:
            type_ = 'database'
            name = db
420
            priv_set = set(x.strip() for x in token.split(','))
421 422 423
        else:
            type_ = 'table'
            name, privileges = token.split(':', 1)
424
            priv_set = set(x.strip() for x in privileges.split(','))
425

426
        o_privs[type_][name] = priv_set
427

428
    return o_privs
429 430 431 432 433 434 435 436

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

def main():
    module = AnsibleModule(
        argument_spec=dict(
437 438 439
            login_user=dict(default="postgres"),
            login_password=dict(default=""),
            login_host=dict(default=""),
440
            user=dict(required=True, aliases=['name']),
441
            password=dict(default=None),
442
            state=dict(default="present", choices=["absent", "present"]),
443 444
            priv=dict(default=None),
            db=dict(default=''),
445
            port=dict(default='5432'),
446
            fail_on_user=dict(type='bool', default='yes'),
447
            role_attr_flags=dict(default=''),
448
            encrypted=dict(type='bool', default='no'),
449
            expires=dict(default=None)
450
        ),
451
        supports_check_mode = True
452
    )
453

454
    user = module.params["user"]
455
    password = module.params["password"]
456
    state = module.params["state"]
457
    fail_on_user = module.params["fail_on_user"]
458
    db = module.params["db"]
459 460 461
    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)
462
    port = module.params["port"]
463
    role_attr_flags = parse_role_attrs(module.params["role_attr_flags"])
464 465 466 467 468
    if module.params["encrypted"]:
        encrypted = "ENCRYPTED"
    else:
        encrypted = "UNENCRYPTED"
    expires = module.params["expires"]
469 470 471

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

    # To use defaults values, keyword arguments must be absent, so
474 475
    # check which values are empty and don't include in the **kw
    # dictionary
Michael DeHaan committed
476
    params_map = {
477 478
        "login_host":"host",
        "login_user":"user",
479
        "login_password":"password",
480
        "port":"port",
481
        "db":"database"
482
    }
483
    kw = dict( (params_map[k], v) for (k, v) in module.params.iteritems()
484
              if k in params_map and v != "" )
485
    try:
Pepe Barbe committed
486
        db_connection = psycopg2.connect(**kw)
487
        cursor = db_connection.cursor()
488
    except Exception, e:
489
        module.fail_json(msg="unable to connect to database: %s" % e)
490

Pepe Barbe committed
491
    kw = dict(user=user)
492
    changed = False
Pepe Barbe committed
493
    user_removed = False
494

495
    if state == "present":
496
        if user_exists(cursor, user):
497
            changed = user_alter(cursor, module, user, password, role_attr_flags, encrypted, expires)
498
        else:
499
            changed = user_add(cursor, user, password, role_attr_flags, encrypted, expires)
500 501
        changed = grant_privileges(cursor, user, privs) or changed
    else:
502
        if user_exists(cursor, user):
503 504 505 506 507 508 509 510 511 512 513
            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
514 515

    if changed:
516 517 518 519
        if module.check_mode:
            db_connection.rollback()
        else:
            db_connection.commit()
Pepe Barbe committed
520 521 522

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

524
# import module snippets
525
from ansible.module_utils.basic import *
526
main()