| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright Ansible Project |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: vertica_schema |
| 11 |
short_description: Adds or removes Vertica database schema and roles |
| 12 |
description: |
| 13 |
- Adds or removes Vertica database schema and, optionally, roles with schema access privileges. |
| 14 |
- A schema is not removed until all the objects have been dropped. |
| 15 |
- In such a situation, if the module tries to remove the schema it fails and only remove roles created for the schema if |
| 16 |
they have no dependencies. |
| 17 |
extends_documentation_fragment: |
| 18 |
- community.general._attributes |
| 19 |
attributes: |
| 20 |
check_mode: |
| 21 |
support: full |
| 22 |
diff_mode: |
| 23 |
support: none |
| 24 |
options: |
| 25 |
schema: |
| 26 |
description: |
| 27 |
- Name of the schema to add or remove. |
| 28 |
required: true |
| 29 |
aliases: ['name'] |
| 30 |
type: str |
| 31 |
usage_roles: |
| 32 |
description: |
| 33 |
- Comma separated list of roles to create and grant usage access to the schema. |
| 34 |
aliases: ['usage_role'] |
| 35 |
type: str |
| 36 |
create_roles: |
| 37 |
description: |
| 38 |
- Comma separated list of roles to create and grant usage and create access to the schema. |
| 39 |
aliases: ['create_role'] |
| 40 |
type: str |
| 41 |
owner: |
| 42 |
description: |
| 43 |
- Name of the user to set as owner of the schema. |
| 44 |
type: str |
| 45 |
state: |
| 46 |
description: |
| 47 |
- Whether to create V(present), or drop V(absent) a schema. |
| 48 |
default: present |
| 49 |
choices: ['present', 'absent'] |
| 50 |
type: str |
| 51 |
db: |
| 52 |
description: |
| 53 |
- Name of the Vertica database. |
| 54 |
type: str |
| 55 |
cluster: |
| 56 |
description: |
| 57 |
- Name of the Vertica cluster. |
| 58 |
default: localhost |
| 59 |
type: str |
| 60 |
port: |
| 61 |
description: |
| 62 |
- Vertica cluster port to connect to. |
| 63 |
default: '5433' |
| 64 |
type: str |
| 65 |
login_user: |
| 66 |
description: |
| 67 |
- The username used to authenticate with. |
| 68 |
default: dbadmin |
| 69 |
type: str |
| 70 |
login_password: |
| 71 |
description: |
| 72 |
- The password used to authenticate with. |
| 73 |
type: str |
| 74 |
notes: |
| 75 |
- The default authentication assumes that you are either logging in as or sudo'ing to the C(dbadmin) account on the host. |
| 76 |
- This module uses C(pyodbc), a Python ODBC database adapter. You must ensure that C(unixODBC) and C(pyodbc) is installed |
| 77 |
on the host and properly configured. |
| 78 |
- Configuring C(unixODBC) for Vertica requires C(Driver = /opt/vertica/lib64/libverticaodbc.so) to be added to the C(Vertica) |
| 79 |
section of either C(/etc/odbcinst.ini) or C($HOME/.odbcinst.ini) and both C(ErrorMessagesPath = /opt/vertica/lib64) and |
| 80 |
C(DriverManagerEncoding = UTF-16) to be added to the C(Driver) section of either C(/etc/vertica.ini) or C($HOME/.vertica.ini). |
| 81 |
requirements: ['unixODBC', 'pyodbc'] |
| 82 |
author: "Dariusz Owczarek (@dareko)" |
| 83 |
""" |
| 84 |
|
| 85 |
EXAMPLES = r""" |
| 86 |
- name: Creating a new vertica schema |
| 87 |
community.general.vertica_schema: name=schema_name db=db_name state=present |
| 88 |
|
| 89 |
- name: Creating a new schema with specific schema owner |
| 90 |
community.general.vertica_schema: name=schema_name owner=dbowner db=db_name state=present |
| 91 |
|
| 92 |
- name: Creating a new schema with roles |
| 93 |
community.general.vertica_schema: name=schema_name create_roles=schema_name_all usage_roles=schema_name_ro,schema_name_rw |
| 94 |
db=db_name state=present |
| 95 |
""" |
| 96 |
import traceback |
| 97 |
|
| 98 |
PYODBC_IMP_ERR = None |
| 99 |
try: |
| 100 |
import pyodbc |
| 101 |
except ImportError: |
| 102 |
PYODBC_IMP_ERR = traceback.format_exc() |
| 103 |
pyodbc_found = False |
| 104 |
else: |
| 105 |
pyodbc_found = True |
| 106 |
|
| 107 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 108 |
|
| 109 |
|
| 110 |
class NotSupportedError(Exception): |
| 111 |
pass |
| 112 |
|
| 113 |
|
| 114 |
class CannotDropError(Exception): |
| 115 |
pass |
| 116 |
|
| 117 |
|
| 118 |
# module specific functions |
| 119 |
|
| 120 |
|
| 121 |
def get_schema_facts(cursor, schema=""): |
| 122 |
facts = {} |
| 123 |
cursor.execute( |
| 124 |
""" |
| 125 |
select schema_name, schema_owner, create_time |
| 126 |
from schemata |
| 127 |
where not is_system_schema and schema_name not in ('public', 'TxtIndex') |
| 128 |
and (? = '' or schema_name ilike ?) |
| 129 |
""", |
| 130 |
schema, |
| 131 |
schema, |
| 132 |
) |
| 133 |
while True: |
| 134 |
rows = cursor.fetchmany(100) |
| 135 |
if not rows: |
| 136 |
break |
| 137 |
for row in rows: |
| 138 |
facts[row.schema_name.lower()] = { |
| 139 |
"name": row.schema_name, |
| 140 |
"owner": row.schema_owner, |
| 141 |
"create_time": str(row.create_time), |
| 142 |
"usage_roles": [], |
| 143 |
"create_roles": [], |
| 144 |
} |
| 145 |
cursor.execute( |
| 146 |
""" |
| 147 |
select g.object_name as schema_name, r.name as role_name, |
| 148 |
lower(g.privileges_description) privileges_description |
| 149 |
from roles r join grants g |
| 150 |
on g.grantee_id = r.role_id and g.object_type='SCHEMA' |
| 151 |
and g.privileges_description like '%USAGE%' |
| 152 |
and g.grantee not in ('public', 'dbadmin') |
| 153 |
and (? = '' or g.object_name ilike ?) |
| 154 |
""", |
| 155 |
schema, |
| 156 |
schema, |
| 157 |
) |
| 158 |
while True: |
| 159 |
rows = cursor.fetchmany(100) |
| 160 |
if not rows: |
| 161 |
break |
| 162 |
for row in rows: |
| 163 |
schema_key = row.schema_name.lower() |
| 164 |
if "create" in row.privileges_description: |
| 165 |
facts[schema_key]["create_roles"].append(row.role_name) |
| 166 |
else: |
| 167 |
facts[schema_key]["usage_roles"].append(row.role_name) |
| 168 |
return facts |
| 169 |
|
| 170 |
|
| 171 |
def update_roles(schema_facts, cursor, schema, existing, required, create_existing, create_required): |
| 172 |
for role in set(existing + create_existing) - set(required + create_required): |
| 173 |
cursor.execute(f"drop role {role} cascade") |
| 174 |
for role in set(create_existing) - set(create_required): |
| 175 |
cursor.execute(f"revoke create on schema {schema} from {role}") |
| 176 |
for role in set(required + create_required) - set(existing + create_existing): |
| 177 |
cursor.execute(f"create role {role}") |
| 178 |
cursor.execute(f"grant usage on schema {schema} to {role}") |
| 179 |
for role in set(create_required) - set(create_existing): |
| 180 |
cursor.execute(f"grant create on schema {schema} to {role}") |
| 181 |
|
| 182 |
|
| 183 |
def check(schema_facts, schema, usage_roles, create_roles, owner): |
| 184 |
schema_key = schema.lower() |
| 185 |
if schema_key not in schema_facts: |
| 186 |
return False |
| 187 |
if owner and owner.lower() == schema_facts[schema_key]["owner"].lower(): |
| 188 |
return False |
| 189 |
if sorted(usage_roles) != sorted(schema_facts[schema_key]["usage_roles"]): |
| 190 |
return False |
| 191 |
return sorted(create_roles) == sorted(schema_facts[schema_key]["create_roles"]) |
| 192 |
|
| 193 |
|
| 194 |
def present(schema_facts, cursor, schema, usage_roles, create_roles, owner): |
| 195 |
schema_key = schema.lower() |
| 196 |
if schema_key not in schema_facts: |
| 197 |
query_fragments = [f"create schema {schema}"] |
| 198 |
if owner: |
| 199 |
query_fragments.append(f"authorization {owner}") |
| 200 |
cursor.execute(" ".join(query_fragments)) |
| 201 |
update_roles(schema_facts, cursor, schema, [], usage_roles, [], create_roles) |
| 202 |
schema_facts.update(get_schema_facts(cursor, schema)) |
| 203 |
return True |
| 204 |
else: |
| 205 |
changed = False |
| 206 |
if owner and owner.lower() != schema_facts[schema_key]["owner"].lower(): |
| 207 |
raise NotSupportedError( |
| 208 |
f"Changing schema owner is not supported. Current owner: {schema_facts[schema_key]['owner']}." |
| 209 |
) |
| 210 |
if sorted(usage_roles) != sorted(schema_facts[schema_key]["usage_roles"]) or sorted(create_roles) != sorted( |
| 211 |
schema_facts[schema_key]["create_roles"] |
| 212 |
): |
| 213 |
update_roles( |
| 214 |
schema_facts, |
| 215 |
cursor, |
| 216 |
schema, |
| 217 |
schema_facts[schema_key]["usage_roles"], |
| 218 |
usage_roles, |
| 219 |
schema_facts[schema_key]["create_roles"], |
| 220 |
create_roles, |
| 221 |
) |
| 222 |
changed = True |
| 223 |
if changed: |
| 224 |
schema_facts.update(get_schema_facts(cursor, schema)) |
| 225 |
return changed |
| 226 |
|
| 227 |
|
| 228 |
def absent(schema_facts, cursor, schema, usage_roles, create_roles): |
| 229 |
schema_key = schema.lower() |
| 230 |
if schema_key in schema_facts: |
| 231 |
update_roles( |
| 232 |
schema_facts, |
| 233 |
cursor, |
| 234 |
schema, |
| 235 |
schema_facts[schema_key]["usage_roles"], |
| 236 |
[], |
| 237 |
schema_facts[schema_key]["create_roles"], |
| 238 |
[], |
| 239 |
) |
| 240 |
try: |
| 241 |
cursor.execute(f"drop schema {schema_facts[schema_key]['name']} restrict") |
| 242 |
except pyodbc.Error as e: |
| 243 |
raise CannotDropError("Dropping schema failed due to dependencies.") from e |
| 244 |
del schema_facts[schema_key] |
| 245 |
return True |
| 246 |
else: |
| 247 |
return False |
| 248 |
|
| 249 |
|
| 250 |
# module logic |
| 251 |
|
| 252 |
|
| 253 |
def main(): |
| 254 |
module = AnsibleModule( |
| 255 |
argument_spec=dict( |
| 256 |
schema=dict(required=True, aliases=["name"]), |
| 257 |
usage_roles=dict(aliases=["usage_role"]), |
| 258 |
create_roles=dict(aliases=["create_role"]), |
| 259 |
owner=dict(), |
| 260 |
state=dict(default="present", choices=["absent", "present"]), |
| 261 |
db=dict(), |
| 262 |
cluster=dict(default="localhost"), |
| 263 |
port=dict(default="5433"), |
| 264 |
login_user=dict(default="dbadmin"), |
| 265 |
login_password=dict(no_log=True), |
| 266 |
), |
| 267 |
supports_check_mode=True, |
| 268 |
) |
| 269 |
|
| 270 |
if not pyodbc_found: |
| 271 |
module.fail_json(msg=missing_required_lib("pyodbc"), exception=PYODBC_IMP_ERR) |
| 272 |
|
| 273 |
schema = module.params["schema"] |
| 274 |
usage_roles = [] |
| 275 |
if module.params["usage_roles"]: |
| 276 |
usage_roles = module.params["usage_roles"].split(",") |
| 277 |
usage_roles = [_f for _f in usage_roles if _f] |
| 278 |
create_roles = [] |
| 279 |
if module.params["create_roles"]: |
| 280 |
create_roles = module.params["create_roles"].split(",") |
| 281 |
create_roles = [_f for _f in create_roles if _f] |
| 282 |
owner = module.params["owner"] |
| 283 |
state = module.params["state"] |
| 284 |
db = "" |
| 285 |
if module.params["db"]: |
| 286 |
db = module.params["db"] |
| 287 |
|
| 288 |
changed = False |
| 289 |
|
| 290 |
try: |
| 291 |
dsn = ( |
| 292 |
"Driver=Vertica;" |
| 293 |
f"Server={module.params['cluster']};" |
| 294 |
f"Port={module.params['port']};" |
| 295 |
f"Database={db};" |
| 296 |
f"User={module.params['login_user']};" |
| 297 |
f"Password={module.params['login_password']};" |
| 298 |
f"ConnectionLoadBalance=true" |
| 299 |
) |
| 300 |
db_conn = pyodbc.connect(dsn, autocommit=True) |
| 301 |
cursor = db_conn.cursor() |
| 302 |
except Exception as e: |
| 303 |
module.fail_json(msg=f"Unable to connect to database: {e}.") |
| 304 |
|
| 305 |
try: |
| 306 |
schema_facts = get_schema_facts(cursor) |
| 307 |
if module.check_mode: |
| 308 |
changed = not check(schema_facts, schema, usage_roles, create_roles, owner) |
| 309 |
elif state == "absent": |
| 310 |
try: |
| 311 |
changed = absent(schema_facts, cursor, schema, usage_roles, create_roles) |
| 312 |
except pyodbc.Error as e: |
| 313 |
module.fail_json(msg=f"{e}", exception=traceback.format_exc()) |
| 314 |
elif state == "present": |
| 315 |
try: |
| 316 |
changed = present(schema_facts, cursor, schema, usage_roles, create_roles, owner) |
| 317 |
except pyodbc.Error as e: |
| 318 |
module.fail_json(msg=f"{e}", exception=traceback.format_exc()) |
| 319 |
except NotSupportedError as e: |
| 320 |
module.fail_json(msg=f"{e}", ansible_facts={"vertica_schemas": schema_facts}) |
| 321 |
except CannotDropError as e: |
| 322 |
module.fail_json(msg=f"{e}", ansible_facts={"vertica_schemas": schema_facts}) |
| 323 |
except SystemExit: |
| 324 |
# avoid catching this on python 2.4 |
| 325 |
raise |
| 326 |
except Exception as e: |
| 327 |
module.fail_json(msg=f"{e}", exception=traceback.format_exc()) |
| 328 |
|
| 329 |
module.exit_json(changed=changed, schema=schema, ansible_facts={"vertica_schemas": schema_facts}) |
| 330 |
|
| 331 |
|
| 332 |
if __name__ == "__main__": |
| 333 |
main() |