| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: Ansible Project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
|
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
DOCUMENTATION = r''' |
| 12 |
--- |
| 13 |
module: postgresql_ext |
| 14 |
short_description: Add or remove PostgreSQL extensions from a database |
| 15 |
description: |
| 16 |
- Add or remove PostgreSQL extensions from a database. |
| 17 |
options: |
| 18 |
name: |
| 19 |
description: |
| 20 |
- Name of the extension to add or remove. |
| 21 |
required: true |
| 22 |
type: str |
| 23 |
aliases: |
| 24 |
- ext |
| 25 |
login_db: |
| 26 |
description: |
| 27 |
- Name of the database to add or remove the extension to/from. |
| 28 |
- The V(db) alias is deprecated and will be removed in version 5.0.0. |
| 29 |
required: true |
| 30 |
type: str |
| 31 |
aliases: |
| 32 |
- db |
| 33 |
schema: |
| 34 |
description: |
| 35 |
- Name of the schema to add the extension to. |
| 36 |
type: str |
| 37 |
session_role: |
| 38 |
description: |
| 39 |
- Switch to session_role after connecting. |
| 40 |
- The specified session_role must be a role that the current login_user is a member of. |
| 41 |
- Permissions checking for SQL commands is carried out as though the session_role were the one that had logged in originally. |
| 42 |
type: str |
| 43 |
state: |
| 44 |
description: |
| 45 |
- The database extension state. |
| 46 |
default: present |
| 47 |
choices: [ absent, present ] |
| 48 |
type: str |
| 49 |
cascade: |
| 50 |
description: |
| 51 |
- Automatically install/remove any extensions that this extension depends on |
| 52 |
that are not already installed/removed (supported since PostgreSQL 9.6). |
| 53 |
type: bool |
| 54 |
default: false |
| 55 |
login_unix_socket: |
| 56 |
description: |
| 57 |
- Path to a Unix domain socket for local connections. |
| 58 |
type: str |
| 59 |
ssl_mode: |
| 60 |
description: |
| 61 |
- Determines whether or with what priority a secure SSL TCP/IP connection will be negotiated with the server. |
| 62 |
- See U(https://www.postgresql.org/docs/current/static/libpq-ssl.html) for more information on the modes. |
| 63 |
- Default of C(prefer) matches libpq default. |
| 64 |
type: str |
| 65 |
default: prefer |
| 66 |
choices: [ allow, disable, prefer, require, verify-ca, verify-full ] |
| 67 |
ca_cert: |
| 68 |
description: |
| 69 |
- Specifies the name of a file containing SSL certificate authority (CA) certificate(s). |
| 70 |
- If the file exists, the server's certificate will be verified to be signed by one of these authorities. |
| 71 |
type: str |
| 72 |
aliases: [ ssl_rootcert ] |
| 73 |
version: |
| 74 |
description: |
| 75 |
- Extension version to add or update to. Has effect with I(state=present) only. |
| 76 |
- If not specified and extension is not installed in the database, |
| 77 |
the latest version available will be created. |
| 78 |
- If extension is already installed, will update to the given version if a valid update |
| 79 |
path exists. |
| 80 |
- Downgrading is only supported if the extension provides a downgrade path otherwise |
| 81 |
the extension must be removed and a lower version of the extension must be made available. |
| 82 |
- Set I(version=latest) to update the extension to the latest available version. |
| 83 |
type: str |
| 84 |
trust_input: |
| 85 |
description: |
| 86 |
- If C(false), check whether values of parameters I(ext), I(schema), |
| 87 |
I(version), I(session_role) are potentially dangerous. |
| 88 |
- It makes sense to use C(false) only when SQL injections via the parameters are possible. |
| 89 |
type: bool |
| 90 |
default: true |
| 91 |
version_added: '0.2.0' |
| 92 |
comment: |
| 93 |
description: |
| 94 |
- Sets a comment on the extension. |
| 95 |
- To reset the comment, pass an empty string. |
| 96 |
type: str |
| 97 |
version_added: '3.3.0' |
| 98 |
|
| 99 |
seealso: |
| 100 |
- name: PostgreSQL extensions |
| 101 |
description: General information about PostgreSQL extensions. |
| 102 |
link: https://www.postgresql.org/docs/current/external-extensions.html |
| 103 |
- name: CREATE EXTENSION reference |
| 104 |
description: Complete reference of the CREATE EXTENSION command documentation. |
| 105 |
link: https://www.postgresql.org/docs/current/sql-createextension.html |
| 106 |
- name: ALTER EXTENSION reference |
| 107 |
description: Complete reference of the ALTER EXTENSION command documentation. |
| 108 |
link: https://www.postgresql.org/docs/current/sql-alterextension.html |
| 109 |
- name: DROP EXTENSION reference |
| 110 |
description: Complete reference of the DROP EXTENSION command documentation. |
| 111 |
link: https://www.postgresql.org/docs/current/sql-droppublication.html |
| 112 |
|
| 113 |
notes: |
| 114 |
- Incomparable versions, for example PostGIS ``unpackaged``, cannot be installed. |
| 115 |
|
| 116 |
attributes: |
| 117 |
check_mode: |
| 118 |
support: full |
| 119 |
|
| 120 |
author: |
| 121 |
- Daniel Schep (@dschep) |
| 122 |
- Thomas O'Donnell (@andytom) |
| 123 |
- Sandro Santilli (@strk) |
| 124 |
- Andrew Klychkov (@Andersson007) |
| 125 |
- Keith Fiske (@keithf4) |
| 126 |
- Daniele Giudice (@RealGreenDragon) |
| 127 |
|
| 128 |
extends_documentation_fragment: |
| 129 |
- community.postgresql.postgres |
| 130 |
''' |
| 131 |
|
| 132 |
EXAMPLES = r''' |
| 133 |
- name: Adds postgis extension to the database acme in the schema foo |
| 134 |
community.postgresql.postgresql_ext: |
| 135 |
name: postgis |
| 136 |
login_db: acme |
| 137 |
schema: foo |
| 138 |
comment: Test extension |
| 139 |
|
| 140 |
- name: Removes postgis extension to the database acme |
| 141 |
community.postgresql.postgresql_ext: |
| 142 |
name: postgis |
| 143 |
login_db: acme |
| 144 |
state: absent |
| 145 |
|
| 146 |
- name: Adds earthdistance extension to the database template1 cascade |
| 147 |
community.postgresql.postgresql_ext: |
| 148 |
name: earthdistance |
| 149 |
login_db: template1 |
| 150 |
cascade: true |
| 151 |
|
| 152 |
# In the example below, if earthdistance extension is installed, |
| 153 |
# it will be removed too because it depends on cube: |
| 154 |
- name: Removes cube extension from the database acme cascade |
| 155 |
community.postgresql.postgresql_ext: |
| 156 |
name: cube |
| 157 |
login_db: acme |
| 158 |
cascade: true |
| 159 |
state: absent |
| 160 |
|
| 161 |
- name: Create extension foo of version 1.2 or update it to that version if it's already created and a valid update path exists |
| 162 |
community.postgresql.postgresql_ext: |
| 163 |
login_db: acme |
| 164 |
name: foo |
| 165 |
version: 1.2 |
| 166 |
|
| 167 |
- name: Create the latest available version of extension foo. If already installed, update it to the latest version |
| 168 |
community.postgresql.postgresql_ext: |
| 169 |
login_db: acme |
| 170 |
name: foo |
| 171 |
version: latest |
| 172 |
''' |
| 173 |
|
| 174 |
RETURN = r''' |
| 175 |
queries: |
| 176 |
description: List of executed queries. |
| 177 |
returned: success |
| 178 |
type: list |
| 179 |
sample: ["DROP EXTENSION \"acme\""] |
| 180 |
prev_version: |
| 181 |
description: Previous installed extension version or empty string if the extension was not installed. |
| 182 |
returned: success |
| 183 |
type: str |
| 184 |
sample: '1.0' |
| 185 |
version_added: '3.1.0' |
| 186 |
version: |
| 187 |
description: Current installed extension version or empty string if the extension is not installed. |
| 188 |
returned: success |
| 189 |
type: str |
| 190 |
sample: '2.0' |
| 191 |
version_added: '3.1.0' |
| 192 |
''' |
| 193 |
|
| 194 |
import traceback |
| 195 |
|
| 196 |
from ansible.module_utils.common.text.converters import to_native |
| 197 |
from ansible.module_utils.basic import AnsibleModule |
| 198 |
from ansible_collections.community.postgresql.plugins.module_utils.database import \ |
| 199 |
check_input |
| 200 |
from ansible_collections.community.postgresql.plugins.module_utils.postgres import ( |
| 201 |
connect_to_db, |
| 202 |
ensure_required_libs, |
| 203 |
get_comment, |
| 204 |
get_conn_params, |
| 205 |
pg_cursor_args, |
| 206 |
postgres_common_argument_spec, |
| 207 |
set_comment, |
| 208 |
) |
| 209 |
|
| 210 |
executed_queries = [] |
| 211 |
|
| 212 |
|
| 213 |
# =========================================== |
| 214 |
# PostgreSQL module specific support methods. |
| 215 |
# |
| 216 |
|
| 217 |
|
| 218 |
def ext_delete(check_mode, cursor, ext, cascade): |
| 219 |
"""Remove the extension from the database. |
| 220 |
|
| 221 |
Return True if success. |
| 222 |
|
| 223 |
Args: |
| 224 |
cursor (cursor) -- cursor object of psycopg library |
| 225 |
ext (str) -- extension name |
| 226 |
cascade (boolean) -- Pass the CASCADE flag to the DROP command |
| 227 |
""" |
| 228 |
query = "DROP EXTENSION \"%s\"" % ext |
| 229 |
|
| 230 |
if cascade: |
| 231 |
query += " CASCADE" |
| 232 |
|
| 233 |
if not check_mode: |
| 234 |
cursor.execute(query) |
| 235 |
executed_queries.append(cursor.mogrify(query)) |
| 236 |
|
| 237 |
return True |
| 238 |
|
| 239 |
|
| 240 |
def ext_update_version(check_mode, cursor, ext, version): |
| 241 |
"""Update extension version. |
| 242 |
|
| 243 |
Return True if success. |
| 244 |
|
| 245 |
Args: |
| 246 |
cursor (cursor) -- cursor object of psycopg library |
| 247 |
ext (str) -- extension name |
| 248 |
version (str) -- extension version |
| 249 |
""" |
| 250 |
query = "ALTER EXTENSION \"%s\" UPDATE" % ext |
| 251 |
params = {} |
| 252 |
|
| 253 |
if version != 'latest': |
| 254 |
query += " TO %(ver)s" |
| 255 |
params['ver'] = version |
| 256 |
|
| 257 |
if not check_mode: |
| 258 |
cursor.execute(query, params) |
| 259 |
executed_queries.append(cursor.mogrify(query, params)) |
| 260 |
|
| 261 |
return True |
| 262 |
|
| 263 |
|
| 264 |
def ext_create(check_mode, cursor, ext, schema, cascade, version): |
| 265 |
""" |
| 266 |
Create the extension objects inside the database. |
| 267 |
|
| 268 |
Return True if success. |
| 269 |
|
| 270 |
Args: |
| 271 |
cursor (cursor) -- cursor object of psycopg library |
| 272 |
ext (str) -- extension name |
| 273 |
schema (str) -- target schema for extension objects |
| 274 |
cascade (boolean) -- Pass the CASCADE flag to the CREATE command |
| 275 |
version (str) -- extension version |
| 276 |
""" |
| 277 |
query = "CREATE EXTENSION \"%s\"" % ext |
| 278 |
params = {} |
| 279 |
|
| 280 |
if schema: |
| 281 |
query += " WITH SCHEMA \"%s\"" % schema |
| 282 |
if version != 'latest': |
| 283 |
query += " VERSION %(ver)s" |
| 284 |
params['ver'] = version |
| 285 |
if cascade: |
| 286 |
query += " CASCADE" |
| 287 |
|
| 288 |
if not check_mode: |
| 289 |
cursor.execute(query, params) |
| 290 |
executed_queries.append(cursor.mogrify(query, params)) |
| 291 |
|
| 292 |
return True |
| 293 |
|
| 294 |
|
| 295 |
def ext_get_versions(cursor, ext): |
| 296 |
""" |
| 297 |
Get the currently created extension version if it is installed |
| 298 |
in the database, its default version (used to update to 'latest'), |
| 299 |
and versions that are available if it is installed on the system. |
| 300 |
|
| 301 |
Return tuple (current_version, default_version, [list of available versions]). |
| 302 |
|
| 303 |
Note: the list of available versions contains only versions |
| 304 |
that higher than the current created version. |
| 305 |
If the extension is not created, this list will contain all |
| 306 |
available versions. |
| 307 |
|
| 308 |
Args: |
| 309 |
cursor (cursor) -- cursor object of psycopg library |
| 310 |
ext (str) -- extension name |
| 311 |
""" |
| 312 |
|
| 313 |
current_version = None |
| 314 |
default_version = None |
| 315 |
params = {} |
| 316 |
params['ext'] = ext |
| 317 |
|
| 318 |
# 1. Get the current extension version: |
| 319 |
query = ("SELECT extversion FROM pg_catalog.pg_extension " |
| 320 |
"WHERE extname = %(ext)s") |
| 321 |
|
| 322 |
cursor.execute(query, params) |
| 323 |
|
| 324 |
res = cursor.fetchone() |
| 325 |
if res: |
| 326 |
current_version = res["extversion"] |
| 327 |
|
| 328 |
# 2. Get the extension default version: |
| 329 |
query = ("SELECT default_version FROM pg_catalog.pg_available_extensions " |
| 330 |
"WHERE name = %(ext)s") |
| 331 |
|
| 332 |
cursor.execute(query, params) |
| 333 |
|
| 334 |
res = cursor.fetchone() |
| 335 |
if res: |
| 336 |
default_version = res["default_version"] |
| 337 |
|
| 338 |
# 3. Get extension available versions: |
| 339 |
query = ("SELECT version FROM pg_catalog.pg_available_extension_versions " |
| 340 |
"WHERE name = %(ext)s") |
| 341 |
|
| 342 |
cursor.execute(query, params) |
| 343 |
|
| 344 |
available_versions = set(r["version"] for r in cursor.fetchall()) |
| 345 |
|
| 346 |
if current_version is None: |
| 347 |
current_version = False |
| 348 |
if default_version is None: |
| 349 |
default_version = False |
| 350 |
|
| 351 |
return (current_version, default_version, available_versions) |
| 352 |
|
| 353 |
|
| 354 |
def ext_valid_update_path(cursor, ext, current_version, version): |
| 355 |
""" |
| 356 |
Check to see if the installed extension version has a valid update |
| 357 |
path to the given version. |
| 358 |
|
| 359 |
Return True if a valid path exists. Otherwise return False. |
| 360 |
|
| 361 |
Note: 'latest' is not a valid value for version here as it can be |
| 362 |
replaced with default_version specified in extension control file. |
| 363 |
|
| 364 |
Args: |
| 365 |
cursor (cursor) -- cursor object of psycopg library |
| 366 |
ext (str) -- extension name |
| 367 |
current_version (str) -- installed version of the extension. |
| 368 |
version (str) -- target extension version to update to. |
| 369 |
""" |
| 370 |
|
| 371 |
valid_path = False |
| 372 |
params = {} |
| 373 |
query = ("SELECT path FROM pg_extension_update_paths(%(ext)s) " |
| 374 |
"WHERE source = %(cv)s " |
| 375 |
"AND target = %(ver)s") |
| 376 |
|
| 377 |
params['ext'] = ext |
| 378 |
params['cv'] = current_version |
| 379 |
params['ver'] = version |
| 380 |
|
| 381 |
cursor.execute(query, params) |
| 382 |
res = cursor.fetchone() |
| 383 |
if res is not None: |
| 384 |
valid_path = True |
| 385 |
|
| 386 |
return (valid_path) |
| 387 |
|
| 388 |
|
| 389 |
# =========================================== |
| 390 |
# Module execution. |
| 391 |
# |
| 392 |
|
| 393 |
|
| 394 |
def main(): |
| 395 |
argument_spec = postgres_common_argument_spec() |
| 396 |
argument_spec.update( |
| 397 |
login_db=dict(type='str', aliases=['db'], required=True, deprecated_aliases=[ |
| 398 |
{ |
| 399 |
'name': 'db', |
| 400 |
'version': '5.0.0', |
| 401 |
'collection_name': 'community.postgresql', |
| 402 |
}], |
| 403 |
), |
| 404 |
ext=dict(type="str", required=True, aliases=["name"]), |
| 405 |
schema=dict(type="str"), |
| 406 |
state=dict(type="str", default="present", choices=["absent", "present"]), |
| 407 |
cascade=dict(type="bool", default=False), |
| 408 |
session_role=dict(type="str"), |
| 409 |
version=dict(type="str"), |
| 410 |
trust_input=dict(type="bool", default=True), |
| 411 |
comment=dict(type="str", default=None), |
| 412 |
) |
| 413 |
|
| 414 |
module = AnsibleModule( |
| 415 |
argument_spec=argument_spec, |
| 416 |
supports_check_mode=True, |
| 417 |
) |
| 418 |
|
| 419 |
ext = module.params["ext"] |
| 420 |
schema = module.params["schema"] |
| 421 |
state = module.params["state"] |
| 422 |
cascade = module.params["cascade"] |
| 423 |
version = module.params["version"] |
| 424 |
session_role = module.params["session_role"] |
| 425 |
trust_input = module.params["trust_input"] |
| 426 |
comment = module.params["comment"] |
| 427 |
|
| 428 |
changed = False |
| 429 |
|
| 430 |
if not trust_input: |
| 431 |
check_input(module, ext, schema, version, session_role, comment) |
| 432 |
|
| 433 |
if version and state == 'absent': |
| 434 |
module.warn("Parameter version is ignored when state=absent") |
| 435 |
|
| 436 |
# Ensure psycopg libraries are available before connecting to DB: |
| 437 |
ensure_required_libs(module) |
| 438 |
conn_params = get_conn_params(module, module.params) |
| 439 |
db_connection, dummy = connect_to_db(module, conn_params, autocommit=True) |
| 440 |
cursor = db_connection.cursor(**pg_cursor_args) |
| 441 |
|
| 442 |
try: |
| 443 |
# Get extension info and available versions: |
| 444 |
curr_version, default_version, available_versions = ext_get_versions(cursor, ext) |
| 445 |
|
| 446 |
# Decode version 'latest' when passed (if version is not passed 'latest' is assumed) |
| 447 |
# Note: real_version used for checks but not in CREATE/DROP/ALTER EXTENSION commands, |
| 448 |
# as the correct way to obtain 'latest' version is not specify the version |
| 449 |
if not version or version == 'latest': |
| 450 |
# If there are not available versions the extension is not available |
| 451 |
if not available_versions: |
| 452 |
module.fail_json(msg="Extension %s is not available" % ext) |
| 453 |
# Check default_version is available |
| 454 |
if default_version: |
| 455 |
# 'latest' version matches default_version specified in extension control file |
| 456 |
real_version = default_version |
| 457 |
else: |
| 458 |
# Passed version is 'latest', versions are available, but no default_version is specified |
| 459 |
# in extension control file. In this situation CREATE/ALTER EXTENSION commands fail if |
| 460 |
# a specific version is not passed ('latest' cannot be determined). |
| 461 |
module.fail_json(msg="Passed version 'latest' but no default_version available " |
| 462 |
"in extension control file") |
| 463 |
else: |
| 464 |
real_version = version |
| 465 |
|
| 466 |
if state == "present": |
| 467 |
|
| 468 |
# If version passed: |
| 469 |
if version: |
| 470 |
# If extension is installed, update to passed version if a valid path exists |
| 471 |
if curr_version: |
| 472 |
# Given/Latest version already installed |
| 473 |
if curr_version == real_version: |
| 474 |
changed = False |
| 475 |
# Attempt to update to given/latest version |
| 476 |
else: |
| 477 |
valid_update_path = ext_valid_update_path(cursor, ext, curr_version, real_version) |
| 478 |
if valid_update_path: |
| 479 |
# Reconnect (required by some extensions like timescaledb) |
| 480 |
if not module.check_mode: |
| 481 |
db_connection.close() |
| 482 |
db_connection, dummy = connect_to_db(module, conn_params, autocommit=True) |
| 483 |
cursor = db_connection.cursor(**pg_cursor_args) |
| 484 |
changed = ext_update_version(module.check_mode, cursor, ext, version) |
| 485 |
else: |
| 486 |
if version == 'latest': |
| 487 |
# No valid update path from curr_version to latest extension version |
| 488 |
# (extension is buggy or no direct update supported) |
| 489 |
module.fail_json(msg="Latest version '%s' has no valid update path from " |
| 490 |
"the currently installed version '%s'" % (real_version, curr_version)) |
| 491 |
else: |
| 492 |
module.fail_json(msg="Passed version '%s' has no valid update path from " |
| 493 |
"the currently installed version '%s' or " |
| 494 |
"the passed version is not available" % (version, curr_version)) |
| 495 |
# If extension is not installed, install passed version |
| 496 |
else: |
| 497 |
# If passed version not available fail |
| 498 |
if real_version not in available_versions: |
| 499 |
if version == 'latest': |
| 500 |
# Latest version not available (extension is buggy) |
| 501 |
module.fail_json(msg="Latest version '%s' is not available" % real_version) |
| 502 |
else: |
| 503 |
module.fail_json(msg="Passed version '%s' is not available" % real_version) |
| 504 |
# Else install the passed version |
| 505 |
else: |
| 506 |
changed = ext_create(module.check_mode, cursor, ext, schema, cascade, version) |
| 507 |
|
| 508 |
# If version is not passed: |
| 509 |
else: |
| 510 |
# Extension exists, no request to update so no change |
| 511 |
if curr_version: |
| 512 |
changed = False |
| 513 |
else: |
| 514 |
# If the ext doesn't exist and is available: |
| 515 |
if available_versions: |
| 516 |
# 'latest' version installed by default if version not passed |
| 517 |
changed = ext_create(module.check_mode, cursor, ext, schema, cascade, 'latest') |
| 518 |
# If the ext doesn't exist and is not available: |
| 519 |
else: |
| 520 |
module.fail_json(msg="Extension %s is not available" % ext) |
| 521 |
|
| 522 |
if comment is not None: |
| 523 |
current_comment = get_comment(cursor, 'extension', ext) |
| 524 |
# For the resetting comment feature (comment: '') to work correctly |
| 525 |
current_comment = current_comment if current_comment is not None else '' |
| 526 |
if comment != current_comment: |
| 527 |
changed = set_comment(cursor, comment, 'extension', ext, module.check_mode, executed_queries) |
| 528 |
|
| 529 |
elif state == "absent": |
| 530 |
if curr_version: |
| 531 |
changed = ext_delete(module.check_mode, cursor, ext, cascade) |
| 532 |
else: |
| 533 |
changed = False |
| 534 |
|
| 535 |
# Get extension info again: |
| 536 |
new_version, new_default_version, new_available_versions = ext_get_versions(cursor, ext) |
| 537 |
|
| 538 |
# Parse previous and current version for module output |
| 539 |
out_prev_version = curr_version if curr_version else '' |
| 540 |
if module.check_mode and changed: |
| 541 |
if state == "present": |
| 542 |
out_version = real_version |
| 543 |
elif state == "absent": |
| 544 |
out_version = '' |
| 545 |
else: |
| 546 |
out_version = new_version if new_version else '' |
| 547 |
|
| 548 |
except Exception as e: |
| 549 |
db_connection.close() |
| 550 |
module.fail_json(msg="Management of PostgreSQL extension failed: %s" % to_native(e), exception=traceback.format_exc()) |
| 551 |
|
| 552 |
db_connection.close() |
| 553 |
module.exit_json( |
| 554 |
changed=changed, |
| 555 |
db=module.params["login_db"], |
| 556 |
ext=ext, |
| 557 |
prev_version=out_prev_version, |
| 558 |
version=out_version, |
| 559 |
queries=executed_queries, |
| 560 |
) |
| 561 |
|
| 562 |
|
| 563 |
if __name__ == '__main__': |
| 564 |
main() |