Debian Codegraph @

ansible_collections/community/postgresql/plugins/modules/postgresql_subscription.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2019, Andrew Klychkov (@Andersson007) <[email protected]>
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
12 DOCUMENTATION = r'''
13 ---
14 module: postgresql_subscription
15 short_description: Add, update, or remove PostgreSQL subscription
16 description:
17 - Add, update, or remove PostgreSQL subscription.
18 version_added: '0.2.0'
19
20 options:
21 name:
22 description:
23 - Name of the subscription to add, update, or remove.
24 type: str
25 required: true
26 login_db:
27 description:
28 - Name of the database to connect to and where
29 the subscription state will be changed.
30 - The V(db) alias is deprecated and will be removed in version 5.0.0.
31 aliases: [ db ]
32 type: str
33 required: true
34 state:
35 description:
36 - The subscription state.
37 - C(present) implies that if I(name) subscription doesn't exist, it will be created.
38 - C(absent) implies that if I(name) subscription exists, it will be removed.
39 - C(refresh) implies that if I(name) subscription exists, it will be refreshed.
40 Fetch missing table information from publisher. Always returns ``changed`` is ``True``.
41 This will start replication of tables that were added to the subscribed-to publications
42 since the last invocation of REFRESH PUBLICATION or since CREATE SUBSCRIPTION.
43 The existing data in the publications that are being subscribed to
44 should be copied once the replication starts.
45 - For more information about C(refresh) see U(https://www.postgresql.org/docs/current/sql-altersubscription.html).
46 type: str
47 choices: [ absent, present, refresh ]
48 default: present
49 owner:
50 description:
51 - Subscription owner.
52 - If I(owner) is not defined, the owner will be set as I(login_user) or I(session_role).
53 - Ignored when I(state) is not C(present).
54 type: str
55 publications:
56 description:
57 - The publication names on the publisher to use for the subscription.
58 - Ignored when I(state) is not C(present).
59 type: list
60 elements: str
61 connparams:
62 description:
63 - The connection dict param-value to connect to the publisher.
64 - For more information see U(https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING).
65 - Ignored when I(state) is not C(present).
66 - Ignored when an existing subscription's connection parameters are not available from the server (such as in CloudSQL).
67 type: dict
68 cascade:
69 description:
70 - Drop subscription dependencies. Has effect with I(state=absent) only.
71 - Ignored when I(state) is not C(absent).
72 type: bool
73 default: false
74 subsparams:
75 description:
76 - Dictionary of optional parameters for a subscription, e.g. copy_data, enabled, create_slot, etc.
77 - For update the subscription allowed keys are C(enabled), C(slot_name), C(synchronous_commit), C(publication_name).
78 - See available parameters to create a new subscription
79 on U(https://www.postgresql.org/docs/current/sql-createsubscription.html).
80 - Ignored when I(state) is not C(present).
81 type: dict
82 session_role:
83 description:
84 - Switch to session_role after connecting. The specified session_role must
85 be a role that the current login_user is a member of.
86 - Permissions checking for SQL commands is carried out as though
87 the session_role were the one that had logged in originally.
88 type: str
89 version_added: '0.2.0'
90 trust_input:
91 description:
92 - If C(false), check whether values of parameters I(name), I(publications), I(owner),
93 I(session_role), I(connparams), I(subsparams) are potentially dangerous.
94 - It makes sense to use C(true) only when SQL injections via the parameters are possible.
95 type: bool
96 default: true
97 version_added: '0.2.0'
98 comment:
99 description:
100 - Sets a comment on the subscription.
101 - To reset the comment, pass an empty string.
102 type: str
103 version_added: '3.3.0'
104
105 notes:
106 - PostgreSQL version must be 10 or greater.
107
108 attributes:
109 check_mode:
110 support: full
111
112 seealso:
113 - module: community.postgresql.postgresql_publication
114 - module: community.postgresql.postgresql_info
115 - name: CREATE SUBSCRIPTION reference
116 description: Complete reference of the CREATE SUBSCRIPTION command documentation.
117 link: https://www.postgresql.org/docs/current/sql-createsubscription.html
118 - name: ALTER SUBSCRIPTION reference
119 description: Complete reference of the ALTER SUBSCRIPTION command documentation.
120 link: https://www.postgresql.org/docs/current/sql-altersubscription.html
121 - name: DROP SUBSCRIPTION reference
122 description: Complete reference of the DROP SUBSCRIPTION command documentation.
123 link: https://www.postgresql.org/docs/current/sql-dropsubscription.html
124
125 author:
126 - Andrew Klychkov (@Andersson007) <[email protected]>
127
128 extends_documentation_fragment:
129 - community.postgresql.postgres
130 '''
131
132 EXAMPLES = r'''
133 - name: >
134 Create acme subscription in mydb database using acme_publication and
135 the following connection parameters to connect to the publisher.
136 Set the subscription owner as alice.
137 community.postgresql.postgresql_subscription:
138 login_db: mydb
139 name: acme
140 state: present
141 publications: acme_publication
142 owner: alice
143 connparams:
144 host: 127.0.0.1
145 port: 5432
146 user: repl
147 password: replpass
148 dbname: mydb
149 comment: Made by Ansible
150
151 - name: Assuming that acme subscription exists, try to change conn parameters
152 community.postgresql.postgresql_subscription:
153 login_db: mydb
154 name: acme
155 connparams:
156 host: 127.0.0.1
157 port: 5432
158 user: repl
159 password: replpass
160 connect_timeout: 100
161
162 - name: Refresh acme publication
163 community.postgresql.postgresql_subscription:
164 db: mydb
165 name: acme
166 state: refresh
167
168 - name: Drop acme subscription from mydb with dependencies (cascade=true)
169 community.postgresql.postgresql_subscription:
170 login_db: mydb
171 name: acme
172 state: absent
173 cascade: true
174
175 - name: Assuming that acme subscription exists and enabled, disable the subscription
176 community.postgresql.postgresql_subscription:
177 login_db: mydb
178 name: acme
179 state: present
180 subsparams:
181 enabled: false
182 '''
183
184 RETURN = r'''
185 name:
186 description:
187 - Name of the subscription.
188 returned: success
189 type: str
190 sample: acme
191 exists:
192 description:
193 - Flag indicates the subscription exists or not at the end of runtime.
194 returned: success
195 type: bool
196 sample: true
197 queries:
198 description: List of executed queries.
199 returned: success
200 type: str
201 sample: [ 'DROP SUBSCRIPTION "mysubscription"' ]
202 initial_state:
203 description: Subscription configuration at the beginning of runtime.
204 returned: success
205 type: dict
206 sample: {"conninfo": {}, "enabled": true, "owner": "postgres", "slotname": "test", "synccommit": true}
207 final_state:
208 description: Subscription configuration at the end of runtime.
209 returned: success
210 type: dict
211 sample: {"conninfo": {}, "enabled": true, "owner": "postgres", "slotname": "test", "synccommit": true}
212 '''
213
214 from copy import deepcopy
215
216 from ansible.module_utils.basic import AnsibleModule
217 from ansible_collections.community.postgresql.plugins.module_utils.database import \
218 check_input
219 from ansible_collections.community.postgresql.plugins.module_utils.postgres import (
220 connect_to_db,
221 ensure_required_libs,
222 exec_sql,
223 get_conn_params,
224 get_server_version,
225 pg_cursor_args,
226 postgres_common_argument_spec,
227 set_comment,
228 )
229
230 SUPPORTED_PG_VERSION = 10000
231
232 SUBSPARAMS_KEYS_FOR_UPDATE = ('enabled', 'synchronous_commit', 'slot_name')
233
234
235 ################################
236 # Module functions and classes #
237 ################################
238
239 def convert_conn_params(conn_dict):
240 """Converts the passed connection dictionary to string.
241
242 Args:
243 conn_dict (list): Dictionary which needs to be converted.
244
245 Returns:
246 Connection string.
247 """
248 conn_list = []
249 for (param, val) in conn_dict.items():
250 conn_list.append('%s=%s' % (param, val))
251
252 return ' '.join(conn_list)
253
254
255 def convert_subscr_params(params_dict):
256 """Converts the passed params dictionary to string.
257
258 Args:
259 params_dict (list): Dictionary which needs to be converted.
260
261 Returns:
262 Parameters string.
263 """
264 params_list = []
265 for (param, val) in params_dict.items():
266 if val is False:
267 val = 'false'
268 elif val is True:
269 val = 'true'
270
271 params_list.append('%s = %s' % (param, val))
272
273 return ', '.join(params_list)
274
275
276 def cast_connparams(connparams_dict):
277 """Cast the passed connparams_dict dictionary
278
279 Returns:
280 Dictionary
281 """
282 for (param, val) in connparams_dict.items():
283 try:
284 connparams_dict[param] = int(val)
285 except ValueError:
286 connparams_dict[param] = val
287
288 return connparams_dict
289
290
291 class PgSubscription():
292 """Class to work with PostgreSQL subscription.
293
294 Args:
295 module (AnsibleModule): Object of AnsibleModule class.
296 cursor (cursor): Cursor object of psycopg library to work with PostgreSQL.
297 name (str): The name of the subscription.
298 db (str): The database name the subscription will be associated with.
299
300 Attributes:
301 module (AnsibleModule): Object of AnsibleModule class.
302 cursor (cursor): Cursor object of psycopg library to work with PostgreSQL.
303 name (str): Name of subscription.
304 executed_queries (list): List of executed queries.
305 attrs (dict): Dict with subscription attributes.
306 exists (bool): Flag indicates the subscription exists or not.
307 """
308
309 def __init__(self, module, cursor, name, db):
310 self.module = module
311 self.cursor = cursor
312 self.name = name
313 self.db = db
314 self.executed_queries = []
315 self.attrs = {
316 'owner': None,
317 'enabled': None,
318 'synccommit': None,
319 'conninfo': {},
320 'slotname': None,
321 'publications': [],
322 'comment': None,
323 }
324 self.empty_attrs = deepcopy(self.attrs)
325 self.exists = self.check_subscr()
326
327 def get_info(self):
328 """Refresh the subscription information.
329
330 Returns:
331 ``self.attrs``.
332 """
333 self.exists = self.check_subscr()
334 return self.attrs
335
336 def check_subscr(self):
337 """Check the subscription and refresh ``self.attrs`` subscription attribute.
338
339 Returns:
340 True if the subscription with ``self.name`` exists, False otherwise.
341 """
342
343 subscr_info = self.__get_general_subscr_info()
344
345 if not subscr_info:
346 # The subscription does not exist:
347 self.attrs = deepcopy(self.empty_attrs)
348 return False
349
350 self.attrs['owner'] = subscr_info.get('rolname')
351 self.attrs['enabled'] = subscr_info.get('subenabled')
352 self.attrs['synccommit'] = subscr_info.get('subenabled')
353 self.attrs['slotname'] = subscr_info.get('subslotname')
354 self.attrs['publications'] = subscr_info.get('subpublications')
355 if subscr_info.get('comment') is not None:
356 self.attrs['comment'] = subscr_info.get('comment')
357 else:
358 # To support the comment resetting functionality
359 self.attrs['comment'] = ''
360 if subscr_info.get('subconninfo'):
361 for param in subscr_info['subconninfo'].split(' '):
362 tmp = param.split('=')
363 try:
364 self.attrs['conninfo'][tmp[0]] = int(tmp[1])
365 except ValueError:
366 self.attrs['conninfo'][tmp[0]] = tmp[1]
367
368 return True
369
370 def create(self, connparams, publications, subsparams, check_mode=True):
371 """Create the subscription.
372
373 Args:
374 connparams (str): Connection string in libpq style.
375 publications (list): Publications on the primary to use.
376 subsparams (str): Parameters string in WITH () clause style.
377
378 Kwargs:
379 check_mode (bool): If True, don't actually change anything,
380 just make SQL, add it to ``self.executed_queries`` and return True.
381
382 Returns:
383 changed (bool): True if the subscription has been created, otherwise False.
384 """
385 query_fragments = []
386 query_fragments.append("CREATE SUBSCRIPTION %s CONNECTION '%s' "
387 "PUBLICATION %s" % (self.name, connparams, ', '.join(publications)))
388
389 if subsparams:
390 query_fragments.append("WITH (%s)" % subsparams)
391
392 changed = self.__exec_sql(' '.join(query_fragments), check_mode=check_mode)
393
394 return changed
395
396 def update(self, connparams, publications, subsparams, check_mode=True):
397 """Update the subscription.
398
399 Args:
400 connparams (dict): Connection dict in libpq style.
401 publications (list): Publications on the primary to use.
402 subsparams (dict): Dictionary of optional parameters.
403
404 Kwargs:
405 check_mode (bool): If True, don't actually change anything,
406 just make SQL, add it to ``self.executed_queries`` and return True.
407
408 Returns:
409 changed (bool): True if subscription has been updated, otherwise False.
410 """
411 changed = False
412
413 if connparams:
414 if connparams != self.attrs['conninfo']:
415 changed = self.__set_conn_params(convert_conn_params(connparams),
416 check_mode=check_mode)
417
418 if publications:
419 if sorted(self.attrs['publications']) != sorted(publications):
420 changed = self.__set_publications(publications, check_mode=check_mode)
421
422 if subsparams:
423 params_to_update = []
424
425 for (param, value) in subsparams.items():
426 if param == 'enabled':
427 if self.attrs['enabled'] and value is False:
428 changed = self.enable(enabled=False, check_mode=check_mode)
429 elif not self.attrs['enabled'] and value is True:
430 changed = self.enable(enabled=True, check_mode=check_mode)
431
432 elif param == 'synchronous_commit':
433 if self.attrs['synccommit'] is True and value is False:
434 params_to_update.append("%s = false" % param)
435 elif self.attrs['synccommit'] is False and value is True:
436 params_to_update.append("%s = true" % param)
437
438 elif param == 'slot_name':
439 if self.attrs['slotname'] and self.attrs['slotname'] != value:
440 params_to_update.append("%s = %s" % (param, value))
441
442 else:
443 self.module.warn("Parameter '%s' is not in params supported "
444 "for update '%s', ignored..." % (param, SUBSPARAMS_KEYS_FOR_UPDATE))
445
446 if params_to_update:
447 changed = self.__set_params(params_to_update, check_mode=check_mode)
448
449 return changed
450
451 def drop(self, cascade=False, check_mode=True):
452 """Drop the subscription.
453
454 Kwargs:
455 cascade (bool): Flag indicates that the subscription needs to be deleted
456 with its dependencies.
457 check_mode (bool): If True, don't actually change anything,
458 just make SQL, add it to ``self.executed_queries`` and return True.
459
460 Returns:
461 changed (bool): True if the subscription has been removed, otherwise False.
462 """
463 if self.exists:
464 query_fragments = ["DROP SUBSCRIPTION %s" % self.name]
465 if cascade:
466 query_fragments.append("CASCADE")
467
468 return self.__exec_sql(' '.join(query_fragments), check_mode=check_mode)
469
470 def set_owner(self, role, check_mode=True):
471 """Set a subscription owner.
472
473 Args:
474 role (str): Role (user) name that needs to be set as a subscription owner.
475
476 Kwargs:
477 check_mode (bool): If True, don't actually change anything,
478 just make SQL, add it to ``self.executed_queries`` and return True.
479
480 Returns:
481 True if successful, False otherwise.
482 """
483 query = 'ALTER SUBSCRIPTION %s OWNER TO "%s"' % (self.name, role)
484 return self.__exec_sql(query, check_mode=check_mode)
485
486 def set_comment(self, comment, check_mode=True):
487 """Set a subscription comment.
488
489 Args:
490 comment (str): Comment to set on the subscription.
491
492 Kwargs:
493 check_mode (bool): If True, don not change anything.
494
495 Returns:
496 True if success, False otherwise.
497 """
498 set_comment(self.cursor, comment, 'subscription', self.name, check_mode, self.executed_queries)
499
500 return True
501
502 def refresh(self, check_mode=True):
503 """Refresh publication.
504
505 Fetches missing table info from publisher.
506
507 Kwargs:
508 check_mode (bool): If True, don't actually change anything,
509 just make SQL, add it to ``self.executed_queries`` and return True.
510
511 Returns:
512 True if successful, False otherwise.
513 """
514 query = 'ALTER SUBSCRIPTION %s REFRESH PUBLICATION' % self.name
515 return self.__exec_sql(query, check_mode=check_mode)
516
517 def __set_params(self, params_to_update, check_mode=True):
518 """Update optional subscription parameters.
519
520 Args:
521 params_to_update (list): Parameters with values to update.
522
523 Kwargs:
524 check_mode (bool): If True, don't actually change anything,
525 just make SQL, add it to ``self.executed_queries`` and return True.
526
527 Returns:
528 True if successful, False otherwise.
529 """
530 query = 'ALTER SUBSCRIPTION %s SET (%s)' % (self.name, ', '.join(params_to_update))
531 return self.__exec_sql(query, check_mode=check_mode)
532
533 def __set_conn_params(self, connparams, check_mode=True):
534 """Update connection parameters.
535
536 Args:
537 connparams (str): Connection string in libpq style.
538
539 Kwargs:
540 check_mode (bool): If True, don't actually change anything,
541 just make SQL, add it to ``self.executed_queries`` and return True.
542
543 Returns:
544 True if successful, False otherwise.
545 """
546 query = "ALTER SUBSCRIPTION %s CONNECTION '%s'" % (self.name, connparams)
547 return self.__exec_sql(query, check_mode=check_mode)
548
549 def __set_publications(self, publications, check_mode=True):
550 """Update publications.
551
552 Args:
553 publications (list): Publications on the primary to use.
554
555 Kwargs:
556 check_mode (bool): If True, don't actually change anything,
557 just make SQL, add it to ``self.executed_queries`` and return True.
558
559 Returns:
560 True if successful, False otherwise.
561 """
562 query = 'ALTER SUBSCRIPTION %s SET PUBLICATION %s' % (self.name, ', '.join(publications))
563 return self.__exec_sql(query, check_mode=check_mode)
564
565 def enable(self, enabled=True, check_mode=True):
566 """Enable or disable the subscription.
567
568 Kwargs:
569 enable (bool): Flag indicates that the subscription needs
570 to be enabled or disabled.
571 check_mode (bool): If True, don't actually change anything,
572 just make SQL, add it to ``self.executed_queries`` and return True.
573
574 Returns:
575 True if successful, False otherwise.
576 """
577 if enabled:
578 query = 'ALTER SUBSCRIPTION %s ENABLE' % self.name
579 else:
580 query = 'ALTER SUBSCRIPTION %s DISABLE' % self.name
581
582 return self.__exec_sql(query, check_mode=check_mode)
583
584 def __get_general_subscr_info(self):
585 """Get and return general subscription information.
586
587 Returns:
588 Dict with subscription information if successful, False otherwise.
589 """
590 columns_sub_table = ("SELECT column_name "
591 "FROM information_schema.columns "
592 "WHERE table_schema = 'pg_catalog' "
593 "AND table_name = 'pg_subscription'"
594 "AND column_name IN ('subenabled','subconninfo','subslotname','subsynccommit','subpublications')")
595 columns_result = exec_sql(self, columns_sub_table, query_params={'name': self.name, 'db': self.db}, add_to_executed=False)
596 columns = ", ".join(["s.%s" % column['column_name'] for column in columns_result])
597 query = ("SELECT obj_description(s.oid, 'pg_subscription') AS comment, "
598 "d.datname, r.rolname," + columns + " "
599 "FROM pg_catalog.pg_subscription s "
600 "JOIN pg_catalog.pg_database d "
601 "ON s.subdbid = d.oid "
602 "JOIN pg_catalog.pg_roles AS r "
603 "ON s.subowner = r.oid "
604 "WHERE s.subname = %(name)s AND d.datname = %(db)s")
605
606 result = exec_sql(self, query, query_params={'name': self.name, 'db': self.db}, add_to_executed=False)
607 if result:
608 return result[0]
609 else:
610 return False
611
612 def __exec_sql(self, query, check_mode=False):
613 """Execute SQL query.
614
615 Note: If we need just to get information from the database,
616 we use ``exec_sql`` function directly.
617
618 Args:
619 query (str): Query that needs to be executed.
620
621 Kwargs:
622 check_mode (bool): If True, don't actually change anything,
623 just add ``query`` to ``self.executed_queries`` and return True.
624
625 Returns:
626 True if successful, False otherwise.
627 """
628 if check_mode:
629 self.executed_queries.append(query)
630 return True
631 else:
632 return exec_sql(self, query, return_bool=True)
633
634
635 # ===========================================
636 # Module execution.
637 #
638
639
640 def main():
641 argument_spec = postgres_common_argument_spec()
642 argument_spec.update(
643 name=dict(type='str', required=True),
644 login_db=dict(type='str', required=True, aliases=['db'], deprecated_aliases=[
645 {
646 'name': 'db',
647 'version': '5.0.0',
648 'collection_name': 'community.postgresql',
649 }],
650 ),
651 state=dict(type='str', default='present', choices=['absent', 'present', 'refresh']),
652 publications=dict(type='list', elements='str'),
653 connparams=dict(type='dict'),
654 cascade=dict(type='bool', default=False),
655 owner=dict(type='str'),
656 subsparams=dict(type='dict'),
657 session_role=dict(type='str'),
658 trust_input=dict(type='bool', default=True),
659 comment=dict(type='str', default=None),
660 )
661 module = AnsibleModule(
662 argument_spec=argument_spec,
663 supports_check_mode=True,
664 )
665
666 # Parameters handling:
667 db = module.params['login_db']
668 name = module.params['name']
669 state = module.params['state']
670 publications = module.params['publications']
671 cascade = module.params['cascade']
672 owner = module.params['owner']
673 subsparams = module.params['subsparams']
674 connparams = module.params['connparams']
675 session_role = module.params['session_role']
676 trust_input = module.params['trust_input']
677 comment = module.params['comment']
678
679 if not trust_input:
680 # Check input for potentially dangerous elements:
681 if not subsparams:
682 subsparams_str = None
683 else:
684 subsparams_str = convert_subscr_params(subsparams)
685
686 if not connparams:
687 connparams_str = None
688 else:
689 connparams_str = convert_conn_params(connparams)
690
691 check_input(module, name, publications, owner, session_role,
692 connparams_str, subsparams_str, comment)
693
694 if state == 'present' and cascade:
695 module.warn('parameter "cascade" is ignored when state is not absent')
696
697 if state != 'present':
698 if owner:
699 module.warn("parameter 'owner' is ignored when state is not 'present'")
700 if publications:
701 module.warn("parameter 'publications' is ignored when state is not 'present'")
702 if connparams:
703 module.warn("parameter 'connparams' is ignored when state is not 'present'")
704 if subsparams:
705 module.warn("parameter 'subsparams' is ignored when state is not 'present'")
706 if comment is not None:
707 module.warn("parameter 'comment' is ignored when state is not 'present'")
708
709 # Ensure psycopg libraries are available before connecting to DB:
710 ensure_required_libs(module)
711 # Connect to DB and make cursor object:
712 pg_conn_params = get_conn_params(module, module.params)
713 # We check subscription state without DML queries execution, so set autocommit:
714 db_connection, dummy = connect_to_db(module, pg_conn_params, autocommit=True)
715 cursor = db_connection.cursor(**pg_cursor_args)
716
717 # Check version:
718 if get_server_version(cursor.connection) < SUPPORTED_PG_VERSION:
719 module.fail_json(msg="PostgreSQL server version should be 10.0 or greater")
720
721 # Set defaults:
722 changed = False
723 initial_state = {}
724 final_state = {}
725
726 ###################################
727 # Create object and do rock'n'roll:
728 subscription = PgSubscription(module, cursor, name, db)
729
730 if subscription.exists:
731 initial_state = deepcopy(subscription.attrs)
732 final_state = deepcopy(initial_state)
733
734 if state == 'present':
735 if not subscription.exists:
736 if subsparams:
737 subsparams = convert_subscr_params(subsparams)
738
739 if connparams:
740 connparams = convert_conn_params(connparams)
741
742 changed = subscription.create(connparams,
743 publications,
744 subsparams,
745 check_mode=module.check_mode)
746
747 else:
748 if subscription.attrs['conninfo'] != {}:
749 if connparams:
750 connparams = cast_connparams(connparams)
751
752 changed = subscription.update(connparams,
753 publications,
754 subsparams,
755 check_mode=module.check_mode)
756 else:
757 module.warn("'connparams' is ignored because pg_subscription.subconninfo is not accessible in your instance.")
758 changed = subscription.update(False,
759 publications,
760 subsparams,
761 check_mode=module.check_mode)
762
763 if owner and subscription.attrs['owner'] != owner:
764 changed = subscription.set_owner(owner, check_mode=module.check_mode) or changed
765
766 if comment is not None and comment != subscription.attrs['comment']:
767 changed = subscription.set_comment(comment, check_mode=module.check_mode) or changed
768
769 elif state == 'absent':
770 changed = subscription.drop(cascade, check_mode=module.check_mode)
771
772 elif state == 'refresh':
773 if not subscription.exists:
774 module.fail_json(msg="Refresh failed: subscription '%s' does not exist" % name)
775
776 # Always returns True:
777 changed = subscription.refresh(check_mode=module.check_mode)
778
779 # Get final subscription info:
780 final_state = subscription.get_info()
781
782 # Connection is not needed any more:
783 cursor.close()
784 db_connection.close()
785
786 # Return ret values and exit:
787 module.exit_json(changed=changed,
788 name=name,
789 exists=subscription.exists,
790 queries=subscription.executed_queries,
791 initial_state=initial_state,
792 final_state=final_state)
793
794
795 if __name__ == '__main__':
796 main()