Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the 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 ---
9 module: rds_instance_param_group
10 version_added: 5.0.0
11 short_description: manage RDS parameter groups
12 description:
13 - Creates, modifies, and deletes RDS parameter groups.
14 - This module was originally added to C(community.aws) in release 1.0.0.
15 options:
16 state:
17 description:
18 - Specifies whether the group should be present or absent.
19 required: true
20 choices: [ 'present' , 'absent' ]
21 type: str
22 name:
23 description:
24 - Database parameter group identifier.
25 required: true
26 type: str
27 description:
28 description:
29 - Database parameter group description. Only set when a new group is added.
30 type: str
31 engine:
32 description:
33 - The type of database for this group.
34 - Please use M(amazon.aws.rds_engine_versions_info) to get list of all supported db engines and their respective versions.
35 - The DB parameter group family is immutable and can't be changed when updating a DB parameter group.
36 See U(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbparametergroup.html)
37 - Required for O(state=present).
38 type: str
39 immediate:
40 description:
41 - Whether to apply the changes immediately, or after the next reboot of any associated instances.
42 aliases:
43 - apply_immediately
44 type: bool
45 params:
46 description:
47 - Map of parameter names and values. Numeric values may be represented as K for kilo (1024), M for mega (1024^2), G for giga (1024^3),
48 or T for tera (1024^4), and these values will be expanded into the appropriate number before being set in the parameter group.
49 aliases: [parameters]
50 type: dict
51 author:
52 - "Scott Anderson (@tastychutney)"
53 - "Will Thames (@willthames)"
54 extends_documentation_fragment:
55 - amazon.aws.common.modules
56 - amazon.aws.region.modules
57 - amazon.aws.tags
58 - amazon.aws.boto3
59 """
60
61 EXAMPLES = r"""
62 - name: Add or change a parameter group, in this case setting auto_increment_increment to 42 * 1024
63 amazon.aws.rds_instance_param_group:
64 state: present
65 name: norwegian-blue
66 description: 'My Fancy Ex Parrot Group'
67 engine: 'mysql5.6'
68 params:
69 auto_increment_increment: "42K"
70 tags:
71 Environment: production
72 Application: parrot
73
74 - name: Remove a parameter group
75 amazon.aws.rds_instance_param_group:
76 state: absent
77 name: norwegian-blue
78 """
79
80 RETURN = r"""
81 db_parameter_group_name:
82 description: Name of DB parameter group.
83 type: str
84 returned: when O(state=present)
85 db_parameter_group_family:
86 description: DB parameter group family that this DB parameter group is compatible with.
87 type: str
88 returned: when O(state=present)
89 db_parameter_group_arn:
90 description: ARN of the DB parameter group.
91 type: str
92 returned: when O(state=present)
93 description:
94 description: description of the DB parameter group.
95 type: str
96 returned: when O(state=present)
97 errors:
98 description: List of errors from attempting to modify parameters that are not modifiable.
99 type: list
100 returned: when O(state=present)
101 tags:
102 description: A dictionary of tags.
103 type: dict
104 returned: when O(state=present)
105 """
106
107 from itertools import zip_longest
108
109 try:
110 import botocore
111 except ImportError:
112 pass # Handled by AnsibleAWSModule
113
114 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
115 from ansible.module_utils.parsing.convert_bool import BOOLEANS_TRUE
116
117 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
118 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
119 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
120 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
121 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
122 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
123
124 INT_MODIFIERS = {
125 "K": 1024,
126 "M": pow(1024, 2),
127 "G": pow(1024, 3),
128 "T": pow(1024, 4),
129 }
130
131
132 @AWSRetry.jittered_backoff()
133 def _describe_db_parameters(connection, **params):
134 try:
135 paginator = connection.get_paginator("describe_db_parameters")
136 return paginator.paginate(**params).build_full_result()
137 except is_boto3_error_code("DBParameterGroupNotFound"):
138 return None
139
140
141 def convert_parameter(param, value):
142 """
143 Allows setting parameters with 10M = 10* 1024 * 1024 and so on.
144 """
145 converted_value = value
146
147 if param["DataType"] == "integer":
148 if isinstance(value, str):
149 try:
150 for name, modifier in INT_MODIFIERS.items():
151 if value.endswith(name):
152 converted_value = int(value[:-1]) * modifier
153 except ValueError:
154 # may be based on a variable (ie. {foo*3/4}) so
155 # just pass it on through to the AWS SDK
156 pass
157 elif isinstance(value, bool):
158 converted_value = 1 if value else 0
159
160 elif param["DataType"] == "boolean":
161 if isinstance(value, str):
162 converted_value = value in BOOLEANS_TRUE
163 # convert True/False to 1/0
164 converted_value = 1 if converted_value else 0
165 return str(converted_value)
166
167
168 def update_parameters(module, connection):
169 groupname = module.params["name"]
170 desired = module.params["params"]
171 apply_method = "immediate" if module.params["immediate"] else "pending-reboot"
172 errors = []
173 modify_list = []
174 existing = {}
175 try:
176 _existing = _describe_db_parameters(connection, DBParameterGroupName=groupname)
177 if _existing:
178 existing = _existing["Parameters"]
179 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
180 module.fail_json_aws(e, msg="Failed to describe existing parameter groups")
181 lookup = dict((param["ParameterName"], param) for param in existing)
182 for param_key, param_value in desired.items():
183 if param_key not in lookup:
184 errors.append(
185 f"Parameter {param_key} is not an available parameter for the {module.params.get('engine')} engine"
186 )
187 else:
188 converted_value = convert_parameter(lookup[param_key], param_value)
189 # engine-default parameters do not have a ParameterValue, so we'll always override those.
190 if converted_value != lookup[param_key].get("ParameterValue"):
191 if lookup[param_key]["IsModifiable"]:
192 modify_list.append(
193 dict(ParameterValue=converted_value, ParameterName=param_key, ApplyMethod=apply_method)
194 )
195 else:
196 errors.append(f"Parameter {param_key} is not modifiable")
197
198 # modify_db_parameters takes at most 20 parameters
199 if modify_list and not module.check_mode:
200 for modify_slice in zip_longest(*[iter(modify_list)] * 20, fillvalue=None):
201 non_empty_slice = [item for item in modify_slice if item]
202 try:
203 connection.modify_db_parameter_group(
204 aws_retry=True, DBParameterGroupName=groupname, Parameters=non_empty_slice
205 )
206 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
207 module.fail_json_aws(e, msg="Couldn't update parameters")
208 return True, errors
209 return False, errors
210
211
212 def update_tags(module, connection, group, tags):
213 if tags is None:
214 return False
215 changed = False
216
217 existing_tags = connection.list_tags_for_resource(aws_retry=True, ResourceName=group["DBParameterGroupArn"])[
218 "TagList"
219 ]
220 to_update, to_delete = compare_aws_tags(
221 boto3_tag_list_to_ansible_dict(existing_tags), tags, module.params["purge_tags"]
222 )
223
224 if module.check_mode:
225 if not to_update and not to_delete:
226 return False
227 else:
228 return True
229
230 if to_update:
231 try:
232 connection.add_tags_to_resource(
233 aws_retry=True,
234 ResourceName=group["DBParameterGroupArn"],
235 Tags=ansible_dict_to_boto3_tag_list(to_update),
236 )
237 changed = True
238 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
239 module.fail_json_aws(e, msg="Couldn't add tags to parameter group")
240 if to_delete:
241 try:
242 connection.remove_tags_from_resource(
243 aws_retry=True, ResourceName=group["DBParameterGroupArn"], TagKeys=to_delete
244 )
245 changed = True
246 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
247 module.fail_json_aws(e, msg="Couldn't remove tags from parameter group")
248 return changed
249
250
251 def ensure_present(module, connection):
252 groupname = module.params["name"]
253 tags = module.params.get("tags")
254 changed = False
255 errors = []
256 try:
257 response = connection.describe_db_parameter_groups(aws_retry=True, DBParameterGroupName=groupname)
258 except is_boto3_error_code("DBParameterGroupNotFound"):
259 response = None
260 except botocore.exceptions.ClientError as e: # pylint: disable=duplicate-except
261 module.fail_json_aws(e, msg="Couldn't access parameter group information")
262 if not response:
263 params = dict(
264 DBParameterGroupName=groupname,
265 DBParameterGroupFamily=module.params["engine"],
266 Description=module.params["description"],
267 )
268 if tags:
269 params["Tags"] = ansible_dict_to_boto3_tag_list(tags)
270 if not module.check_mode:
271 try:
272 response = connection.create_db_parameter_group(aws_retry=True, **params)
273 changed = True
274 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
275 module.fail_json_aws(e, msg="Couldn't create parameter group")
276 else:
277 group = response["DBParameterGroups"][0]
278 db_parameter_group_family = group["DBParameterGroupFamily"]
279
280 if module.params.get("engine") != db_parameter_group_family:
281 module.warn("The DB parameter group family (engine) can't be changed when updating a DB parameter group.")
282
283 if tags:
284 changed = update_tags(module, connection, group, tags)
285
286 if module.params.get("params"):
287 params_changed, errors = update_parameters(module, connection)
288 changed = changed or params_changed
289
290 try:
291 response = connection.describe_db_parameter_groups(aws_retry=True, DBParameterGroupName=groupname)
292 group = camel_dict_to_snake_dict(response["DBParameterGroups"][0])
293 except is_boto3_error_code("DBParameterGroupNotFound"):
294 module.exit_json(changed=True, errors=errors)
295 except (
296 botocore.exceptions.ClientError,
297 botocore.exceptions.BotoCoreError,
298 ) as e: # pylint: disable=duplicate-except
299 module.fail_json_aws(e, msg="Couldn't obtain parameter group information")
300 try:
301 tags = connection.list_tags_for_resource(aws_retry=True, ResourceName=group["db_parameter_group_arn"])[
302 "TagList"
303 ]
304 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
305 module.fail_json_aws(e, msg="Couldn't obtain parameter group tags")
306 group["tags"] = boto3_tag_list_to_ansible_dict(tags)
307
308 module.exit_json(changed=changed, errors=errors, **group)
309
310
311 def ensure_absent(module, connection):
312 group = module.params["name"]
313 try:
314 response = connection.describe_db_parameter_groups(DBParameterGroupName=group)
315 except is_boto3_error_code("DBParameterGroupNotFound"):
316 module.exit_json(changed=False)
317 except botocore.exceptions.ClientError as e: # pylint: disable=duplicate-except
318 module.fail_json_aws(e, msg="Couldn't access parameter group information")
319
320 if response and module.check_mode:
321 module.exit_json(changed=True)
322
323 try:
324 response = connection.delete_db_parameter_group(aws_retry=True, DBParameterGroupName=group)
325 module.exit_json(changed=True)
326 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
327 module.fail_json_aws(e, msg="Couldn't delete parameter group")
328
329
330 def main():
331 argument_spec = dict(
332 state=dict(required=True, choices=["present", "absent"]),
333 name=dict(required=True),
334 engine=dict(),
335 description=dict(),
336 params=dict(aliases=["parameters"], type="dict"),
337 immediate=dict(type="bool", aliases=["apply_immediately"]),
338 tags=dict(type="dict", aliases=["resource_tags"]),
339 purge_tags=dict(type="bool", default=True),
340 )
341 module = AnsibleAWSModule(
342 argument_spec=argument_spec,
343 required_if=[["state", "present", ["description", "engine"]]],
344 supports_check_mode=True,
345 )
346
347 try:
348 conn = module.client("rds", retry_decorator=AWSRetry.jittered_backoff())
349 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
350 module.fail_json_aws(e, msg="Failed to connect to AWS")
351
352 state = module.params.get("state")
353 if state == "present":
354 ensure_present(module, conn)
355 if state == "absent":
356 ensure_absent(module, conn)
357
358
359 if __name__ == "__main__":
360 main()