2016-11-24 18:07:51 +00:00
|
|
|
#!/usr/bin/python
|
|
|
|
# -*- coding: utf-8 -*-
|
2017-07-29 21:14:16 +00:00
|
|
|
# Copyright: Ansible Project
|
|
|
|
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
|
|
|
|
|
|
|
from __future__ import absolute_import, division, print_function
|
|
|
|
__metaclass__ = type
|
2016-11-24 18:07:51 +00:00
|
|
|
|
|
|
|
|
2017-08-16 03:16:38 +00:00
|
|
|
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
2017-03-14 16:07:22 +00:00
|
|
|
'status': ['preview'],
|
|
|
|
'supported_by': 'community'}
|
|
|
|
|
2016-12-06 10:35:25 +00:00
|
|
|
|
2016-11-24 18:07:51 +00:00
|
|
|
DOCUMENTATION = '''
|
|
|
|
---
|
|
|
|
module: postgresql_schema
|
2016-11-24 18:35:53 +00:00
|
|
|
short_description: Add or remove PostgreSQL schema from a remote host
|
2016-11-24 18:07:51 +00:00
|
|
|
description:
|
|
|
|
- Add or remove PostgreSQL schema from a remote host.
|
2016-11-24 18:35:53 +00:00
|
|
|
version_added: "2.3"
|
2016-11-24 18:07:51 +00:00
|
|
|
options:
|
|
|
|
name:
|
|
|
|
description:
|
2016-11-24 18:35:53 +00:00
|
|
|
- Name of the schema to add or remove.
|
2016-11-24 18:07:51 +00:00
|
|
|
required: true
|
|
|
|
database:
|
|
|
|
description:
|
2016-11-24 18:35:53 +00:00
|
|
|
- Name of the database to connect to.
|
2016-11-24 18:07:51 +00:00
|
|
|
default: postgres
|
|
|
|
login_user:
|
|
|
|
description:
|
2016-11-24 18:35:53 +00:00
|
|
|
- The username used to authenticate with.
|
2016-11-24 18:07:51 +00:00
|
|
|
login_password:
|
|
|
|
description:
|
2016-11-24 18:35:53 +00:00
|
|
|
- The password used to authenticate with.
|
2016-11-24 18:07:51 +00:00
|
|
|
login_host:
|
|
|
|
description:
|
2016-11-24 18:35:53 +00:00
|
|
|
- Host running the database.
|
2016-11-24 18:07:51 +00:00
|
|
|
default: localhost
|
|
|
|
login_unix_socket:
|
|
|
|
description:
|
2016-11-24 18:35:53 +00:00
|
|
|
- Path to a Unix domain socket for local connections.
|
2016-11-24 18:07:51 +00:00
|
|
|
owner:
|
|
|
|
description:
|
2016-11-24 18:35:53 +00:00
|
|
|
- Name of the role to set as owner of the schema.
|
2016-11-24 18:07:51 +00:00
|
|
|
port:
|
|
|
|
description:
|
|
|
|
- Database port to connect to.
|
|
|
|
default: 5432
|
|
|
|
state:
|
|
|
|
description:
|
2016-11-24 18:35:53 +00:00
|
|
|
- The schema state.
|
2016-11-24 18:07:51 +00:00
|
|
|
default: present
|
|
|
|
choices: [ "present", "absent" ]
|
|
|
|
notes:
|
|
|
|
- This module uses I(psycopg2), a Python PostgreSQL database adapter. You must ensure that psycopg2 is installed on
|
2017-03-23 01:50:28 +00:00
|
|
|
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 C(postgresql), C(libpq-dev), and C(python-psycopg2) packages on the remote host before
|
|
|
|
using this module.
|
2016-11-24 18:07:51 +00:00
|
|
|
requirements: [ psycopg2 ]
|
|
|
|
author: "Flavien Chantelot <contact@flavien.io>"
|
|
|
|
'''
|
|
|
|
|
|
|
|
EXAMPLES = '''
|
|
|
|
# Create a new schema with name "acme"
|
2016-11-24 18:35:53 +00:00
|
|
|
- postgresql_schema:
|
|
|
|
name: acme
|
|
|
|
|
2016-11-24 18:07:51 +00:00
|
|
|
# Create a new schema "acme" with a user "bob" who will own it
|
2017-01-27 23:20:31 +00:00
|
|
|
- postgresql_schema:
|
2016-11-24 18:35:53 +00:00
|
|
|
name: acme
|
|
|
|
owner: bob
|
2016-11-24 18:07:51 +00:00
|
|
|
|
|
|
|
'''
|
|
|
|
|
|
|
|
RETURN = '''
|
|
|
|
schema:
|
|
|
|
description: Name of the schema
|
|
|
|
returned: success, changed
|
|
|
|
type: string
|
|
|
|
sample: "acme"
|
|
|
|
'''
|
|
|
|
|
2017-07-29 21:14:16 +00:00
|
|
|
import traceback
|
|
|
|
|
2016-11-24 18:07:51 +00:00
|
|
|
try:
|
|
|
|
import psycopg2
|
|
|
|
import psycopg2.extras
|
|
|
|
except ImportError:
|
|
|
|
postgresqldb_found = False
|
|
|
|
else:
|
|
|
|
postgresqldb_found = True
|
|
|
|
|
2017-07-29 21:14:16 +00:00
|
|
|
from ansible.module_utils.basic import AnsibleModule
|
|
|
|
from ansible.module_utils.database import SQLParseError, pg_quote_identifier
|
fix failing fail_json call in postgresql_schema (#21495)
fix failing fail_json call in postgresql_schema
- Bugfix Pull Request
modules/database/postgresql/postgresql_schema
```
2.3.0
```
Here's an example of the error that was coming out. Massaged some linebreaks and backslashes to make it more readable:
"module_stderr": "Traceback (most recent call last):
File "/tmp/ansible_3X05GE/ansible_module_postgresql_schema.py", line 274, in <module>
main()
File "/tmp/ansible_3X05GE/ansible_module_postgresql_schema.py", line 265, in main
module.fail_json(msg="Database query failed: %s" %(text, str(e)))
NameError: global name 'text' is not defined
",
Now it triggers with the correct exception and shows the traceback. This duplication of str(e) and traceback seems to be the best design pattern.
Sample of the new output:
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_gp4v1Q/ansible_module_postgresql_schema.py", line 254, in main
changed = schema_create(cursor, schema, owner)
...
return super(DictCursor, self).execute(query, vars)
ProgrammingError: permission denied for database schemadb
fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
...
},
"msg": "Database query failed: permission denied for database schemadb\n"
2017-02-16 19:26:40 +00:00
|
|
|
from ansible.module_utils._text import to_native
|
|
|
|
|
2017-07-29 21:14:16 +00:00
|
|
|
|
2016-11-24 18:07:51 +00:00
|
|
|
class NotSupportedError(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
# ===========================================
|
|
|
|
# PostgreSQL module specific support methods.
|
|
|
|
#
|
|
|
|
|
|
|
|
def set_owner(cursor, schema, owner):
|
|
|
|
query = "ALTER SCHEMA %s OWNER TO %s" % (
|
|
|
|
pg_quote_identifier(schema, 'schema'),
|
|
|
|
pg_quote_identifier(owner, 'role'))
|
|
|
|
cursor.execute(query)
|
|
|
|
return True
|
|
|
|
|
2017-12-07 16:27:06 +00:00
|
|
|
|
2016-11-24 18:07:51 +00:00
|
|
|
def get_schema_info(cursor, schema):
|
|
|
|
query = """
|
|
|
|
SELECT schema_owner AS owner
|
|
|
|
FROM information_schema.schemata
|
|
|
|
WHERE schema_name = %(schema)s
|
|
|
|
"""
|
|
|
|
cursor.execute(query, {'schema': schema})
|
|
|
|
return cursor.fetchone()
|
|
|
|
|
2017-12-07 16:27:06 +00:00
|
|
|
|
2016-11-24 18:07:51 +00:00
|
|
|
def schema_exists(cursor, schema):
|
|
|
|
query = "SELECT schema_name FROM information_schema.schemata WHERE schema_name = %(schema)s"
|
|
|
|
cursor.execute(query, {'schema': schema})
|
|
|
|
return cursor.rowcount == 1
|
|
|
|
|
2017-12-07 16:27:06 +00:00
|
|
|
|
2016-11-24 18:07:51 +00:00
|
|
|
def schema_delete(cursor, schema):
|
|
|
|
if schema_exists(cursor, schema):
|
|
|
|
query = "DROP SCHEMA %s" % pg_quote_identifier(schema, 'schema')
|
|
|
|
cursor.execute(query)
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
2017-12-07 16:27:06 +00:00
|
|
|
|
2016-11-24 18:07:51 +00:00
|
|
|
def schema_create(cursor, schema, owner):
|
|
|
|
if not schema_exists(cursor, schema):
|
|
|
|
query_fragments = ['CREATE SCHEMA %s' % pg_quote_identifier(schema, 'schema')]
|
|
|
|
if owner:
|
|
|
|
query_fragments.append('AUTHORIZATION %s' % pg_quote_identifier(owner, 'role'))
|
|
|
|
query = ' '.join(query_fragments)
|
|
|
|
cursor.execute(query)
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
schema_info = get_schema_info(cursor, schema)
|
|
|
|
if owner and owner != schema_info['owner']:
|
|
|
|
return set_owner(cursor, schema, owner)
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
2017-12-07 16:27:06 +00:00
|
|
|
|
2016-11-24 18:07:51 +00:00
|
|
|
def schema_matches(cursor, schema, owner):
|
|
|
|
if not schema_exists(cursor, schema):
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
schema_info = get_schema_info(cursor, schema)
|
|
|
|
if owner and owner != schema_info['owner']:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
|
|
|
|
# ===========================================
|
|
|
|
# Module execution.
|
|
|
|
#
|
|
|
|
|
2017-12-07 16:27:06 +00:00
|
|
|
|
2016-11-24 18:07:51 +00:00
|
|
|
def main():
|
|
|
|
module = AnsibleModule(
|
|
|
|
argument_spec=dict(
|
|
|
|
login_user=dict(default="postgres"),
|
2017-02-09 18:16:54 +00:00
|
|
|
login_password=dict(default="", no_log=True),
|
2016-11-24 18:07:51 +00:00
|
|
|
login_host=dict(default=""),
|
|
|
|
login_unix_socket=dict(default=""),
|
|
|
|
port=dict(default="5432"),
|
|
|
|
schema=dict(required=True, aliases=['name']),
|
|
|
|
owner=dict(default=""),
|
|
|
|
database=dict(default="postgres"),
|
|
|
|
state=dict(default="present", choices=["absent", "present"]),
|
|
|
|
),
|
2017-12-07 16:27:06 +00:00
|
|
|
supports_check_mode=True
|
2016-11-24 18:07:51 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
if not postgresqldb_found:
|
|
|
|
module.fail_json(msg="the python psycopg2 module is required")
|
|
|
|
|
|
|
|
schema = module.params["schema"]
|
|
|
|
owner = module.params["owner"]
|
|
|
|
state = module.params["state"]
|
|
|
|
database = module.params["database"]
|
|
|
|
changed = False
|
|
|
|
|
|
|
|
# To use defaults values, keyword arguments must be absent, so
|
|
|
|
# check which values are empty and don't include in the **kw
|
|
|
|
# dictionary
|
|
|
|
params_map = {
|
2017-12-07 16:27:06 +00:00
|
|
|
"login_host": "host",
|
|
|
|
"login_user": "user",
|
|
|
|
"login_password": "password",
|
|
|
|
"port": "port"
|
2016-11-24 18:07:51 +00:00
|
|
|
}
|
2017-12-07 16:27:06 +00:00
|
|
|
kw = dict((params_map[k], v) for (k, v) in module.params.items()
|
|
|
|
if k in params_map and v != '')
|
2016-11-24 18:07:51 +00:00
|
|
|
|
|
|
|
# If a login_unix_socket is specified, incorporate it here.
|
|
|
|
is_localhost = "host" not in kw or kw["host"] == "" or kw["host"] == "localhost"
|
|
|
|
if is_localhost and module.params["login_unix_socket"] != "":
|
|
|
|
kw["host"] = module.params["login_unix_socket"]
|
|
|
|
|
|
|
|
try:
|
|
|
|
db_connection = psycopg2.connect(database=database, **kw)
|
|
|
|
# Enable autocommit so we can create databases
|
|
|
|
if psycopg2.__version__ >= '2.4.2':
|
|
|
|
db_connection.autocommit = True
|
|
|
|
else:
|
|
|
|
db_connection.set_isolation_level(psycopg2
|
|
|
|
.extensions
|
|
|
|
.ISOLATION_LEVEL_AUTOCOMMIT)
|
|
|
|
cursor = db_connection.cursor(
|
2017-01-29 07:28:53 +00:00
|
|
|
cursor_factory=psycopg2.extras.DictCursor)
|
2017-07-29 21:14:16 +00:00
|
|
|
except Exception as e:
|
fix failing fail_json call in postgresql_schema (#21495)
fix failing fail_json call in postgresql_schema
- Bugfix Pull Request
modules/database/postgresql/postgresql_schema
```
2.3.0
```
Here's an example of the error that was coming out. Massaged some linebreaks and backslashes to make it more readable:
"module_stderr": "Traceback (most recent call last):
File "/tmp/ansible_3X05GE/ansible_module_postgresql_schema.py", line 274, in <module>
main()
File "/tmp/ansible_3X05GE/ansible_module_postgresql_schema.py", line 265, in main
module.fail_json(msg="Database query failed: %s" %(text, str(e)))
NameError: global name 'text' is not defined
",
Now it triggers with the correct exception and shows the traceback. This duplication of str(e) and traceback seems to be the best design pattern.
Sample of the new output:
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_gp4v1Q/ansible_module_postgresql_schema.py", line 254, in main
changed = schema_create(cursor, schema, owner)
...
return super(DictCursor, self).execute(query, vars)
ProgrammingError: permission denied for database schemadb
fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
...
},
"msg": "Database query failed: permission denied for database schemadb\n"
2017-02-16 19:26:40 +00:00
|
|
|
module.fail_json(msg="unable to connect to database: %s" % to_native(e), exception=traceback.format_exc())
|
2016-11-24 18:07:51 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
if module.check_mode:
|
|
|
|
if state == "absent":
|
|
|
|
changed = not schema_exists(cursor, schema)
|
|
|
|
elif state == "present":
|
|
|
|
changed = not schema_matches(cursor, schema, owner)
|
|
|
|
module.exit_json(changed=changed, schema=schema)
|
|
|
|
|
|
|
|
if state == "absent":
|
|
|
|
try:
|
|
|
|
changed = schema_delete(cursor, schema)
|
2017-07-29 21:14:16 +00:00
|
|
|
except SQLParseError as e:
|
|
|
|
module.fail_json(msg=to_native(e), exception=traceback.format_exc())
|
2016-11-24 18:07:51 +00:00
|
|
|
|
|
|
|
elif state == "present":
|
|
|
|
try:
|
|
|
|
changed = schema_create(cursor, schema, owner)
|
2017-07-29 21:14:16 +00:00
|
|
|
except SQLParseError as e:
|
|
|
|
module.fail_json(msg=to_native(e), exception=traceback.format_exc())
|
|
|
|
except NotSupportedError as e:
|
|
|
|
module.fail_json(msg=to_native(e), exception=traceback.format_exc())
|
2016-11-24 18:07:51 +00:00
|
|
|
except SystemExit:
|
|
|
|
# Avoid catching this on Python 2.4
|
|
|
|
raise
|
2017-07-29 21:14:16 +00:00
|
|
|
except Exception as e:
|
fix failing fail_json call in postgresql_schema (#21495)
fix failing fail_json call in postgresql_schema
- Bugfix Pull Request
modules/database/postgresql/postgresql_schema
```
2.3.0
```
Here's an example of the error that was coming out. Massaged some linebreaks and backslashes to make it more readable:
"module_stderr": "Traceback (most recent call last):
File "/tmp/ansible_3X05GE/ansible_module_postgresql_schema.py", line 274, in <module>
main()
File "/tmp/ansible_3X05GE/ansible_module_postgresql_schema.py", line 265, in main
module.fail_json(msg="Database query failed: %s" %(text, str(e)))
NameError: global name 'text' is not defined
",
Now it triggers with the correct exception and shows the traceback. This duplication of str(e) and traceback seems to be the best design pattern.
Sample of the new output:
An exception occurred during task execution. The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_gp4v1Q/ansible_module_postgresql_schema.py", line 254, in main
changed = schema_create(cursor, schema, owner)
...
return super(DictCursor, self).execute(query, vars)
ProgrammingError: permission denied for database schemadb
fatal: [localhost]: FAILED! => {
"changed": false,
"failed": true,
...
},
"msg": "Database query failed: permission denied for database schemadb\n"
2017-02-16 19:26:40 +00:00
|
|
|
module.fail_json(msg="Database query failed: %s" % to_native(e), exception=traceback.format_exc())
|
2016-11-24 18:07:51 +00:00
|
|
|
|
|
|
|
module.exit_json(changed=changed, schema=schema)
|
|
|
|
|
2016-11-24 18:35:53 +00:00
|
|
|
|
2016-11-24 18:07:51 +00:00
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|