Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/rds_option_group.py

raw
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 DOCUMENTATION = r"""
8 module: rds_option_group
9 short_description: Manages the creation, modification, deletion of RDS option groups
10 version_added: 5.0.0
11 description:
12 - Manages the creation, modification, deletion of RDS option groups.
13 - This module was originally added to C(community.aws) in release 2.1.0.
14 author:
15 - "Nick Aslanidis (@naslanidis)"
16 - "Will Thames (@willthames)"
17 - "Alina Buzachis (@alinabuzachis)"
18 options:
19 state:
20 description:
21 - Specifies whether the option group should be V(present) or V(absent).
22 required: true
23 choices: [ 'present', 'absent' ]
24 type: str
25 option_group_name:
26 description:
27 - Specifies the name of the option group to be created.
28 required: true
29 type: str
30 engine_name:
31 description:
32 - Specifies the name of the engine that this option group should be associated with.
33 type: str
34 major_engine_version:
35 description:
36 - Specifies the major version of the engine that this option group should be associated with.
37 type: str
38 option_group_description:
39 description:
40 - The description of the option group.
41 type: str
42 apply_immediately:
43 description:
44 - Indicates whether the changes should be applied immediately, or during the next maintenance window.
45 required: false
46 type: bool
47 default: false
48 options:
49 description:
50 - Options in this list are added to the option group.
51 - If already present, the specified configuration is used to update the existing configuration.
52 - If none are supplied, any existing options are removed.
53 type: list
54 elements: dict
55 suboptions:
56 option_name:
57 description: The configuration of options to include in a group.
58 required: false
59 type: str
60 port:
61 description: The optional port for the option.
62 required: false
63 type: int
64 option_version:
65 description: The version for the option.
66 required: false
67 type: str
68 option_settings:
69 description: The option settings to include in an option group.
70 required: false
71 type: list
72 elements: dict
73 suboptions:
74 name:
75 description: The name of the option that has settings that you can set.
76 required: false
77 type: str
78 value:
79 description: The current value of the option setting.
80 required: false
81 type: str
82 default_value:
83 description: The default value of the option setting.
84 required: false
85 type: str
86 description:
87 description: The description of the option setting.
88 required: false
89 type: str
90 apply_type:
91 description: The DB engine specific parameter type.
92 required: false
93 type: str
94 data_type:
95 description: The data type of the option setting.
96 required: false
97 type: str
98 allowed_values:
99 description: The allowed values of the option setting.
100 required: false
101 type: str
102 is_modifiable:
103 description: A Boolean value that, when V(true), indicates the option setting can be modified from the default.
104 required: false
105 type: bool
106 is_collection:
107 description: Indicates if the option setting is part of a collection.
108 required: false
109 type: bool
110 db_security_group_memberships:
111 description: A list of V(DBSecurityGroupMembership) name strings used for this option.
112 required: false
113 type: list
114 elements: str
115 vpc_security_group_memberships:
116 description: A list of V(VpcSecurityGroupMembership) name strings used for this option.
117 required: false
118 type: list
119 elements: str
120 wait:
121 description: Whether to wait for the cluster to be available or deleted.
122 type: bool
123 default: true
124 extends_documentation_fragment:
125 - amazon.aws.common.modules
126 - amazon.aws.region.modules
127 - amazon.aws.tags
128 - amazon.aws.boto3
129 """
130
131 EXAMPLES = r"""
132 # Create an RDS Mysql Option group
133 - name: Create an RDS Mysql option group
134 amazon.aws.rds_option_group:
135 state: present
136 option_group_name: test-mysql-option-group
137 engine_name: mysql
138 major_engine_version: 5.6
139 option_group_description: test mysql option group
140 apply_immediately: true
141 options:
142 - option_name: MEMCACHED
143 port: 11211
144 vpc_security_group_memberships:
145 - "sg-d188c123"
146 option_settings:
147 - name: MAX_SIMULTANEOUS_CONNECTIONS
148 value: "20"
149 - name: CHUNK_SIZE_GROWTH_FACTOR
150 value: "1.25"
151 register: new_rds_mysql_option_group
152
153 # Remove currently configured options for an option group by removing options argument
154 - name: Create an RDS Mysql option group
155 amazon.aws.rds_option_group:
156 state: present
157 option_group_name: test-mysql-option-group
158 engine_name: mysql
159 major_engine_version: 5.6
160 option_group_description: test mysql option group
161 apply_immediately: true
162 register: rds_mysql_option_group
163
164 - name: Create an RDS Mysql option group using tags
165 amazon.aws.rds_option_group:
166 state: present
167 option_group_name: test-mysql-option-group
168 engine_name: mysql
169 major_engine_version: 5.6
170 option_group_description: test mysql option group
171 apply_immediately: true
172 tags:
173 Tag1: tag1
174 Tag2: tag2
175 register: rds_mysql_option_group
176
177 # Delete an RDS Mysql Option group
178 - name: Delete an RDS Mysql option group
179 amazon.aws.rds_option_group:
180 state: absent
181 option_group_name: test-mysql-option-group
182 register: deleted_rds_mysql_option_group
183 """
184
185 RETURN = r"""
186 allows_vpc_and_non_vpc_instance_memberships:
187 description: Indicates whether this option group can be applied to both VPC and non-VPC instances.
188 returned: always
189 type: bool
190 sample: false
191 changed:
192 description: If the Option Group has changed.
193 type: bool
194 returned: always
195 sample: true
196 engine_name:
197 description: Indicates the name of the engine that this option group can be applied to.
198 returned: always
199 type: str
200 sample: "mysql"
201 major_engine_version:
202 description: Indicates the major engine version associated with this option group.
203 returned: always
204 type: str
205 sample: "5.6"
206 option_group_arn:
207 description: The Amazon Resource Name (ARN) for the option group.
208 returned: always
209 type: str
210 sample: "arn:aws:rds:ap-southeast-2:123456789012:og:ansible-test-option-group"
211 option_group_description:
212 description: Provides a description of the option group.
213 returned: always
214 type: str
215 sample: "test mysql option group"
216 option_group_name:
217 description: Specifies the name of the option group.
218 returned: always
219 type: str
220 sample: "test-mysql-option-group"
221 options:
222 description: Indicates what options are available in the option group.
223 returned: always
224 type: list
225 elements: dict
226 contains:
227 db_security_group_memberships:
228 description: If the option requires access to a port, then this DB security group allows access to the port.
229 returned: always
230 type: list
231 elements: dict
232 contains:
233 status:
234 description: The status of the DB security group.
235 returned: always
236 type: str
237 sample: "available"
238 db_security_group_name:
239 description: The name of the DB security group.
240 returned: always
241 type: str
242 sample: "mydbsecuritygroup"
243 option_description:
244 description: The description of the option.
245 returned: always
246 type: str
247 sample: "Innodb Memcached for MySQL"
248 option_name:
249 description: The name of the option.
250 returned: always
251 type: str
252 sample: "MEMCACHED"
253 option_settings:
254 description: The name of the option.
255 returned: always
256 type: list
257 contains:
258 allowed_values:
259 description: The allowed values of the option setting.
260 returned: always
261 type: str
262 sample: "1-2048"
263 apply_type:
264 description: The DB engine specific parameter type.
265 returned: always
266 type: str
267 sample: "STATIC"
268 data_type:
269 description: The data type of the option setting.
270 returned: always
271 type: str
272 sample: "INTEGER"
273 default_value:
274 description: The default value of the option setting.
275 returned: always
276 type: str
277 sample: "1024"
278 description:
279 description: The description of the option setting.
280 returned: always
281 type: str
282 sample: "Verbose level for memcached."
283 is_collection:
284 description: Indicates if the option setting is part of a collection.
285 returned: always
286 type: bool
287 sample: true
288 is_modifiable:
289 description: A Boolean value that, when true, indicates the option setting can be modified from the default.
290 returned: always
291 type: bool
292 sample: true
293 name:
294 description: The name of the option that has settings that you can set.
295 returned: always
296 type: str
297 sample: "INNODB_API_ENABLE_MDL"
298 value:
299 description: The current value of the option setting.
300 returned: always
301 type: str
302 sample: "0"
303 permanent:
304 description: Indicate if this option is permanent.
305 returned: always
306 type: bool
307 sample: true
308 persistent:
309 description: Indicate if this option is persistent.
310 returned: always
311 type: bool
312 sample: true
313 port:
314 description: If required, the port configured for this option to use.
315 returned: always
316 type: int
317 sample: 11211
318 vpc_security_group_memberships:
319 description: If the option requires access to a port, then this VPC security group allows access to the port.
320 returned: always
321 type: list
322 elements: dict
323 contains:
324 status:
325 description: The status of the VPC security group.
326 returned: always
327 type: str
328 sample: "available"
329 vpc_security_group_id:
330 description: The name of the VPC security group.
331 returned: always
332 type: str
333 sample: "sg-0cd636a23ae76e9a4"
334 vpc_id:
335 description: If present, this option group can only be applied to instances that are in the VPC indicated by this field.
336 returned: always
337 type: str
338 sample: "vpc-bf07e9d6"
339 tags:
340 description: The tags associated the RDS option group.
341 type: dict
342 returned: always
343 sample: {
344 "Ansible": "Test"
345 }
346 """
347
348
349 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
350 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
351
352 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
353 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
354 from ansible_collections.amazon.aws.plugins.module_utils.rds import get_tags
355 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
356 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
357 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
358 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
359
360 try:
361 import botocore
362 except ImportError:
363 pass # caught by AnsibleAWSModule
364
365
366 @AWSRetry.jittered_backoff(retries=10)
367 def _describe_option_groups(client, **params):
368 try:
369 paginator = client.get_paginator("describe_option_groups")
370 return paginator.paginate(**params).build_full_result()["OptionGroupsList"][0]
371 except is_boto3_error_code("OptionGroupNotFoundFault"):
372 return {}
373
374
375 def get_option_group(client, module):
376 params = dict()
377 params["OptionGroupName"] = module.params.get("option_group_name")
378
379 try:
380 result = camel_dict_to_snake_dict(_describe_option_groups(client, **params))
381 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
382 module.fail_json_aws(e, msg="Couldn't describe option groups.")
383
384 if result:
385 result["tags"] = get_tags(client, module, result["option_group_arn"])
386
387 return result
388
389
390 def create_option_group_options(client, module):
391 changed = True
392 params = dict()
393 params["OptionGroupName"] = module.params.get("option_group_name")
394 options_to_include = module.params.get("options")
395 params["OptionsToInclude"] = snake_dict_to_camel_dict(options_to_include, capitalize_first=True)
396
397 if module.params.get("apply_immediately"):
398 params["ApplyImmediately"] = module.params.get("apply_immediately")
399
400 if module.check_mode:
401 return changed
402
403 try:
404 client.modify_option_group(aws_retry=True, **params)
405 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
406 module.fail_json_aws(e, msg="Unable to update Option Group.")
407
408 return changed
409
410
411 def remove_option_group_options(client, module, options_to_remove):
412 changed = True
413 params = dict()
414 params["OptionGroupName"] = module.params.get("option_group_name")
415 params["OptionsToRemove"] = options_to_remove
416
417 if module.params.get("apply_immediately"):
418 params["ApplyImmediately"] = module.params.get("apply_immediately")
419
420 if module.check_mode:
421 return changed
422
423 try:
424 client.modify_option_group(aws_retry=True, **params)
425 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
426 module.fail_json_aws(e)
427
428 return changed
429
430
431 def create_option_group(client, module):
432 changed = True
433 params = dict()
434 params["OptionGroupName"] = module.params.get("option_group_name")
435 params["EngineName"] = module.params.get("engine_name")
436 params["MajorEngineVersion"] = str(module.params.get("major_engine_version"))
437 params["OptionGroupDescription"] = module.params.get("option_group_description")
438
439 if module.params.get("tags"):
440 params["Tags"] = ansible_dict_to_boto3_tag_list(module.params.get("tags"))
441 else:
442 params["Tags"] = list()
443
444 if module.check_mode:
445 return changed
446 try:
447 client.create_option_group(aws_retry=True, **params)
448 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
449 module.fail_json_aws(e, msg="Unable to create Option Group.")
450
451 return changed
452
453
454 def match_option_group_options(client, module):
455 requires_update = False
456 new_options = module.params.get("options")
457
458 # Get existing option groups and compare to our new options spec
459 current_option = get_option_group(client, module)
460
461 if current_option["options"] == [] and new_options:
462 requires_update = True
463 else:
464 for option in current_option["options"]:
465 for setting_name in new_options:
466 if setting_name["option_name"] == option["option_name"]:
467 # Security groups need to be handled separately due to different keys on request and what is
468 # returned by the API
469 if any(
470 name in option.keys() - ["option_settings", "vpc_security_group_memberships"]
471 and setting_name[name] != option[name]
472 for name in setting_name
473 ):
474 requires_update = True
475
476 if any(name in option and name == "vpc_security_group_memberships" for name in setting_name):
477 current_sg = set(sg["vpc_security_group_id"] for sg in option["vpc_security_group_memberships"])
478 new_sg = set(setting_name["vpc_security_group_memberships"])
479 if current_sg != new_sg:
480 requires_update = True
481
482 if any(
483 new_option_setting["name"] == current_option_setting["name"]
484 and new_option_setting["value"] != current_option_setting["value"]
485 for new_option_setting in setting_name["option_settings"]
486 for current_option_setting in option["option_settings"]
487 ):
488 requires_update = True
489 else:
490 requires_update = True
491
492 return requires_update
493
494
495 def compare_option_group(client, module):
496 to_be_added = None
497 to_be_removed = None
498 current_option = get_option_group(client, module)
499 new_options = module.params.get("options")
500 new_settings = set([item["option_name"] for item in new_options])
501 old_settings = set([item["option_name"] for item in current_option["options"]])
502
503 if new_settings != old_settings:
504 to_be_added = list(new_settings - old_settings)
505 to_be_removed = list(old_settings - new_settings)
506
507 return to_be_added, to_be_removed
508
509
510 def setup_option_group(client, module):
511 results = []
512 changed = False
513 to_be_added = None
514 to_be_removed = None
515
516 # Check if there is an existing options group
517 existing_option_group = get_option_group(client, module)
518
519 if existing_option_group:
520 results = existing_option_group
521
522 # Check tagging
523 changed |= update_tags(client, module, existing_option_group)
524
525 if module.params.get("options"):
526 # Check if existing options require updating
527 update_required = match_option_group_options(client, module)
528
529 # Check if there are options to be added or removed
530 if update_required:
531 to_be_added, to_be_removed = compare_option_group(client, module)
532
533 if to_be_added or update_required:
534 changed |= create_option_group_options(client, module)
535
536 if to_be_removed:
537 changed |= remove_option_group_options(client, module, to_be_removed)
538
539 # If changed, get updated version of option group
540 if changed:
541 results = get_option_group(client, module)
542 else:
543 # No options were supplied. If options exist, remove them
544 current_option_group = get_option_group(client, module)
545
546 if current_option_group["options"] != []:
547 # Here we would call our remove options function
548 options_to_remove = []
549
550 for option in current_option_group["options"]:
551 options_to_remove.append(option["option_name"])
552
553 changed |= remove_option_group_options(client, module, options_to_remove)
554
555 # If changed, get updated version of option group
556 if changed:
557 results = get_option_group(client, module)
558 else:
559 changed = create_option_group(client, module)
560
561 if module.params.get("options"):
562 changed = create_option_group_options(client, module)
563
564 results = get_option_group(client, module)
565
566 return changed, results
567
568
569 def remove_option_group(client, module):
570 changed = False
571 params = dict()
572 params["OptionGroupName"] = module.params.get("option_group_name")
573
574 # Check if there is an existing options group
575 existing_option_group = get_option_group(client, module)
576
577 if existing_option_group:
578 if module.check_mode:
579 return True, {}
580
581 changed = True
582 try:
583 client.delete_option_group(aws_retry=True, **params)
584 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
585 module.fail_json_aws(e, msg="Unable to delete option group.")
586
587 return changed, {}
588
589
590 def update_tags(client, module, option_group):
591 if module.params.get("tags") is None:
592 return False
593
594 try:
595 existing_tags = client.list_tags_for_resource(aws_retry=True, ResourceName=option_group["option_group_arn"])[
596 "TagList"
597 ]
598 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
599 module.fail_json_aws(e, msg="Couldn't obtain option group tags.")
600
601 to_update, to_delete = compare_aws_tags(
602 boto3_tag_list_to_ansible_dict(existing_tags), module.params["tags"], module.params["purge_tags"]
603 )
604 changed = bool(to_update or to_delete)
605
606 if to_update:
607 try:
608 if module.check_mode:
609 return changed
610 client.add_tags_to_resource(
611 aws_retry=True,
612 ResourceName=option_group["option_group_arn"],
613 Tags=ansible_dict_to_boto3_tag_list(to_update),
614 )
615 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
616 module.fail_json_aws(e, msg="Couldn't add tags to option group.")
617 if to_delete:
618 try:
619 if module.check_mode:
620 return changed
621 client.remove_tags_from_resource(
622 aws_retry=True, ResourceName=option_group["option_group_arn"], TagKeys=to_delete
623 )
624 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
625 module.fail_json_aws(e, msg="Couldn't remove tags from option group.")
626
627 return changed
628
629
630 def main():
631 argument_spec = dict(
632 option_group_name=dict(required=True, type="str"),
633 engine_name=dict(type="str"),
634 major_engine_version=dict(type="str"),
635 option_group_description=dict(type="str"),
636 options=dict(required=False, type="list", elements="dict"),
637 apply_immediately=dict(type="bool", default=False),
638 state=dict(required=True, choices=["present", "absent"]),
639 tags=dict(required=False, type="dict", aliases=["resource_tags"]),
640 purge_tags=dict(type="bool", default=True),
641 wait=dict(type="bool", default=True),
642 )
643
644 module = AnsibleAWSModule(
645 argument_spec=argument_spec,
646 supports_check_mode=True,
647 required_if=[["state", "present", ["engine_name", "major_engine_version", "option_group_description"]]],
648 )
649
650 try:
651 client = module.client("rds", retry_decorator=AWSRetry.jittered_backoff())
652 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
653 module.fail_json_aws(e, msg="Failed to connect to AWS.")
654
655 state = module.params.get("state")
656
657 if state == "present":
658 changed, results = setup_option_group(client, module)
659 else:
660 changed, results = remove_option_group(client, module)
661
662 module.exit_json(changed=changed, **results)
663
664
665 if __name__ == "__main__":
666 main()