postgresql_schema: doc fix, return value, usage pg_utils (#54237)

* instead_of_31970

* instead_of_31970: fix
pull/54214/head
Andrey Klychkov 6 years ago committed by John R Barker
parent 9aa1360867
commit a1639f27d5

@ -7,114 +7,138 @@
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
DOCUMENTATION = r'''
---
module: postgresql_schema
short_description: Add or remove PostgreSQL schema from a remote host
short_description: Add or remove PostgreSQL schema
description:
- Add or remove PostgreSQL schema from a remote host.
version_added: "2.3"
- Add or remove PostgreSQL schema.
version_added: '2.3'
options:
name:
description:
- Name of the schema to add or remove.
- Name of the schema to add or remove.
required: true
type: str
database:
description:
- Name of the database to connect to.
- Name of the database to connect to and add or remove the schema.
type: str
default: postgres
aliases:
- db
- login_db
login_user:
description:
- The username used to authenticate with.
- The username used to authenticate with.
type: str
login_password:
description:
- The password used to authenticate with.
- The password used to authenticate with.
type: str
login_host:
description:
- Host running the database.
- Host running the database.
type: str
default: localhost
login_unix_socket:
description:
- Path to a Unix domain socket for local connections.
- Path to a Unix domain socket for local connections.
type: str
owner:
description:
- Name of the role to set as owner of the schema.
- Name of the role to set as owner of the schema.
type: str
port:
description:
- Database port to connect to.
- Database port to connect to.
type: int
default: 5432
aliases:
- login_port
session_role:
version_added: "2.8"
description: |
Switch to session_role after connecting. The specified session_role must be a role that the current login_user is a member of.
Permissions checking for SQL commands is carried out as though the session_role were the one that had logged in originally.
version_added: '2.8'
description:
- Switch to session_role after connecting.
- The specified session_role must be a role that the current login_user is a member of.
- Permissions checking for SQL commands is carried out as though the session_role
were the one that had logged in originally.
type: str
state:
description:
- The schema state.
- The schema state.
type: str
default: present
choices: [ "present", "absent" ]
choices: [ absent, present ]
cascade_drop:
description:
- Drop schema with CASCADE to remove child objects
- Drop schema with CASCADE to remove child objects.
type: bool
default: false
version_added: '2.8'
ssl_mode:
description:
- Determines whether or with what priority a secure SSL TCP/IP connection
will be negotiated with the server.
- See U(https://www.postgresql.org/docs/current/static/libpq-ssl.html) for
more information on the modes.
- Default of C(prefer) matches libpq default.
- Determines whether or with what priority a secure SSL TCP/IP connection
will be negotiated with the server.
- See U(https://www.postgresql.org/docs/current/static/libpq-ssl.html) for
more information on the modes.
- Default of C(prefer) matches libpq default.
type: str
default: prefer
choices: ["disable", "allow", "prefer", "require", "verify-ca", "verify-full"]
choices: [ allow, disable, prefer, require, verify-ca, verify-full ]
version_added: '2.8'
ssl_rootcert:
description:
- Specifies the name of a file containing SSL certificate authority (CA)
certificate(s). If the file exists, the server's certificate will be
verified to be signed by one of these authorities.
- Specifies the name of a file containing SSL certificate authority (CA) certificate(s).
- If the file exists, the server's certificate will be verified to be signed by one of these authorities.
type: str
version_added: '2.8'
notes:
- This module uses I(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 C(postgresql), C(libpq-dev), and C(python-psycopg2) packages on the remote host before
using this module.
- This module uses I(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 C(postgresql), C(libpq-dev),
and C(python-psycopg2) packages on the remote host before using this module.
requirements: [ psycopg2 ]
author:
- Flavien Chantelot (@Dorn-) <contact@flavien.io>
- Thomas O'Donnell (@andytom)
- Flavien Chantelot (@Dorn-) <contact@flavien.io>
- Thomas O'Donnell (@andytom)
'''
EXAMPLES = '''
# Create a new schema with name "acme"
- postgresql_schema:
EXAMPLES = r'''
- name: Create a new schema with name acme in test database
postgresql_schema:
db: test
name: acme
# Create a new schema "acme" with a user "bob" who will own it
- postgresql_schema:
- name: Create a new schema acme with a user bob who will own it
postgresql_schema:
name: acme
owner: bob
# Drop schema "acme" with cascade
- postgresql_schema:
- name: Drop schema "acme" with cascade
postgresql_schema:
name: acme
ensure: absent
cascade_drop: yes
'''
RETURN = '''
RETURN = r'''
schema:
description: Name of the schema
returned: success, changed
type: str
sample: "acme"
description: Name of the schema.
returned: success, changed
type: str
sample: "acme"
queries:
description: List of executed queries.
returned: always
type: list
sample: ["CREATE SCHEMA \"acme\""]
'''
import traceback
@ -123,17 +147,19 @@ PSYCOPG2_IMP_ERR = None
try:
import psycopg2
import psycopg2.extras
HAS_PSYCOPG2 = True
except ImportError:
PSYCOPG2_IMP_ERR = traceback.format_exc()
postgresqldb_found = False
else:
postgresqldb_found = True
HAS_PSYCOPG2 = False
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.postgres import postgres_common_argument_spec
from ansible.module_utils.database import SQLParseError, pg_quote_identifier
from ansible.module_utils.six import iteritems
from ansible.module_utils._text import to_native
executed_queries = []
class NotSupportedError(Exception):
pass
@ -148,22 +174,22 @@ def set_owner(cursor, schema, owner):
pg_quote_identifier(schema, 'schema'),
pg_quote_identifier(owner, 'role'))
cursor.execute(query)
executed_queries.append(query)
return True
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})
query = ("SELECT schema_owner AS owner "
"FROM information_schema.schemata "
"WHERE schema_name = '%s'" % schema)
cursor.execute(query)
return cursor.fetchone()
def schema_exists(cursor, schema):
query = "SELECT schema_name FROM information_schema.schemata WHERE schema_name = %(schema)s"
cursor.execute(query, {'schema': schema})
query = ("SELECT schema_name FROM information_schema.schemata "
"WHERE schema_name = '%s'" % schema)
cursor.execute(query)
return cursor.rowcount == 1
@ -173,6 +199,7 @@ def schema_delete(cursor, schema, cascade):
if cascade:
query += " CASCADE"
cursor.execute(query)
executed_queries.append(query)
return True
else:
return False
@ -185,6 +212,7 @@ def schema_create(cursor, schema, owner):
query_fragments.append('AUTHORIZATION %s' % pg_quote_identifier(owner, 'role'))
query = ' '.join(query_fragments)
cursor.execute(query)
executed_queries.append(query)
return True
else:
schema_info = get_schema_info(cursor, schema)
@ -210,27 +238,30 @@ def schema_matches(cursor, schema, owner):
def main():
argument_spec = postgres_common_argument_spec()
argument_spec.update(
login_user=dict(type="str", default="postgres"),
login_password=dict(type="str", default="", no_log=True),
login_host=dict(type="str", default=""),
login_unix_socket=dict(type="str", default=""),
port=dict(type="int", default=5432, aliases=["login_port"]),
schema=dict(type="str", required=True, aliases=['name']),
owner=dict(type="str", default=""),
database=dict(type="str", default="postgres", aliases=["db", "login_db"]),
cascade_drop=dict(type="bool", default=False),
state=dict(type="str", default="present", choices=["absent", "present"]),
ssl_mode=dict(type="str", default='prefer', choices=[
'disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full']),
ssl_rootcert=dict(type="str", default=None),
session_role=dict(type="str"),
)
module = AnsibleModule(
argument_spec=dict(
login_user=dict(default="postgres"),
login_password=dict(default="", no_log=True),
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"),
cascade_drop=dict(type="bool", default=False),
state=dict(default="present", choices=["absent", "present"]),
ssl_mode=dict(default='prefer', choices=[
'disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full']),
ssl_rootcert=dict(default=None),
session_role=dict(),
),
supports_check_mode=True
argument_spec=argument_spec,
supports_check_mode=True,
)
if not postgresqldb_found:
if not HAS_PSYCOPG2:
module.fail_json(msg=missing_required_lib('psycopg2'), exception=PSYCOPG2_IMP_ERR)
schema = module.params["schema"]
@ -319,7 +350,7 @@ def main():
except Exception as e:
module.fail_json(msg="Database query failed: %s" % to_native(e), exception=traceback.format_exc())
module.exit_json(changed=changed, schema=schema)
module.exit_json(changed=changed, schema=schema, queries=executed_queries)
if __name__ == '__main__':

Loading…
Cancel
Save