Postgresql privs reformat (#54717)

* postgresql_privs: fix doc format, pgutils

* postgresql_privs: added pgutils, ret value

* postgresql_privs: fix test

* postgresql_privs: fixes

* postgresql_privs: fixes

* postgresql_privs: fixed CI
pull/54741/head
Andrey Klychkov 5 years ago committed by John R Barker
parent 7ea01da38f
commit 40f65a54ec

@ -55,7 +55,7 @@ def postgres_common_argument_spec():
login_password=dict(default='', no_log=True), login_password=dict(default='', no_log=True),
login_host=dict(default=''), login_host=dict(default=''),
login_unix_socket=dict(default=''), login_unix_socket=dict(default=''),
port=dict(type='int', default=5432), port=dict(type='int', default=5432, aliases=['login_port']),
ssl_mode=dict(default='prefer', choices=['disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full']), ssl_mode=dict(default='prefer', choices=['allow', 'disable', 'prefer', 'require', 'verify-ca', 'verify-full']),
ca_cert=dict(aliases=['ssl_rootcert']), ca_cert=dict(aliases=['ssl_rootcert']),
) )

@ -21,10 +21,17 @@ version_added: "0.6"
options: options:
name: name:
description: description:
- name of the database to add or remove - Name of the database to add or remove
type: str type: str
required: true required: true
aliases: [ db ] aliases: [ db ]
port:
description:
- Database port to connect (if needed)
type: int
default: 5432
aliases:
- login_port
owner: owner:
description: description:
- Name of the role to set as owner of the database - Name of the role to set as owner of the database

@ -33,11 +33,15 @@ options:
description: description:
- Name of database where the index will be created/dropped. - Name of database where the index will be created/dropped.
type: str type: str
aliases:
- login_db
port: port:
description: description:
- Database port to connect. - Database port to connect.
type: int type: int
default: 5432 default: 5432
aliases:
- login_port
login_user: login_user:
description: description:
- User (role) used to authenticate with PostgreSQL. - User (role) used to authenticate with PostgreSQL.
@ -432,9 +436,7 @@ def main():
argument_spec = postgres_common_argument_spec() argument_spec = postgres_common_argument_spec()
argument_spec.update( argument_spec.update(
idxname=dict(type='str', required=True, aliases=['name']), idxname=dict(type='str', required=True, aliases=['name']),
db=dict(type='str'), db=dict(type='str', aliases=['login_db']),
ssl_mode=dict(type='str', default='prefer', choices=['allow', 'disable', 'prefer', 'require', 'verify-ca', 'verify-full']),
ca_cert=dict(type='str', aliases=['ssl_rootcert']),
state=dict(type='str', default='present', choices=['absent', 'present']), state=dict(type='str', default='present', choices=['absent', 'present']),
concurrent=dict(type='bool', default=True), concurrent=dict(type='bool', default=True),
table=dict(type='str'), table=dict(type='str'),

@ -25,11 +25,15 @@ options:
description: description:
- Name of database to connect. - Name of database to connect.
type: str type: str
aliases:
- login_db
port: port:
description: description:
- Database port to connect. - Database port to connect.
type: int type: int
default: 5432 default: 5432
aliases:
- login_port
login_user: login_user:
description: description:
- User (role) used to authenticate with PostgreSQL. - User (role) used to authenticate with PostgreSQL.
@ -171,9 +175,7 @@ class PgPing(object):
def main(): def main():
argument_spec = postgres_common_argument_spec() argument_spec = postgres_common_argument_spec()
argument_spec.update( argument_spec.update(
db=dict(type='str'), db=dict(type='str', aliases=['login_db']),
ssl_mode=dict(type='str', default='prefer', choices=['allow', 'disable', 'prefer', 'require', 'verify-ca', 'verify-full']),
ca_cert=dict(type='str', aliases=['ssl_rootcert']),
) )
module = AnsibleModule( module = AnsibleModule(
argument_spec=argument_spec, argument_spec=argument_spec,

@ -11,160 +11,190 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'], 'status': ['stableinterface'],
'supported_by': 'community'} 'supported_by': 'community'}
DOCUMENTATION = """ DOCUMENTATION = r'''
--- ---
module: postgresql_privs module: postgresql_privs
version_added: "1.2" version_added: '1.2'
short_description: Grant or revoke privileges on PostgreSQL database objects. short_description: Grant or revoke privileges on PostgreSQL database objects
description: description:
- Grant or revoke privileges on PostgreSQL database objects. - Grant or revoke privileges on PostgreSQL database objects.
- This module is basically a wrapper around most of the functionality of - This module is basically a wrapper around most of the functionality of
PostgreSQL's GRANT and REVOKE statements with detection of changes PostgreSQL's GRANT and REVOKE statements with detection of changes
(GRANT/REVOKE I(privs) ON I(type) I(objs) TO/FROM I(roles)) (GRANT/REVOKE I(privs) ON I(type) I(objs) TO/FROM I(roles)).
options: options:
database: database:
description: description:
- Name of database to connect to. - Name of database to connect to.
- 'Alias: I(db)'
required: yes required: yes
type: str
aliases:
- db
- login_db
state: state:
description: description:
- If C(present), the specified privileges are granted, if C(absent) they - If C(present), the specified privileges are granted, if C(absent) they are revoked.
are revoked. type: str
default: present default: present
choices: [present, absent] choices: [ absent, present ]
privs: privs:
description: description:
- Comma separated list of privileges to grant/revoke. - Comma separated list of privileges to grant/revoke.
- 'Alias: I(priv)' type: str
aliases:
- priv
type: type:
description: description:
- Type of database object to set privileges on. - Type of database object to set privileges on.
- The `default_prives` choice is available starting at version 2.7. - The `default_prives` choice is available starting at version 2.7.
- The 'foreign_data_wrapper' and 'foreign_server' object types are available from Ansible version '2.8'. - The 'foreign_data_wrapper' and 'foreign_server' object types are available from Ansible version '2.8'.
type: str
default: table default: table
choices: [table, sequence, function, database, choices: [ database, default_privs, foreign_data_wrapper, foreign_server, function,
schema, language, tablespace, group, group, language, table, tablespace, schema, sequence ]
default_privs, foreign_data_wrapper, foreign_server]
objs: objs:
description: description:
- Comma separated list of database objects to set privileges on. - Comma separated list of database objects to set privileges on.
- If I(type) is C(table), C(sequence) or C(function), the special value - If I(type) is C(table), C(sequence) or C(function), the special value
C(ALL_IN_SCHEMA) can be provided instead to specify all database C(ALL_IN_SCHEMA) can be provided instead to specify all database
objects of type I(type) in the schema specified via I(schema). (This objects of type I(type) in the schema specified via I(schema). (This
also works with PostgreSQL < 9.0.) (C(ALL_IN_SCHEMA) is available for also works with PostgreSQL < 9.0.) (C(ALL_IN_SCHEMA) is available for
C(function) from version 2.8) C(function) from version 2.8)
- If I(type) is C(database), this parameter can be omitted, in which case - If I(type) is C(database), this parameter can be omitted, in which case
privileges are set for the database specified via I(database). privileges are set for the database specified via I(database).
- 'If I(type) is I(function), colons (":") in object names will be - 'If I(type) is I(function), colons (":") in object names will be
replaced with commas (needed to specify function signatures, see replaced with commas (needed to specify function signatures, see examples)'
examples)' type: str
- 'Alias: I(obj)' aliases:
- obj
schema: schema:
description: description:
- Schema that contains the database objects specified via I(objs). - Schema that contains the database objects specified via I(objs).
- May only be provided if I(type) is C(table), C(sequence), C(function) - May only be provided if I(type) is C(table), C(sequence), C(function)
or C(default_privs). Defaults to C(public) in these cases. or C(default_privs). Defaults to C(public) in these cases.
type: str
roles: roles:
description: description:
- Comma separated list of role (user/group) names to set permissions for. - Comma separated list of role (user/group) names to set permissions for.
- The special value C(PUBLIC) can be provided instead to set permissions - The special value C(PUBLIC) can be provided instead to set permissions
for the implicitly defined PUBLIC group. for the implicitly defined PUBLIC group.
- 'Alias: I(role)' type: str
required: yes required: yes
aliases:
- role
fail_on_role: fail_on_role:
version_added: "2.8" version_added: '2.8'
description: description:
- If C(yes), fail when target role (for whom privs need to be granted) does not exist. - If C(yes), fail when target role (for whom privs need to be granted) does not exist.
Otherwise just warn and continue. Otherwise just warn and continue.
default: yes default: yes
type: bool type: bool
session_role: session_role:
version_added: "2.8" version_added: '2.8'
description: | description:
Switch to session_role after connecting. The specified session_role must be a role that the current login_user is a member of. - Switch to session_role after connecting.
Permissions checking for SQL commands is carried out as though the session_role were the one that had logged in originally. - 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
target_roles: target_roles:
description: description:
- A list of existing role (user/group) names to set as the - A list of existing role (user/group) names to set as the
default permissions for database objects subsequently created by them. default permissions for database objects subsequently created by them.
- Parameter I(target_roles) is only available with C(type=default_privs). - Parameter I(target_roles) is only available with C(type=default_privs).
type: str
version_added: '2.8' version_added: '2.8'
grant_option: grant_option:
description: description:
- Whether C(role) may grant/revoke the specified privileges/group - Whether C(role) may grant/revoke the specified privileges/group memberships to others.
memberships to others. - Set to C(no) to revoke GRANT OPTION, leave unspecified to make no changes.
- Set to C(no) to revoke GRANT OPTION, leave unspecified to - I(grant_option) only has an effect if I(state) is C(present).
make no changes.
- I(grant_option) only has an effect if I(state) is C(present).
- 'Alias: I(admin_option)'
type: bool type: bool
aliases:
- admin_option
host: host:
description: description:
- Database host address. If unspecified, connect via Unix socket. - Database host address. If unspecified, connect via Unix socket.
- 'Alias: I(login_host)' type: str
aliases:
- login_host
port: port:
description: description:
- Database port to connect to. - Database port to connect to.
type: int
default: 5432 default: 5432
aliases:
- login_port
unix_socket: unix_socket:
description: description:
- Path to a Unix domain socket for local connections. - Path to a Unix domain socket for local connections.
- 'Alias: I(login_unix_socket)' type: str
aliases:
- login_unix_socket
login: login:
description: description:
- The username to authenticate with. - The username to authenticate with.
- 'Alias: I(login_user)' type: str
default: postgres default: postgres
aliases:
- login_user
password: password:
description: description:
- The password to authenticate with. - The password to authenticate with.
- 'Alias: I(login_password))' type: str
aliases:
- login_password
ssl_mode: ssl_mode:
description: description:
- Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server. - Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server.
- See https://www.postgresql.org/docs/current/static/libpq-ssl.html for more information on the modes. - See https://www.postgresql.org/docs/current/static/libpq-ssl.html for more information on the modes.
- Default of C(prefer) matches libpq default. - Default of C(prefer) matches libpq default.
type: str
default: prefer default: prefer
choices: [disable, allow, prefer, require, verify-ca, verify-full] choices: [ allow, disable, prefer, require, verify-ca, verify-full ]
version_added: '2.3' version_added: '2.3'
ca_cert: ca_cert:
description: description:
- Specifies the name of a file containing SSL certificate authority (CA) certificate(s). If the file exists, the server's certificate will be - Specifies the name of a file containing SSL certificate authority (CA) certificate(s).
verified to be signed by one of these authorities. - If the file exists, the server's certificate will be verified to be signed by one of these authorities.
version_added: '2.3' version_added: '2.3'
aliases: [ ssl_rootcert ] type: str
aliases:
- ssl_rootcert
notes: notes:
- Default authentication assumes that postgresql_privs is run by the - Default authentication assumes that postgresql_privs is run by the
C(postgres) user on the remote host. (Ansible's C(user) or C(sudo-user)). C(postgres) user on the remote host. (Ansible's C(user) or C(sudo-user)).
- This module requires Python package I(psycopg2) to be installed on the - This module requires Python package I(psycopg2) to be installed on the
remote host. In the default case of the remote host also being the remote host. In the default case of the remote host also being the
PostgreSQL server, PostgreSQL has to be installed there as well, obviously. PostgreSQL server, PostgreSQL has to be installed there as well, obviously.
For Debian/Ubuntu-based systems, install packages I(postgresql) and For Debian/Ubuntu-based systems, install packages I(postgresql) and I(python-psycopg2).
I(python-psycopg2). - Parameters that accept comma separated lists (I(privs), I(objs), I(roles))
- Parameters that accept comma separated lists (I(privs), I(objs), I(roles)) have singular alias names (I(priv), I(obj), I(role)).
have singular alias names (I(priv), I(obj), I(role)). - To revoke only C(GRANT OPTION) for a specific object, set I(state) to
- To revoke only C(GRANT OPTION) for a specific object, set I(state) to C(present) and I(grant_option) to C(no) (see examples).
C(present) and I(grant_option) to C(no) (see examples). - Note that when revoking privileges from a role R, this role may still have
- Note that when revoking privileges from a role R, this role may still have access via privileges granted to any role R is a member of including C(PUBLIC).
access via privileges granted to any role R is a member of including - Note that when revoking privileges from a role R, you do so as the user
C(PUBLIC). specified via I(login). If R has been granted the same privileges by
- Note that when revoking privileges from a role R, you do so as the user another user also, R can still access database objects via these privileges.
specified via I(login). If R has been granted the same privileges by - When revoking privileges, C(RESTRICT) is assumed (see PostgreSQL docs).
another user also, R can still access database objects via these privileges. - The ca_cert parameter requires at least Postgres version 8.4 and I(psycopg2) version 2.4.3.
- When revoking privileges, C(RESTRICT) is assumed (see PostgreSQL docs).
- The ca_cert parameter requires at least Postgres version 8.4 and I(psycopg2) version 2.4.3. requirements:
requirements: [psycopg2] - psycopg2
extends_documentation_fragment: extends_documentation_fragment:
- postgres - postgres
author: "Bernhard Weitzhofer (@b6d)"
"""
EXAMPLES = """ author:
- Bernhard Weitzhofer (@b6d)
'''
EXAMPLES = r'''
# On database "library": # On database "library":
# GRANT SELECT, INSERT, UPDATE ON TABLE public.books, public.authors # GRANT SELECT, INSERT, UPDATE ON TABLE public.books, public.authors
# TO librarian, reader WITH GRANT OPTION # TO librarian, reader WITH GRANT OPTION
- postgresql_privs: - name: Grant privs to librarian and reader on database library
postgresql_privs:
database: library database: library
state: present state: present
privs: SELECT,INSERT,UPDATE privs: SELECT,INSERT,UPDATE
@ -174,8 +204,8 @@ EXAMPLES = """
roles: librarian,reader roles: librarian,reader
grant_option: yes grant_option: yes
# Same as above leveraging default values: - name: Same as above leveraging default values
- postgresql_privs: postgresql_privs:
db: library db: library
privs: SELECT,INSERT,UPDATE privs: SELECT,INSERT,UPDATE
objs: books,authors objs: books,authors
@ -185,7 +215,8 @@ EXAMPLES = """
# REVOKE GRANT OPTION FOR INSERT ON TABLE books FROM reader # REVOKE GRANT OPTION FOR INSERT ON TABLE books FROM reader
# Note that role "reader" will be *granted* INSERT privilege itself if this # Note that role "reader" will be *granted* INSERT privilege itself if this
# isn't already the case (since state: present). # isn't already the case (since state: present).
- postgresql_privs: - name: Revoke privs from reader
postgresql_privs:
db: library db: library
state: present state: present
priv: INSERT priv: INSERT
@ -193,26 +224,26 @@ EXAMPLES = """
role: reader role: reader
grant_option: no grant_option: no
# REVOKE INSERT, UPDATE ON ALL TABLES IN SCHEMA public FROM reader
# "public" is the default schema. This also works for PostgreSQL 8.x. # "public" is the default schema. This also works for PostgreSQL 8.x.
- postgresql_privs: - name: REVOKE INSERT, UPDATE ON ALL TABLES IN SCHEMA public FROM reader
postgresql_privs:
db: library db: library
state: absent state: absent
privs: INSERT,UPDATE privs: INSERT,UPDATE
objs: ALL_IN_SCHEMA objs: ALL_IN_SCHEMA
role: reader role: reader
# GRANT ALL PRIVILEGES ON SCHEMA public, math TO librarian - name: GRANT ALL PRIVILEGES ON SCHEMA public, math TO librarian
- postgresql_privs: postgresql_privs:
db: library db: library
privs: ALL privs: ALL
type: schema type: schema
objs: public,math objs: public,math
role: librarian role: librarian
# GRANT ALL PRIVILEGES ON FUNCTION math.add(int, int) TO librarian, reader
# Note the separation of arguments with colons. # Note the separation of arguments with colons.
- postgresql_privs: - name: GRANT ALL PRIVILEGES ON FUNCTION math.add(int, int) TO librarian, reader
postgresql_privs:
db: library db: library
privs: ALL privs: ALL
type: function type: function
@ -220,41 +251,41 @@ EXAMPLES = """
schema: math schema: math
roles: librarian,reader roles: librarian,reader
# GRANT librarian, reader TO alice, bob WITH ADMIN OPTION
# Note that group role memberships apply cluster-wide and therefore are not # Note that group role memberships apply cluster-wide and therefore are not
# restricted to database "library" here. # restricted to database "library" here.
- postgresql_privs: - name: GRANT librarian, reader TO alice, bob WITH ADMIN OPTION
postgresql_privs:
db: library db: library
type: group type: group
objs: librarian,reader objs: librarian,reader
roles: alice,bob roles: alice,bob
admin_option: yes admin_option: yes
# GRANT ALL PRIVILEGES ON DATABASE library TO librarian
# Note that here "db: postgres" specifies the database to connect to, not the # Note that here "db: postgres" specifies the database to connect to, not the
# database to grant privileges on (which is specified via the "objs" param) # database to grant privileges on (which is specified via the "objs" param)
- postgresql_privs: - name: GRANT ALL PRIVILEGES ON DATABASE library TO librarian
postgresql_privs:
db: postgres db: postgres
privs: ALL privs: ALL
type: database type: database
obj: library obj: library
role: librarian role: librarian
# GRANT ALL PRIVILEGES ON DATABASE library TO librarian
# If objs is omitted for type "database", it defaults to the database # If objs is omitted for type "database", it defaults to the database
# to which the connection is established # to which the connection is established
- postgresql_privs: - name: GRANT ALL PRIVILEGES ON DATABASE library TO librarian
postgresql_privs:
db: library db: library
privs: ALL privs: ALL
type: database type: database
role: librarian role: librarian
# Available since version 2.7 # Available since version 2.7
# ALTER DEFAULT PRIVILEGES ON DATABASE library TO librarian
# Objs must be set, ALL_DEFAULT to TABLES/SEQUENCES/TYPES/FUNCTIONS # Objs must be set, ALL_DEFAULT to TABLES/SEQUENCES/TYPES/FUNCTIONS
# ALL_DEFAULT works only with privs=ALL # ALL_DEFAULT works only with privs=ALL
# For specific # For specific
- postgresql_privs: - name: ALTER DEFAULT PRIVILEGES ON DATABASE library TO librarian
postgresql_privs:
db: library db: library
objs: ALL_DEFAULT objs: ALL_DEFAULT
privs: ALL privs: ALL
@ -263,18 +294,19 @@ EXAMPLES = """
grant_option: yes grant_option: yes
# Available since version 2.7 # Available since version 2.7
# ALTER DEFAULT PRIVILEGES ON DATABASE library TO reader
# Objs must be set, ALL_DEFAULT to TABLES/SEQUENCES/TYPES/FUNCTIONS # Objs must be set, ALL_DEFAULT to TABLES/SEQUENCES/TYPES/FUNCTIONS
# ALL_DEFAULT works only with privs=ALL # ALL_DEFAULT works only with privs=ALL
# For specific # For specific
- postgresql_privs: - name: ALTER DEFAULT PRIVILEGES ON DATABASE library TO reader, step 1
postgresql_privs:
db: library db: library
objs: TABLES,SEQUENCES objs: TABLES,SEQUENCES
privs: SELECT privs: SELECT
type: default_privs type: default_privs
role: reader role: reader
- postgresql_privs: - name: ALTER DEFAULT PRIVILEGES ON DATABASE library TO reader, step 2
postgresql_privs:
db: library db: library
objs: TYPES objs: TYPES
privs: USAGE privs: USAGE
@ -282,8 +314,8 @@ EXAMPLES = """
role: reader role: reader
# Available since version 2.8 # Available since version 2.8
# GRANT ALL PRIVILEGES ON FOREIGN DATA WRAPPER fdw TO reader - name: GRANT ALL PRIVILEGES ON FOREIGN DATA WRAPPER fdw TO reader
- postgresql_privs: postgresql_privs:
db: test db: test
objs: fdw objs: fdw
privs: ALL privs: ALL
@ -291,8 +323,8 @@ EXAMPLES = """
role: reader role: reader
# Available since version 2.8 # Available since version 2.8
# GRANT ALL PRIVILEGES ON FOREIGN SERVER fdw_server TO reader - name: GRANT ALL PRIVILEGES ON FOREIGN SERVER fdw_server TO reader
- postgresql_privs: postgresql_privs:
db: test db: test
objs: fdw_server objs: fdw_server
privs: ALL privs: ALL
@ -300,9 +332,9 @@ EXAMPLES = """
role: reader role: reader
# Available since version 2.8 # Available since version 2.8
# GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA common TO caller
# Grant 'execute' permissions on all functions in schema 'common' to role 'caller' # Grant 'execute' permissions on all functions in schema 'common' to role 'caller'
- postgresql_privs: - name: GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA common TO caller
postgresql_privs:
type: function type: function
state: present state: present
privs: EXECUTE privs: EXECUTE
@ -315,7 +347,8 @@ EXAMPLES = """
# GRANT SELECT privileges for new TABLES objects created by librarian as # GRANT SELECT privileges for new TABLES objects created by librarian as
# default to the role reader. # default to the role reader.
# For specific # For specific
- postgresql_privs: - name: ALTER privs
postgresql_privs:
db: library db: library
schema: library schema: library
objs: TABLES objs: TABLES
@ -329,7 +362,8 @@ EXAMPLES = """
# REVOKE SELECT privileges for new TABLES objects created by librarian as # REVOKE SELECT privileges for new TABLES objects created by librarian as
# default from the role reader. # default from the role reader.
# For specific # For specific
- postgresql_privs: - name: ALTER privs
postgresql_privs:
db: library db: library
state: absent state: absent
schema: library schema: library
@ -338,8 +372,16 @@ EXAMPLES = """
type: default_privs type: default_privs
role: reader role: reader
target_roles: librarian target_roles: librarian
'''
""" RETURN = r'''
queries:
description: List of executed queries.
returned: always
type: list
sample: ['REVOKE GRANT OPTION FOR INSERT ON TABLE "books" FROM "reader";']
version_added: '2.8'
'''
import traceback import traceback
@ -354,6 +396,7 @@ except ImportError:
# import module snippets # import module snippets
from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.database import pg_quote_identifier from ansible.module_utils.database import pg_quote_identifier
from ansible.module_utils.postgres import postgres_common_argument_spec
from ansible.module_utils._text import to_native from ansible.module_utils._text import to_native
VALID_PRIVS = frozenset(('SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', VALID_PRIVS = frozenset(('SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE',
@ -364,6 +407,8 @@ VALID_DEFAULT_OBJS = {'TABLES': ('ALL', 'SELECT', 'INSERT', 'UPDATE', 'DELETE',
'FUNCTIONS': ('ALL', 'EXECUTE'), 'FUNCTIONS': ('ALL', 'EXECUTE'),
'TYPES': ('ALL', 'USAGE')} 'TYPES': ('ALL', 'USAGE')}
executed_queries = []
class Error(Exception): class Error(Exception):
pass pass
@ -695,6 +740,7 @@ class Connection(object):
.for_objs(objs) \ .for_objs(objs) \
.build() .build()
executed_queries.append(query)
self.cursor.execute(query) self.cursor.execute(query)
status_after = get_status(objs) status_after = get_status(objs)
return status_before != status_after return status_before != status_after
@ -826,41 +872,40 @@ class QueryBuilder(object):
def main(): def main():
argument_spec = postgres_common_argument_spec()
argument_spec.update(
database=dict(required=True, aliases=['db', 'login_db']),
state=dict(default='present', choices=['present', 'absent']),
privs=dict(required=False, aliases=['priv']),
type=dict(default='table',
choices=['table',
'sequence',
'function',
'database',
'schema',
'language',
'tablespace',
'group',
'default_privs',
'foreign_data_wrapper',
'foreign_server']),
objs=dict(required=False, aliases=['obj']),
schema=dict(required=False),
roles=dict(required=True, aliases=['role']),
session_role=dict(required=False),
target_roles=dict(required=False),
grant_option=dict(required=False, type='bool',
aliases=['admin_option']),
host=dict(default='', aliases=['login_host']),
unix_socket=dict(default='', aliases=['login_unix_socket']),
login=dict(default='postgres', aliases=['login_user']),
password=dict(default='', aliases=['login_password'], no_log=True),
fail_on_role=dict(type='bool', default=True),
)
module = AnsibleModule( module = AnsibleModule(
argument_spec=dict( argument_spec=argument_spec,
database=dict(required=True, aliases=['db']), supports_check_mode=True,
state=dict(default='present', choices=['present', 'absent']),
privs=dict(required=False, aliases=['priv']),
type=dict(default='table',
choices=['table',
'sequence',
'function',
'database',
'schema',
'language',
'tablespace',
'group',
'default_privs',
'foreign_data_wrapper',
'foreign_server']),
objs=dict(required=False, aliases=['obj']),
schema=dict(required=False),
roles=dict(required=True, aliases=['role']),
session_role=dict(required=False),
target_roles=dict(required=False),
grant_option=dict(required=False, type='bool',
aliases=['admin_option']),
host=dict(default='', aliases=['login_host']),
port=dict(type='int', default=5432),
unix_socket=dict(default='', aliases=['login_unix_socket']),
login=dict(default='postgres', aliases=['login_user']),
password=dict(default='', aliases=['login_password'], no_log=True),
ssl_mode=dict(default="prefer",
choices=['disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full']),
ca_cert=dict(default=None, aliases=['ssl_rootcert']),
fail_on_role=dict(type='bool', default=True),
),
supports_check_mode=True
) )
fail_on_role = module.params['fail_on_role'] fail_on_role = module.params['fail_on_role']
@ -997,7 +1042,7 @@ def main():
conn.rollback() conn.rollback()
else: else:
conn.commit() conn.commit()
module.exit_json(changed=changed) module.exit_json(changed=changed, queries=executed_queries)
if __name__ == '__main__': if __name__ == '__main__':

@ -54,11 +54,15 @@ options:
description: description:
- Name of database to connect to and run queries against. - Name of database to connect to and run queries against.
type: str type: str
aliases:
- login_db
port: port:
description: description:
- Database port to connect. - Database port to connect.
type: int type: int
default: 5432 default: 5432
aliases:
- login_port
login_user: login_user:
description: description:
- User (role) used to authenticate with PostgreSQL. - User (role) used to authenticate with PostgreSQL.
@ -219,9 +223,7 @@ def main():
argument_spec = postgres_common_argument_spec() argument_spec = postgres_common_argument_spec()
argument_spec.update( argument_spec.update(
query=dict(type='str'), query=dict(type='str'),
db=dict(type='str'), db=dict(type='str', aliases=['login_db']),
ssl_mode=dict(type='str', default='prefer', choices=['allow', 'disable', 'prefer', 'require', 'verify-ca', 'verify-full']),
ca_cert=dict(type='str', aliases=['ssl_rootcert']),
positional_args=dict(type='list'), positional_args=dict(type='list'),
named_args=dict(type='dict'), named_args=dict(type='dict'),
session_role=dict(type='str'), session_role=dict(type='str'),

@ -23,13 +23,23 @@
# Prepare SQL script: # Prepare SQL script:
- name: postgresql_query - remove SQL script if exists - name: postgresql_query - remove SQL script if exists
become_user: "{{ pg_user }}"
become: yes become: yes
file: file:
path: '~{{ pg_user}}/test.sql' path: '~{{ pg_user}}/test.sql'
state: absent state: absent
ignore_errors: yes ignore_errors: yes
- name: postgresql_query - create an empty file to check permission
become: yes
file:
path: '~{{ pg_user}}/test.sql'
state: touch
owner: '{{ pg_user }}'
group: '{{ pg_user }}'
mode: 0644
register: sql_file_created
ignore_errors: yes
- name: postgresql_query - prepare SQL script - name: postgresql_query - prepare SQL script
become_user: "{{ pg_user }}" become_user: "{{ pg_user }}"
become: yes become: yes
@ -39,6 +49,7 @@
- SELECT version(); - SELECT version();
- SELECT story FROM test_table - SELECT story FROM test_table
- WHERE id = %s; - WHERE id = %s;
when: sql_file_created
############## ##############
# Start tests: # Start tests:
@ -75,6 +86,7 @@
- 1 - 1
register: result register: result
ignore_errors: yes ignore_errors: yes
when: sql_file_created
- assert: - assert:
that: that:
@ -83,6 +95,7 @@
- result.rowcount == 1 - result.rowcount == 1
- result.statusmessage == 'SELECT 1' or result.statusmessage == 'SELECT' - result.statusmessage == 'SELECT 1' or result.statusmessage == 'SELECT'
- result.query_result[0].story == 'first' - result.query_result[0].story == 'first'
when: sql_file_created
# Simple select query: # Simple select query:
- name: postgresql_query - simple select query to test_table - name: postgresql_query - simple select query to test_table

@ -337,7 +337,6 @@ lib/ansible/modules/database/postgresql/postgresql_db.py E210
lib/ansible/modules/database/postgresql/postgresql_ext.py E322 lib/ansible/modules/database/postgresql/postgresql_ext.py E322
lib/ansible/modules/database/postgresql/postgresql_ext.py E324 lib/ansible/modules/database/postgresql/postgresql_ext.py E324
lib/ansible/modules/database/postgresql/postgresql_lang.py E324 lib/ansible/modules/database/postgresql/postgresql_lang.py E324
lib/ansible/modules/database/postgresql/postgresql_privs.py E322
lib/ansible/modules/database/postgresql/postgresql_schema.py E322 lib/ansible/modules/database/postgresql/postgresql_schema.py E322
lib/ansible/modules/database/postgresql/postgresql_schema.py E324 lib/ansible/modules/database/postgresql/postgresql_schema.py E324
lib/ansible/modules/database/postgresql/postgresql_user.py E322 lib/ansible/modules/database/postgresql/postgresql_user.py E322

Loading…
Cancel
Save