2012-07-26 17:02:28 +02:00
#!/usr/bin/python
2012-08-03 03:29:10 +02:00
# -*- coding: utf-8 -*-
2012-07-26 17:02:28 +02:00
# 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/>.
2012-09-29 16:46:30 +02:00
DOCUMENTATION = '''
---
module: postgresql_user
short_description: Adds or removes a users (roles) from a PostgreSQL database.
description:
2012-09-30 12:21:35 +02:00
- 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.
2012-11-21 18:49:30 +01:00
- A user cannot be removed until all the privileges have been stripped from
2012-09-30 12:21:35 +02:00
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.
2013-11-28 03:23:03 +01:00
version_added: "0.6"
2012-09-29 16:46:30 +02:00
options:
name:
description:
- name of the user (role) to add or remove
required: true
default: null
password:
description:
2013-11-14 17:57:01 +01:00
- set the user's password, before 1.4 this was required.
2013-12-05 11:35:35 +01:00
- "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)\")."
2013-10-26 17:32:16 +02:00
required: false
2012-09-29 16:46:30 +02:00
default: null
db:
description:
- name of database where permissions will be granted
required: false
default: null
fail_on_user:
description:
2012-11-21 18:49:30 +01:00
- if C(yes), fail when user can't be removed. Otherwise just log and continue
2012-09-29 16:46:30 +02:00
required: false
2013-06-01 18:11:26 +02:00
default: 'yes'
2012-09-29 16:46:30 +02:00
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:
2012-09-30 12:21:35 +02:00
- "PostgreSQL privileges string in the format: C(table:priv1,priv2)"
2012-09-29 16:46:30 +02:00
required: false
default: null
2012-10-15 23:42:06 +02:00
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" ]
2012-09-29 16:46:30 +02:00
state:
description:
2013-04-01 12:44:22 +02:00
- The user (role) state
2012-09-29 16:46:30 +02:00
required: false
default: present
choices: [ "present", "absent" ]
2013-10-26 17:32:16 +02:00
encrypted:
description:
- denotes if the password is already encrypted. boolean.
required: false
default: false
2013-10-26 17:37:45 +02:00
version_added: '1.4'
2013-10-26 17:32:16 +02:00
expires:
description:
- sets the user's password expiration.
required: false
default: null
2013-10-26 17:37:45 +02:00
version_added: '1.4'
2012-09-29 16:46:30 +02:00
notes:
2012-09-30 12:21:35 +02:00
- 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.
2013-02-19 04:59:51 +01:00
- 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.
2012-09-29 16:46:30 +02:00
requirements: [ psycopg2 ]
author: Lorin Hochstein
'''
2013-06-14 11:53:43 +02:00
EXAMPLES = '''
# Create django user and grant access to database and products table
2013-11-03 06:42:44 +01:00
- postgresql_user: db=acme name=django password=ceec4eif7ya priv=CONNECT/products:ALL
2013-06-14 11:53:43 +02:00
# Create rails user, grant privilege to create other databases and demote rails from super user status
2013-11-03 06:42:44 +01:00
- postgresql_user: name=rails password=secret role_attr_flags=CREATEDB,NOSUPERUSER
2013-06-14 11:53:43 +02:00
# Remove test user privileges from acme
2013-11-03 06:42:44 +01:00
- postgresql_user: db=acme name=test priv=ALL/products:ALL state=absent fail_on_user=no
2013-06-14 11:53:43 +02:00
# Remove test user from test database and the cluster
2013-11-03 06:42:44 +01:00
- postgresql_user: db=test name=test priv=ALL state=absent
2013-06-14 11:53:43 +02:00
# Example privileges string format
INSERT,UPDATE/table:SELECT/anothertable:ALL
2013-10-26 17:37:45 +02:00
# Remove an existing user's password
- postgresql_user: db=test user=test password=NULL
2013-06-14 11:53:43 +02:00
'''
2012-08-21 21:25:19 +02:00
import re
2012-07-26 17:02:28 +02:00
try:
import psycopg2
except ImportError:
postgresqldb_found = False
else:
postgresqldb_found = True
# ===========================================
# PostgreSQL module specific support methods.
#
def user_exists(cursor, user):
2013-02-19 03:33:36 +01:00
# The PUBLIC user is a special case that is always there
if user == 'PUBLIC':
return True
2012-07-26 17:02:28 +02:00
query = "SELECT rolname FROM pg_roles WHERE rolname=%(user)s"
cursor.execute(query, {'user': user})
return cursor.rowcount > 0
2013-10-26 17:32:16 +02:00
def user_add(cursor, user, password, role_attr_flags, encrypted, expires):
2013-04-01 12:44:22 +02:00
"""Create a new database user (role)."""
2013-10-26 17:32:16 +02:00
query = 'CREATE USER "%(user)s"' % { "user": user}
if password is not None:
query = query + " WITH %(crypt)s PASSWORD '%(password)s'" % { "crypt": encrypted, "password": password }
if expires is not None:
query = query + " VALID UNTIL '%(expires)s'" % { "exipres": expires }
query = query + " " + role_attr_flags
cursor.execute(query)
2012-07-26 17:02:28 +02:00
return True
2013-10-26 17:32:16 +02:00
def user_alter(cursor, user, password, role_attr_flags, encrypted, expires):
2013-04-01 12:44:22 +02:00
"""Change user password and/or attributes. Return True if changed, False otherwise."""
2012-07-26 17:02:28 +02:00
changed = False
2013-02-19 03:33:36 +01:00
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
2012-07-26 17:02:28 +02:00
# Handle passwords.
2012-10-15 23:42:06 +02:00
if password is not None or role_attr_flags is not None:
# Select password and all flag-like columns in order to verify changes.
2012-12-05 09:51:15 +01:00
select = "SELECT * FROM pg_authid where rolname=%(user)s"
cursor.execute(select, {"user": user})
2012-10-15 23:42:06 +02:00
# Grab current role attributes.
current_role_attrs = cursor.fetchone()
2013-10-26 17:32:16 +02:00
alter = 'ALTER USER "%(user)s"' % {"user": user}
2012-10-15 23:42:06 +02:00
if password is not None:
2013-10-26 17:32:16 +02:00
alter = alter + " WITH %(crypt)s PASSWORD '%(password)s' %(flags)s" % {
"crypt": encrypted, "password": password, "flags": role_attr_flags
2013-04-07 23:07:58 +02:00
}
2013-10-26 17:32:16 +02:00
elif role_attr_flags:
alter = alter + ' WITH ' + role_attr_flags
if expires is not None:
alter = alter + " VALID UNTIL '%(expires)s'" % { "exipres": expires }
cursor.execute(alter)
2012-10-15 23:42:06 +02:00
# Grab new role attributes.
2012-12-05 09:51:15 +01:00
cursor.execute(select, {"user": user})
2012-10-15 23:42:06 +02:00
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
2012-07-26 17:02:28 +02:00
return changed
2012-08-21 18:20:16 +02:00
def user_delete(cursor, user):
"""Try to remove a user. Returns True if successful otherwise False"""
cursor.execute("SAVEPOINT ansible_pgsql_user_delete")
try:
2013-01-04 12:48:29 +01:00
cursor.execute("DROP USER \"%s\"" % user)
2012-08-21 18:20:16 +02:00
except:
cursor.execute("ROLLBACK TO SAVEPOINT ansible_pgsql_user_delete")
cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
return False
Fix postgresql_user bug
If I create a database from scratch and assign permissions by doing:
- name: ensure database is created
action: postgresql_db db=$dbname
- name: ensure django user has access
action: postgresql_user db=$dbname user=$dbuser priv=ALL password=$dbpassword
Then it fails with the error:
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 565, in <module>
main()
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 273, in main
changed = grant_privileges(cursor, user, privs) or changed
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 174, in grant_privileges
changed = grant_func(cursor, user, name, privilege)\
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 132, in grant_database_privilege
prev_priv = get_database_privileges(cursor, user, db)
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 118, in get_database_privileges
r = re.search('%s=(C?T?c?)/[a-z]+\,?' % user, datacl)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
This fix fixes the problem by not executing the regex if the
db query on pg_database returns None.
2012-09-07 22:24:00 +02:00
2012-08-21 18:20:16 +02:00
cursor.execute("RELEASE SAVEPOINT ansible_pgsql_user_delete")
return True
def has_table_privilege(cursor, user, table, priv):
2013-01-05 19:31:31 +01:00
query = 'SELECT has_table_privilege(%s, %s, %s)'
2012-08-21 21:25:19 +02:00
cursor.execute(query, (user, table, priv))
2012-08-21 18:20:16 +02:00
return cursor.fetchone()[0]
2012-08-21 21:25:19 +02:00
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()])
Fix postgresql_user bug
If I create a database from scratch and assign permissions by doing:
- name: ensure database is created
action: postgresql_db db=$dbname
- name: ensure django user has access
action: postgresql_user db=$dbname user=$dbuser priv=ALL password=$dbpassword
Then it fails with the error:
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 565, in <module>
main()
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 273, in main
changed = grant_privileges(cursor, user, privs) or changed
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 174, in grant_privileges
changed = grant_func(cursor, user, name, privilege)\
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 132, in grant_database_privilege
prev_priv = get_database_privileges(cursor, user, db)
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 118, in get_database_privileges
r = re.search('%s=(C?T?c?)/[a-z]+\,?' % user, datacl)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
This fix fixes the problem by not executing the regex if the
db query on pg_database returns None.
2012-09-07 22:24:00 +02:00
2012-08-21 21:25:19 +02:00
2012-08-21 18:20:16 +02:00
def grant_table_privilege(cursor, user, table, priv):
2012-08-21 21:25:19 +02:00
prev_priv = get_table_privileges(cursor, user, table)
2013-01-04 12:48:29 +01:00
query = 'GRANT %s ON TABLE \"%s\" TO \"%s\"' % (priv, table, user)
2012-08-21 18:20:16 +02:00
cursor.execute(query)
2012-08-21 21:25:19 +02:00
curr_priv = get_table_privileges(cursor, user, table)
return len(curr_priv) > len(prev_priv)
2012-08-21 18:20:16 +02:00
def revoke_table_privilege(cursor, user, table, priv):
2012-08-21 21:25:19 +02:00
prev_priv = get_table_privileges(cursor, user, table)
2013-01-04 12:48:29 +01:00
query = 'REVOKE %s ON TABLE \"%s\" FROM \"%s\"' % (priv, table, user)
2012-08-21 18:20:16 +02:00
cursor.execute(query)
2012-08-21 21:25:19 +02:00
curr_priv = get_table_privileges(cursor, user, table)
return len(curr_priv) < len(prev_priv)
2012-08-21 18:20:16 +02:00
2012-08-21 21:25:19 +02:00
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]
Fix postgresql_user bug
If I create a database from scratch and assign permissions by doing:
- name: ensure database is created
action: postgresql_db db=$dbname
- name: ensure django user has access
action: postgresql_user db=$dbname user=$dbuser priv=ALL password=$dbpassword
Then it fails with the error:
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 565, in <module>
main()
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 273, in main
changed = grant_privileges(cursor, user, privs) or changed
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 174, in grant_privileges
changed = grant_func(cursor, user, name, privilege)\
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 132, in grant_database_privilege
prev_priv = get_database_privileges(cursor, user, db)
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 118, in get_database_privileges
r = re.search('%s=(C?T?c?)/[a-z]+\,?' % user, datacl)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
This fix fixes the problem by not executing the regex if the
db query on pg_database returns None.
2012-09-07 22:24:00 +02:00
if datacl is None:
return []
2012-08-21 21:25:19 +02:00
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
2012-08-21 18:20:16 +02:00
def has_database_privilege(cursor, user, db, priv):
2013-01-05 19:31:31 +01:00
query = 'SELECT has_database_privilege(%s, %s, %s)'
2012-08-21 21:25:19 +02:00
cursor.execute(query, (user, db, priv))
2012-08-21 18:20:16 +02:00
return cursor.fetchone()[0]
def grant_database_privilege(cursor, user, db, priv):
2012-08-21 21:25:19 +02:00
prev_priv = get_database_privileges(cursor, user, db)
2013-02-19 03:33:36 +01:00
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)
2012-08-21 18:20:16 +02:00
cursor.execute(query)
2012-08-21 21:25:19 +02:00
curr_priv = get_database_privileges(cursor, user, db)
return len(curr_priv) > len(prev_priv)
2012-07-26 17:02:28 +02:00
2012-08-21 18:20:16 +02:00
def revoke_database_privilege(cursor, user, db, priv):
2012-08-21 21:25:19 +02:00
prev_priv = get_database_privileges(cursor, user, db)
2013-02-19 03:33:36 +01:00
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)
2012-08-21 18:20:16 +02:00
cursor.execute(query)
2012-08-21 21:25:19 +02:00
curr_priv = get_database_privileges(cursor, user, db)
return len(curr_priv) < len(prev_priv)
2012-07-26 17:02:28 +02:00
2012-08-21 18:20:16 +02:00
def revoke_privileges(cursor, user, privs):
if privs is None:
return False
2012-07-26 17:02:28 +02:00
2012-08-21 18:20:16 +02:00
changed = False
for type_ in privs:
revoke_func = {
'table':revoke_table_privilege,
'database':revoke_database_privilege
}[type_]
2012-08-21 21:25:19 +02:00
for name, privileges in privs[type_].iteritems():
2012-08-21 18:20:16 +02:00
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_]
2012-08-21 21:25:19 +02:00
for name, privileges in privs[type_].iteritems():
2012-08-21 18:20:16 +02:00
for privilege in privileges:
changed = grant_func(cursor, user, name, privilege)\
or changed
return changed
2012-10-15 23:42:06 +02:00
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
2012-08-21 18:20:16 +02:00
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
2012-08-21 21:25:19 +02:00
o_privs = {
2012-08-21 18:20:16 +02:00
'database':{},
'table':{}
}
for token in privs.split('/'):
if ':' not in token:
type_ = 'database'
name = db
2012-08-21 21:25:19 +02:00
priv_set = set(x.strip() for x in token.split(','))
2012-08-21 18:20:16 +02:00
else:
type_ = 'table'
name, privileges = token.split(':', 1)
2012-08-21 21:25:19 +02:00
priv_set = set(x.strip() for x in privileges.split(','))
Fix postgresql_user bug
If I create a database from scratch and assign permissions by doing:
- name: ensure database is created
action: postgresql_db db=$dbname
- name: ensure django user has access
action: postgresql_user db=$dbname user=$dbuser priv=ALL password=$dbpassword
Then it fails with the error:
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 565, in <module>
main()
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 273, in main
changed = grant_privileges(cursor, user, privs) or changed
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 174, in grant_privileges
changed = grant_func(cursor, user, name, privilege)\
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 132, in grant_database_privilege
prev_priv = get_database_privileges(cursor, user, db)
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 118, in get_database_privileges
r = re.search('%s=(C?T?c?)/[a-z]+\,?' % user, datacl)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
This fix fixes the problem by not executing the regex if the
db query on pg_database returns None.
2012-09-07 22:24:00 +02:00
2012-08-21 21:25:19 +02:00
o_privs[type_][name] = priv_set
Fix postgresql_user bug
If I create a database from scratch and assign permissions by doing:
- name: ensure database is created
action: postgresql_db db=$dbname
- name: ensure django user has access
action: postgresql_user db=$dbname user=$dbuser priv=ALL password=$dbpassword
Then it fails with the error:
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 565, in <module>
main()
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 273, in main
changed = grant_privileges(cursor, user, privs) or changed
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 174, in grant_privileges
changed = grant_func(cursor, user, name, privilege)\
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 132, in grant_database_privilege
prev_priv = get_database_privileges(cursor, user, db)
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 118, in get_database_privileges
r = re.search('%s=(C?T?c?)/[a-z]+\,?' % user, datacl)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
This fix fixes the problem by not executing the regex if the
db query on pg_database returns None.
2012-09-07 22:24:00 +02:00
2012-08-21 21:25:19 +02:00
return o_privs
2012-07-26 17:02:28 +02:00
# ===========================================
# Module execution.
#
def main():
module = AnsibleModule(
argument_spec=dict(
2012-07-29 18:47:44 +02:00
login_user=dict(default="postgres"),
login_password=dict(default=""),
login_host=dict(default=""),
2012-08-01 06:21:36 +02:00
user=dict(required=True, aliases=['name']),
2012-07-29 18:47:44 +02:00
password=dict(default=None),
2012-07-26 17:02:28 +02:00
state=dict(default="present", choices=["absent", "present"]),
2012-08-21 18:20:16 +02:00
priv=dict(default=None),
db=dict(default=''),
2012-09-05 18:18:30 +02:00
port=dict(default='5432'),
2013-10-26 17:32:16 +02:00
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)
2013-02-20 15:12:25 +01:00
),
2013-02-27 02:30:33 +01:00
supports_check_mode = True
2012-07-26 17:02:28 +02:00
)
2013-02-20 15:12:25 +01:00
2012-07-26 17:02:28 +02:00
user = module.params["user"]
2012-07-29 18:47:44 +02:00
password = module.params["password"]
2012-07-26 17:02:28 +02:00
state = module.params["state"]
2013-10-26 17:32:16 +02:00
fail_on_user = module.params["fail_on_user"]
2012-07-26 17:02:28 +02:00
db = module.params["db"]
2012-08-21 18:20:16 +02:00
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)
2012-09-05 18:18:30 +02:00
port = module.params["port"]
2012-10-15 23:42:06 +02:00
role_attr_flags = parse_role_attrs(module.params["role_attr_flags"])
2013-10-26 17:32:16 +02:00
if module.params["encrypted"]:
encrypted = "ENCRYPTED"
else:
encrypted = "UNENCRYPTED"
expires = module.params["expires"]
2012-07-26 17:02:28 +02:00
if not postgresqldb_found:
module.fail_json(msg="the python psycopg2 module is required")
Fix postgresql_user bug
If I create a database from scratch and assign permissions by doing:
- name: ensure database is created
action: postgresql_db db=$dbname
- name: ensure django user has access
action: postgresql_user db=$dbname user=$dbuser priv=ALL password=$dbpassword
Then it fails with the error:
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 565, in <module>
main()
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 273, in main
changed = grant_privileges(cursor, user, privs) or changed
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 174, in grant_privileges
changed = grant_func(cursor, user, name, privilege)\
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 132, in grant_database_privilege
prev_priv = get_database_privileges(cursor, user, db)
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 118, in get_database_privileges
r = re.search('%s=(C?T?c?)/[a-z]+\,?' % user, datacl)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
This fix fixes the problem by not executing the regex if the
db query on pg_database returns None.
2012-09-07 22:24:00 +02:00
# To use defaults values, keyword arguments must be absent, so
2012-08-17 17:37:02 +02:00
# check which values are empty and don't include in the **kw
# dictionary
2012-10-31 01:42:07 +01:00
params_map = {
2012-08-17 17:37:02 +02:00
"login_host":"host",
"login_user":"user",
2012-08-21 18:20:16 +02:00
"login_password":"password",
2012-09-05 18:18:30 +02:00
"port":"port",
Fix postgresql_user bug
If I create a database from scratch and assign permissions by doing:
- name: ensure database is created
action: postgresql_db db=$dbname
- name: ensure django user has access
action: postgresql_user db=$dbname user=$dbuser priv=ALL password=$dbpassword
Then it fails with the error:
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 565, in <module>
main()
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 273, in main
changed = grant_privileges(cursor, user, privs) or changed
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 174, in grant_privileges
changed = grant_func(cursor, user, name, privilege)\
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 132, in grant_database_privilege
prev_priv = get_database_privileges(cursor, user, db)
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 118, in get_database_privileges
r = re.search('%s=(C?T?c?)/[a-z]+\,?' % user, datacl)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
This fix fixes the problem by not executing the regex if the
db query on pg_database returns None.
2012-09-07 22:24:00 +02:00
"db":"database"
2012-08-17 17:37:02 +02:00
}
Fix postgresql_user bug
If I create a database from scratch and assign permissions by doing:
- name: ensure database is created
action: postgresql_db db=$dbname
- name: ensure django user has access
action: postgresql_user db=$dbname user=$dbuser priv=ALL password=$dbpassword
Then it fails with the error:
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 565, in <module>
main()
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 273, in main
changed = grant_privileges(cursor, user, privs) or changed
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 174, in grant_privileges
changed = grant_func(cursor, user, name, privilege)\
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 132, in grant_database_privilege
prev_priv = get_database_privileges(cursor, user, db)
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 118, in get_database_privileges
r = re.search('%s=(C?T?c?)/[a-z]+\,?' % user, datacl)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
This fix fixes the problem by not executing the regex if the
db query on pg_database returns None.
2012-09-07 22:24:00 +02:00
kw = dict( (params_map[k], v) for (k, v) in module.params.iteritems()
2012-08-17 17:37:02 +02:00
if k in params_map and v != "" )
2012-07-26 17:02:28 +02:00
try:
2012-08-21 21:23:45 +02:00
db_connection = psycopg2.connect(**kw)
2012-07-26 17:02:28 +02:00
cursor = db_connection.cursor()
2012-08-17 17:37:02 +02:00
except Exception, e:
2012-07-26 17:02:28 +02:00
module.fail_json(msg="unable to connect to database: %s" % e)
Fix postgresql_user bug
If I create a database from scratch and assign permissions by doing:
- name: ensure database is created
action: postgresql_db db=$dbname
- name: ensure django user has access
action: postgresql_user db=$dbname user=$dbuser priv=ALL password=$dbpassword
Then it fails with the error:
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 565, in <module>
main()
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 273, in main
changed = grant_privileges(cursor, user, privs) or changed
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 174, in grant_privileges
changed = grant_func(cursor, user, name, privilege)\
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 132, in grant_database_privilege
prev_priv = get_database_privileges(cursor, user, db)
File "/tmp/ansible-1347048449.32-29998829936529/postgresql_user", line 118, in get_database_privileges
r = re.search('%s=(C?T?c?)/[a-z]+\,?' % user, datacl)
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
This fix fixes the problem by not executing the regex if the
db query on pg_database returns None.
2012-09-07 22:24:00 +02:00
2012-08-21 21:23:45 +02:00
kw = dict(user=user)
2012-08-21 18:20:16 +02:00
changed = False
2012-08-21 21:23:45 +02:00
user_removed = False
2013-02-20 15:12:25 +01:00
2013-10-26 17:32:16 +02:00
if state == "present":
2012-07-26 17:02:28 +02:00
if user_exists(cursor, user):
2013-10-26 17:32:16 +02:00
changed = user_alter(cursor, user, password, role_attr_flags, encrypted, expires)
2012-07-26 17:02:28 +02:00
else:
2013-10-26 17:32:16 +02:00
changed = user_add(cursor, user, password, role_attr_flags, encrypted, expires)
2012-08-21 18:20:16 +02:00
changed = grant_privileges(cursor, user, privs) or changed
else:
2012-07-26 17:02:28 +02:00
if user_exists(cursor, user):
2013-10-26 17:32:16 +02:00
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
2012-08-21 18:20:16 +02:00
if changed:
2013-10-26 17:32:16 +02:00
if module.check_mode:
db_connection.rollback()
else:
db_connection.commit()
2012-08-21 21:23:45 +02:00
kw['changed'] = changed
module.exit_json(**kw)
2012-07-26 17:02:28 +02:00
2013-12-02 21:13:49 +01:00
# import module snippets
2013-12-02 21:11:23 +01:00
from ansible.module_utils.basic import *
2012-07-26 17:02:28 +02:00
main()