Add session_role to postgresql modules (#43650)

* Allow session_role to be set for PostgreSQL

By implementing session_role it becomes possible to run the specific
PostgreSQL commands as a different role.
The usecase that is immediately served by this, is the one that one
ansible playbook can be shared by multiple users, which all have
their
own PostgreSQL login_user. They do not need to share login
credentials,
as they can share the role within the PostgreSQL database.

The following example may give some insight:

$ psql -U jdoe -X -d postgres

postgres=> CREATE DATABASE abc;
ERROR:  permission denied to create database
postgres=> set role postgres;
SET
postgres=# CREATE DATABASE abc;
CREATE DATABASE

fixes #43592

* Tests for session_role in PostgreSQL

* Bump version_added for session_role feature

* Remove explicit encrypted parameter from tests
This commit is contained in:
Feike Steenbergen 2019-02-02 19:12:14 +00:00 committed by Dag Wieers
parent e633b93f85
commit 38e70ea317
9 changed files with 339 additions and 1 deletions

View file

@ -70,6 +70,11 @@ options:
for the implicitly defined PUBLIC group.
- 'Alias: I(role)'
required: yes
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.
grant_option:
description:
- Whether C(role) may grant/revoke the specified privileges/group
@ -668,6 +673,7 @@ def main():
objs=dict(required=False, aliases=['obj']),
schema=dict(required=False),
roles=dict(required=True, aliases=['role']),
session_role=dict(required=False),
grant_option=dict(required=False, type='bool',
aliases=['admin_option']),
host=dict(default='', aliases=['login_host']),
@ -722,6 +728,12 @@ def main():
# We raise this when the psycopg library is too old
module.fail_json(msg=to_native(e))
if p.session_role:
try:
conn.cursor.execute('SET ROLE %s' % pg_quote_identifier(p.session_role, 'role'))
except Exception as e:
module.fail_json(msg="Could not switch to role %s: %s" % (p.session_role, to_native(e)), exception=traceback.format_exc())
try:
# privs
if p.privs: