postgresql_user 14.6 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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    required: false
    default: yes
    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 89 90 91 92 93
  state:
    description:
      - The database state
    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 116
requirements: [ psycopg2 ]
author: Lorin Hochstein
'''

117 118
import re

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
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


137
def user_add(cursor, user, password, role_attr_flags):
138
    """Create a new user with write access to the database"""
139
    query = "CREATE USER \"%(user)s\" with PASSWORD '%(password)s' %(role_attr_flags)s"
140
    cursor.execute(query % {"user": user, "password": password, "role_attr_flags": role_attr_flags})
141 142
    return True

143
def user_alter(cursor, user, password, role_attr_flags):
144
    """Change user password"""
145 146 147
    changed = False

    # Handle passwords.
148 149
    if password is not None or role_attr_flags is not None:
        # Select password and all flag-like columns in order to verify changes.
150 151
        select = "SELECT * FROM pg_authid where rolname=%(user)s"
        cursor.execute(select, {"user": user})
152 153 154 155 156
        # Grab current role attributes.
        current_role_attrs = cursor.fetchone()

        if password is not None:
            # Update the role attributes, including password.
157
            alter = "ALTER USER \"%(user)s\" WITH PASSWORD '%(password)s' %(role_attr_flags)s"
158 159 160
            cursor.execute(alter % {"user": user, "password": password, "role_attr_flags": role_attr_flags})
        else:
            # Update the role attributes, excluding password.
161
            alter = "ALTER USER \"%(user)s\" WITH %(role_attr_flags)s"
162 163
            cursor.execute(alter % {"user": user, "role_attr_flags": role_attr_flags})
        # Grab new role attributes.
164
        cursor.execute(select, {"user": user})
165 166 167 168 169 170
        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
171 172 173

    return changed

174 175 176 177
def user_delete(cursor, user):
    """Try to remove a user. Returns True if successful otherwise False"""
    cursor.execute("SAVEPOINT ansible_pgsql_user_delete")
    try:
178
        cursor.execute("DROP USER \"%s\"" % user)
179 180 181 182
    except:
        cursor.execute("ROLLBACK TO SAVEPOINT ansible_pgsql_user_delete")
        cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
        return False
183

184 185 186 187
    cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
    return True

def has_table_privilege(cursor, user, table, priv):
188
    query = 'SELECT has_table_privilege(%s, %s, %s)'
189
    cursor.execute(query, (user, table, priv))
190 191
    return cursor.fetchone()[0]

192 193 194 195 196 197 198 199 200
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()])
201

202

203
def grant_table_privilege(cursor, user, table, priv):
204
    prev_priv = get_table_privileges(cursor, user, table)
205
    query = 'GRANT %s ON TABLE \"%s\" TO \"%s\"' % (priv, table, user)
206
    cursor.execute(query)
207 208
    curr_priv = get_table_privileges(cursor, user, table)
    return len(curr_priv) > len(prev_priv)
209 210

def revoke_table_privilege(cursor, user, table, priv):
211
    prev_priv = get_table_privileges(cursor, user, table)
212
    query = 'REVOKE %s ON TABLE \"%s\" FROM \"%s\"' % (priv, table, user)
213
    cursor.execute(query)
214 215
    curr_priv = get_table_privileges(cursor, user, table)
    return len(curr_priv) < len(prev_priv)
216 217


218 219 220 221 222 223 224 225 226
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]
227 228
    if datacl is None:
        return []
229 230 231 232 233 234 235 236
    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

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

def grant_database_privilege(cursor, user, db, priv):
243
    prev_priv = get_database_privileges(cursor, user, db)
244
    query = 'GRANT %s ON DATABASE \"%s\" TO \"%s\"' % (priv, db, user)
245
    cursor.execute(query)
246 247
    curr_priv = get_database_privileges(cursor, user, db)
    return len(curr_priv) > len(prev_priv)
248

249
def revoke_database_privilege(cursor, user, db, priv):
250
    prev_priv = get_database_privileges(cursor, user, db)
251
    query = 'REVOKE %s ON DATABASE \"%s\" FROM \"%s\"' % (priv, db, user)
252
    cursor.execute(query)
253 254
    curr_priv = get_database_privileges(cursor, user, db)
    return len(curr_priv) < len(prev_priv)
255

256 257 258
def revoke_privileges(cursor, user, privs):
    if privs is None:
        return False
259

260 261 262 263 264 265
    changed = False
    for type_ in privs:
        revoke_func = {
            'table':revoke_table_privilege,
            'database':revoke_database_privilege
        }[type_]
266
        for name, privileges in privs[type_].iteritems():
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
            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_]
283
        for name, privileges in privs[type_].iteritems():
284 285 286 287 288 289
            for privilege in privileges:
                changed = grant_func(cursor, user, name, privilege)\
                        or changed

    return changed

290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
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

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
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

322
    o_privs = {
323 324 325 326 327 328 329
        'database':{},
        'table':{}
    }
    for token in privs.split('/'):
        if ':' not in token:
            type_ = 'database'
            name = db
330
            priv_set = set(x.strip() for x in token.split(','))
331 332 333
        else:
            type_ = 'table'
            name, privileges = token.split(':', 1)
334
            priv_set = set(x.strip() for x in privileges.split(','))
335

336
        o_privs[type_][name] = priv_set
337

338
    return o_privs
339 340 341 342 343 344 345 346

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

def main():
    module = AnsibleModule(
        argument_spec=dict(
347 348 349
            login_user=dict(default="postgres"),
            login_password=dict(default=""),
            login_host=dict(default=""),
350
            user=dict(required=True, aliases=['name']),
351
            password=dict(default=None),
352
            state=dict(default="present", choices=["absent", "present"]),
353 354
            priv=dict(default=None),
            db=dict(default=''),
355
            port=dict(default='5432'),
356 357
            fail_on_user=dict(default='yes'),
            role_attr_flags=dict(default='')
358 359 360
        )
    )
    user = module.params["user"]
361
    password = module.params["password"]
362
    state = module.params["state"]
Pepe Barbe committed
363
    fail_on_user = module.params["fail_on_user"] == 'yes'
364
    db = module.params["db"]
365 366 367
    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)
368
    port = module.params["port"]
369
    role_attr_flags = parse_role_attrs(module.params["role_attr_flags"])
370 371 372

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

    # To use defaults values, keyword arguments must be absent, so
375 376
    # check which values are empty and don't include in the **kw
    # dictionary
Michael DeHaan committed
377
    params_map = {
378 379
        "login_host":"host",
        "login_user":"user",
380
        "login_password":"password",
381
        "port":"port",
382
        "db":"database"
383
    }
384
    kw = dict( (params_map[k], v) for (k, v) in module.params.iteritems()
385
              if k in params_map and v != "" )
386
    try:
Pepe Barbe committed
387
        db_connection = psycopg2.connect(**kw)
388
        cursor = db_connection.cursor()
389
    except Exception, e:
390
        module.fail_json(msg="unable to connect to database: %s" % e)
391

Pepe Barbe committed
392
    kw = dict(user=user)
393
    changed = False
Pepe Barbe committed
394
    user_removed = False
395 396
    if state == "present":
        if user_exists(cursor, user):
397
            changed = user_alter(cursor, user, password, role_attr_flags)
398
        else:
399 400
            if password is None:
                msg = "password parameter required when adding a user"
401
                module.fail_json(msg=msg)
402
            changed = user_add(cursor, user, password, role_attr_flags)
403 404
        changed = grant_privileges(cursor, user, privs) or changed
    else:
405
        if user_exists(cursor, user):
406 407 408
            changed = revoke_privileges(cursor, user, privs)
            user_removed = user_delete(cursor, user)
            changed = changed or user_removed
Pepe Barbe committed
409
            if fail_on_user and not user_removed:
Pepe Barbe committed
410
                msg = "unable to remove user"
Pepe Barbe committed
411 412
                module.fail_json(msg=msg)
            kw['user_removed'] = user_removed
413 414 415

    if changed:
        db_connection.commit()
Pepe Barbe committed
416 417 418

    kw['changed'] = changed
    module.exit_json(**kw)
419 420 421 422

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