def main(): argument_spec = pgutils.postgres_common_argument_spec() argument_spec.update(dict( db=dict(required=True, aliases=['name']), owner=dict(default=""), template=dict(default=""), encoding=dict(default=""), lc_collate=dict(default=""), lc_ctype=dict(default=""), state=dict(default="present", choices=["absent", "present", "dump", "restore"]), target=dict(default="", type="path"), target_opts=dict(default=""), maintenance_db=dict(default="postgres"), )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) if not HAS_PSYCOPG2: module.fail_json(msg="the python psycopg2 module is required") db = module.params["db"] owner = module.params["owner"] template = module.params["template"] encoding = module.params["encoding"] lc_collate = module.params["lc_collate"] lc_ctype = module.params["lc_ctype"] target = module.params["target"] target_opts = module.params["target_opts"] state = module.params["state"] changed = False maintenance_db = module.params['maintenance_db'] # 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 = { "login_host": "host", "login_user": "******", "login_password": "******", "port": "port", "ssl_mode": "sslmode", "ssl_rootcert": "sslrootcert" } kw = dict((params_map[k], v) for (k, v) in iteritems(module.params) if k in params_map and v != '' and v is not None) # 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"] if target == "": target = "{0}/{1}.sql".format(os.getcwd(), db) target = os.path.expanduser(target) try: pgutils.ensure_libs(sslrootcert=module.params.get('ssl_rootcert')) db_connection = psycopg2.connect(database=maintenance_db, **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(cursor_factory=psycopg2.extras.DictCursor) except pgutils.LibraryError as e: module.fail_json(msg="unable to connect to database: {0}".format(to_native(e)), exception=traceback.format_exc()) except TypeError as e: if 'sslrootcert' in e.args[0]: module.fail_json(msg='Postgresql server must be at least version 8.4 to support sslrootcert. Exception: {0}'.format(to_native(e)), exception=traceback.format_exc()) module.fail_json(msg="unable to connect to database: %s" % to_native(e), exception=traceback.format_exc()) except Exception as e: module.fail_json(msg="unable to connect to database: %s" % to_native(e), exception=traceback.format_exc()) try: if module.check_mode: if state == "absent": changed = db_exists(cursor, db) elif state == "present": changed = not db_matches(cursor, db, owner, template, encoding, lc_collate, lc_ctype) module.exit_json(changed=changed, db=db) if state == "absent": try: changed = db_delete(cursor, db) except SQLParseError as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) elif state == "present": try: changed = db_create(cursor, db, owner, template, encoding, lc_collate, lc_ctype) except SQLParseError as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) elif state in ("dump", "restore"): method = state == "dump" and db_dump or db_restore try: rc, stdout, stderr, cmd = method(module, target, target_opts, db, **kw) if rc != 0: module.fail_json(msg=stderr, stdout=stdout, rc=rc, cmd=cmd) else: module.exit_json(changed=True, msg=stdout, stderr=stderr, rc=rc, cmd=cmd) 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()) except SystemExit: # Avoid catching this on Python 2.4 raise except Exception as e: module.fail_json(msg="Database query failed: %s" % to_native(e), exception=traceback.format_exc()) module.exit_json(changed=changed, db=db)
def main(): argument_spec = pgutils.postgres_common_argument_spec() argument_spec.update(db=dict(type='str', required=True, aliases=['name']), owner=dict(type='str', default=''), template=dict(type='str', default=''), encoding=dict(type='str', default=''), lc_collate=dict(type='str', default=''), lc_ctype=dict(type='str', default=''), state=dict( type='str', default='present', choices=['absent', 'dump', 'present', 'restore']), target=dict(type='path', default=''), target_opts=dict(type='str', default=''), maintenance_db=dict(type='str', default="postgres"), session_role=dict(type='str'), conn_limit=dict(type='str', default='')) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) db = module.params["db"] owner = module.params["owner"] template = module.params["template"] encoding = module.params["encoding"] lc_collate = module.params["lc_collate"] lc_ctype = module.params["lc_ctype"] target = module.params["target"] target_opts = module.params["target_opts"] state = module.params["state"] changed = False maintenance_db = module.params['maintenance_db'] session_role = module.params["session_role"] conn_limit = module.params['conn_limit'] raw_connection = state in ("dump", "restore") if not HAS_PSYCOPG2 and not raw_connection: module.fail_json(msg=missing_required_lib('psycopg2'), exception=PSYCOPG2_IMP_ERR) # 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 = { "login_host": "host", "login_user": "******", "login_password": "******", "port": "port", "ssl_mode": "sslmode", "ca_cert": "sslrootcert" } kw = dict((params_map[k], v) for (k, v) in iteritems(module.params) if k in params_map and v != '' and v is not None) # 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"] if target == "": target = "{0}/{1}.sql".format(os.getcwd(), db) target = os.path.expanduser(target) if not raw_connection: try: pgutils.ensure_libs(sslrootcert=module.params.get('ca_cert')) db_connection = psycopg2.connect(database=maintenance_db, **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( cursor_factory=psycopg2.extras.DictCursor) except pgutils.LibraryError as e: module.fail_json(msg="unable to connect to database: {0}".format( to_native(e)), exception=traceback.format_exc()) except TypeError as e: if 'sslrootcert' in e.args[0]: module.fail_json( msg= 'Postgresql server must be at least version 8.4 to support sslrootcert. Exception: {0}' .format(to_native(e)), exception=traceback.format_exc()) module.fail_json(msg="unable to connect to database: %s" % to_native(e), exception=traceback.format_exc()) except Exception as e: module.fail_json(msg="unable to connect to database: %s" % to_native(e), exception=traceback.format_exc()) if session_role: try: cursor.execute('SET ROLE %s' % pg_quote_identifier(session_role, 'role')) except Exception as e: module.fail_json(msg="Could not switch role: %s" % to_native(e), exception=traceback.format_exc()) try: if module.check_mode: if state == "absent": changed = db_exists(cursor, db) elif state == "present": changed = not db_matches(cursor, db, owner, template, encoding, lc_collate, lc_ctype, conn_limit) module.exit_json(changed=changed, db=db) if state == "absent": try: changed = db_delete(cursor, db) except SQLParseError as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) elif state == "present": try: changed = db_create(cursor, db, owner, template, encoding, lc_collate, lc_ctype, conn_limit) except SQLParseError as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) elif state in ("dump", "restore"): method = state == "dump" and db_dump or db_restore try: rc, stdout, stderr, cmd = method(module, target, target_opts, db, **kw) if rc != 0: module.fail_json(msg='Dump of database %s failed' % db, stdout=stdout, stderr=stderr, rc=rc, cmd=cmd) elif stderr and 'warning' not in str(stderr): module.fail_json(msg='Dump of database %s failed' % db, stdout=stdout, stderr=stderr, rc=1, cmd=cmd) else: module.exit_json(changed=True, msg='Dump of database %s has been done' % db, stdout=stdout, stderr=stderr, rc=rc, cmd=cmd) 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()) except SystemExit: # Avoid catching this on Python 2.4 raise except Exception as e: module.fail_json(msg="Database query failed: %s" % to_native(e), exception=traceback.format_exc()) module.exit_json(changed=changed, db=db)
def main(): argument_spec = pgutils.postgres_common_argument_spec() argument_spec.update( dict( db=dict(required=True, aliases=['name']), owner=dict(default=""), template=dict(default=""), encoding=dict(default=""), lc_collate=dict(default=""), lc_ctype=dict(default=""), state=dict(default="present", choices=["absent", "present", "dump", "restore"]), target=dict(default=""), target_opts=dict(default=""), )) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if not HAS_PSYCOPG2: module.fail_json(msg="the python psycopg2 module is required") db = module.params["db"] port = module.params["port"] owner = module.params["owner"] template = module.params["template"] encoding = module.params["encoding"] lc_collate = module.params["lc_collate"] lc_ctype = module.params["lc_ctype"] target = module.params["target"] target_opts = module.params["target_opts"] state = module.params["state"] sslrootcert = module.params["ssl_rootcert"] 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 = { "login_host": "host", "login_user": "******", "login_password": "******", "port": "port", "ssl_mode": "sslmode", "ssl_rootcert": "sslrootcert" } kw = dict((params_map[k], v) for (k, v) in iteritems(module.params) if k in params_map and v != '' and v is not None) # 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"] if target == "": target = "{0}/{1}.sql".format(os.getcwd(), db) target = os.path.expanduser(target) else: target = os.path.expanduser(target) try: pgutils.ensure_libs(sslrootcert=module.params.get('ssl_rootcert')) db_connection = psycopg2.connect(database="postgres", **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( cursor_factory=psycopg2.extras.DictCursor) except pgutils.LibraryError: e = get_exception() module.fail_json(msg="unable to connect to database: {0}".format( str(e)), exception=traceback.format_exc()) except TypeError: e = get_exception() if 'sslrootcert' in e.args[0]: module.fail_json( msg= 'Postgresql server must be at least version 8.4 to support sslrootcert. Exception: {0}' .format(e), exception=traceback.format_exc()) module.fail_json(msg="unable to connect to database: %s" % e, exception=traceback.format_exc()) except Exception: e = get_exception() module.fail_json(msg="unable to connect to database: %s" % e, exception=traceback.format_exc()) try: if module.check_mode: if state == "absent": changed = db_exists(cursor, db) elif state == "present": changed = not db_matches(cursor, db, owner, template, encoding, lc_collate, lc_ctype) module.exit_json(changed=changed, db=db) if state == "absent": try: changed = db_delete(cursor, db) except SQLParseError: e = get_exception() module.fail_json(msg=str(e)) elif state == "present": try: changed = db_create(cursor, db, owner, template, encoding, lc_collate, lc_ctype) except SQLParseError: e = get_exception() module.fail_json(msg=str(e)) elif state in ("dump", "restore"): method = state == "dump" and db_dump or db_restore try: rc, stdout, stderr, cmd = method(module, target, target_opts, db, **kw) if rc != 0: module.fail_json(msg=stderr, stdout=stdout, rc=rc, cmd=cmd) else: module.exit_json(changed=True, msg=stdout, stderr=stderr, rc=rc, cmd=cmd) except SQLParseError: e = get_exception() module.fail_json(msg=str(e)) except NotSupportedError: e = get_exception() module.fail_json(msg=str(e)) except SystemExit: # Avoid catching this on Python 2.4 raise except Exception: e = get_exception() module.fail_json(msg="Database query failed: %s" % e) module.exit_json(changed=changed, db=db)
def main(): argument_spec = pgutils.postgres_common_argument_spec() argument_spec.update( dict( db=dict(required=True, aliases=['name']), state=dict(default="present", choices=["absent", "present"]), maintenance_db=dict(default="postgres"), )) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if not HAS_PSYCOPG2: module.fail_json(msg="the python psycopg2 module is required") db = module.params["db"] state = module.params["state"] changed = False maintenance_db = module.params['maintenance_db'] # 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 = { "login_host": "host", "login_user": "******", "login_password": "******", "port": "port", "ssl_mode": "sslmode", "ssl_rootcert": "sslrootcert" } kw = dict((params_map[k], v) for (k, v) in iteritems(module.params) if k in params_map and v != '' and v is not None) # If a login_unix_socket is specified, incorporate it here. is_localhost = "host" not in kw or kw["host"] == "" or kw[ "host"] == "localhost" try: pgutils.ensure_libs(sslrootcert=module.params.get('ssl_rootcert')) db_connection = psycopg2.connect(database=maintenance_db, **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( cursor_factory=psycopg2.extras.DictCursor) except pgutils.LibraryError as e: module.fail_json(msg="unable to connect to database: {0}".format( to_native(e)), exception=traceback.format_exc()) except TypeError as e: if 'sslrootcert' in e.args[0]: module.fail_json( msg= 'Postgresql server must be at least version 8.4 to support sslrootcert. Exception: {0}' .format(to_native(e)), exception=traceback.format_exc()) module.fail_json(msg="unable to connect to database: %s" % to_native(e), exception=traceback.format_exc()) except Exception as e: module.fail_json(msg="unable to connect to database: %s" % to_native(e), exception=traceback.format_exc()) try: if module.check_mode: if state == "absent": changed = db_exists(cursor, db) elif state == "present": changed = not db_matches(cursor, db) module.exit_json(changed=changed, db=db) if state == "absent": try: changed = db_delete(cursor, db) except SQLParseError as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) elif state == "present": try: changed = db_create(cursor, db) 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()) except SystemExit: # Avoid catching this on Python 2.4 raise except Exception as e: module.fail_json(msg="Database query failed: %s" % to_native(e), exception=traceback.format_exc()) module.exit_json(changed=changed, db=db)
def main(): """Main execution path.""" argument_spec = postgres_utils.postgres_common_argument_spec() argument_spec.update({'db': {'type': 'str', 'default': ''}, 'query': {'required': True, 'type': 'str'}, 'as_dict': {'type': 'bool', 'choices': BOOLEANS, 'default': False}}) module = AnsibleModule(argument_spec=argument_spec) if not HAS_LIB: module.fail_json(msg='psycopg2 is required for this module') psycopg_connect_map = { 'login_host': 'host', 'port': 'port', 'login_user': '******', 'login_password': '******', 'ssl_mode': 'sslmode', 'ssl_rootcert': 'sslrootcert', 'db': 'dbname' } # Taken from postgresql_db module psycopg_connect_args = dict( (psycopg_connect_map[k], v) for (k, v) in module.params.iteritems() if k in psycopg_connect_map and v is not None and v != '' ) if ('host' not in psycopg_connect_args or psycopg_connect_args['host'] == 'localhost') and \ module.params['login_unix_socket'] != '': psycopg_connect_args['host'] = module.params['login_unix_socket'] try: postgres_utils.ensure_libs(sslrootcert=module.params.get('ssl_rootcert')) db_connection = psycopg2.connect(**psycopg_connect_args) if module.params['as_dict']: cursor_factory = RealDictCursor else: cursor_factory = DictCursor cursor = db_connection.cursor(cursor_factory=cursor_factory) except TypeError as ex: if 'sslrootcert' in ex.args[0]: module.fail_json( msg='Postgresql server must be at least version 8.4 to support sslrootcert' ) module.fail_json(msg='Unable to connect to database: {}'.format(ex)) except (postgres_utils.LibraryError, psycopg2.Error) as ex: module.fail_json(msg='Unable to connect to database: {}'.format(ex)) try: cursor.execute(module.params['query']) db_connection.commit() result = None if cursor.description is not None: result = _json_serialize(cursor.fetchall()) statusmessage = cursor.statusmessage changed = cursor.rowcount != 0 cursor.close() except psycopg2.Error as ex: module.fail_json(msg='Unable to execute query: {}'.format(ex), errno=ex.pgcode) finally: if db_connection is not None: db_connection.close() module.exit_json(changed=changed, result=result, statusmessage=statusmessage)