Debian Codegraph @

ansible_collections/community/aws/plugins/modules/elasticache_parameter_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: elasticache_parameter_group
10 version_added: 1.0.0
11 short_description: Manage cache parameter groups in Amazon ElastiCache.
12 description:
13 - Manage cache security groups in Amazon ElastiCache.
14 - Returns information about the specified cache cluster.
15 author:
16 - "Sloane Hertel (@s-hertel)"
17
18 options:
19 group_family:
20 description:
21 - The name of the cache parameter group family that the cache parameter group can be used with.
22 Required when creating a cache parameter group.
23 choices: ['memcached1.4', 'memcached1.5', 'redis2.6', 'redis2.8', 'redis3.2', 'redis4.0', 'redis5.0', 'redis6.x']
24 type: str
25 name:
26 description:
27 - A user-specified name for the cache parameter group.
28 required: true
29 type: str
30 description:
31 description:
32 - A user-specified description for the cache parameter group.
33 type: str
34 default: ''
35 state:
36 description:
37 - Idempotent actions that will create/modify, destroy, or reset a cache parameter group as needed.
38 choices: ['present', 'absent', 'reset']
39 required: true
40 type: str
41 values:
42 description:
43 - A user-specified dictionary of parameters to reset or modify for the cache parameter group.
44 type: dict
45
46 extends_documentation_fragment:
47 - amazon.aws.common.modules
48 - amazon.aws.region.modules
49 - amazon.aws.boto3
50 """
51
52 EXAMPLES = r"""
53 # Note: These examples do not set authentication details, see the AWS Guide for details.
54 - name: Create, modify and delete a parameter group
55 hosts: localhost
56 connection: local
57 tasks:
58 - name: 'Create a test parameter group'
59 community.aws.elasticache_parameter_group:
60 name: 'test-param-group'
61 group_family: 'redis3.2'
62 description: 'This is a cache parameter group'
63 state: 'present'
64 - name: 'Modify a test parameter group'
65 community.aws.elasticache_parameter_group:
66 name: 'test-param-group'
67 values:
68 activerehashing: true
69 client-output-buffer-limit-normal-hard-limit: 4
70 state: 'present'
71 - name: 'Reset all modifiable parameters for the test parameter group'
72 community.aws.elasticache_parameter_group:
73 name: 'test-param-group'
74 state: reset
75 - name: 'Delete a test parameter group'
76 community.aws.elasticache_parameter_group:
77 name: 'test-param-group'
78 state: 'absent'
79 """
80
81 RETURN = r"""
82 elasticache:
83 description: cache parameter group information and response metadata
84 returned: always
85 type: dict
86 sample:
87 cache_parameter_group:
88 cache_parameter_group_family: redis3.2
89 cache_parameter_group_name: test-please-delete
90 description: "initial description"
91 response_metadata:
92 http_headers:
93 content-length: "562"
94 content-type: text/xml
95 date: "Mon, 06 Feb 2017 22:14:08 GMT"
96 x-amzn-requestid: 947291f9-ecb9-11e6-85bd-3baa4eca2cc1
97 http_status_code: 200
98 request_id: 947291f9-ecb9-11e6-85bd-3baa4eca2cc1
99 retry_attempts: 0
100 changed:
101 description: if the cache parameter group has changed
102 returned: always
103 type: bool
104 sample:
105 changed: true
106 """
107
108 try:
109 import botocore
110 except ImportError:
111 pass # Handled by AnsibleAWSModule
112
113 from ansible.module_utils._text import to_text
114 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
115
116 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
117
118
119 def create(module, conn, name, group_family, description):
120 """Create ElastiCache parameter group."""
121 try:
122 response = conn.create_cache_parameter_group(
123 CacheParameterGroupName=name, CacheParameterGroupFamily=group_family, Description=description
124 )
125 changed = True
126 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
127 module.fail_json_aws(e, msg="Unable to create cache parameter group.")
128 return response, changed
129
130
131 def delete(module, conn, name):
132 """Delete ElastiCache parameter group."""
133 try:
134 conn.delete_cache_parameter_group(CacheParameterGroupName=name)
135 response = {}
136 changed = True
137 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
138 module.fail_json_aws(e, msg="Unable to delete cache parameter group.")
139 return response, changed
140
141
142 def make_current_modifiable_param_dict(module, conn, name):
143 """Gets the current state of the cache parameter group and creates a dict with the format: {ParameterName: [Allowed_Values, DataType, ParameterValue]}"""
144 current_info = get_info(conn, name)
145 if current_info is False:
146 module.fail_json(msg=f"Could not connect to the cache parameter group {name}.")
147
148 parameters = current_info["Parameters"]
149 modifiable_params = {}
150
151 for param in parameters:
152 if param["IsModifiable"]:
153 modifiable_params[param["ParameterName"]] = [param.get("AllowedValues")]
154 modifiable_params[param["ParameterName"]].append(param["DataType"])
155 modifiable_params[param["ParameterName"]].append(param.get("ParameterValue"))
156 return modifiable_params
157
158
159 def check_valid_modification(module, values, modifiable_params):
160 """Check if the parameters and values in values are valid."""
161 changed_with_update = False
162
163 for parameter in values:
164 new_value = values[parameter]
165
166 # check valid modifiable parameters
167 if parameter not in modifiable_params:
168 module.fail_json(
169 msg=f"{parameter} is not a modifiable parameter. Valid parameters to modify are: {modifiable_params.keys()}."
170 )
171
172 # check allowed datatype for modified parameters
173 str_to_type = {"integer": int, "string": str}
174 expected_type = str_to_type[modifiable_params[parameter][1]]
175 if not isinstance(new_value, expected_type):
176 if expected_type is str:
177 if isinstance(new_value, bool):
178 values[parameter] = "yes" if new_value else "no"
179 else:
180 values[parameter] = to_text(new_value)
181 elif expected_type is int:
182 if isinstance(new_value, bool):
183 values[parameter] = 1 if new_value else 0
184 else:
185 module.fail_json(
186 msg=(
187 f"{new_value} (type {type(new_value)}) is not an allowed value for the parameter"
188 f" {parameter}. Expected a type {modifiable_params[parameter][1]}."
189 )
190 )
191 else:
192 module.fail_json(
193 msg=(
194 f"{new_value} (type {type(new_value)}) is not an allowed value for the parameter {parameter}."
195 f" Expected a type {modifiable_params[parameter][1]}."
196 )
197 )
198
199 # check allowed values for modifiable parameters
200 choices = modifiable_params[parameter][0]
201 if choices:
202 if not (to_text(new_value) in choices or isinstance(new_value, int)):
203 module.fail_json(
204 msg=f"{new_value} is not an allowed value for the parameter {parameter}. Valid parameters are: {choices}."
205 )
206
207 # check if a new value is different from current value
208 if to_text(values[parameter]) != modifiable_params[parameter][2]:
209 changed_with_update = True
210
211 return changed_with_update, values
212
213
214 def check_changed_parameter_values(values, old_parameters, new_parameters):
215 """Checking if the new values are different than the old values."""
216 changed_with_update = False
217
218 # if the user specified parameters to reset, only check those for change
219 if values:
220 for parameter in values:
221 if old_parameters[parameter] != new_parameters[parameter]:
222 changed_with_update = True
223 break
224 # otherwise check all to find a change
225 else:
226 for parameter in old_parameters:
227 if old_parameters[parameter] != new_parameters[parameter]:
228 changed_with_update = True
229 break
230
231 return changed_with_update
232
233
234 def modify(module, conn, name, values):
235 """Modify ElastiCache parameter group to reflect the new information if it differs from the current."""
236 # compares current group parameters with the parameters we've specified to to a value to see if this will change the group
237 format_parameters = []
238 for key in values:
239 value = to_text(values[key])
240 format_parameters.append({"ParameterName": key, "ParameterValue": value})
241 try:
242 response = conn.modify_cache_parameter_group(
243 CacheParameterGroupName=name, ParameterNameValues=format_parameters
244 )
245 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
246 module.fail_json_aws(e, msg="Unable to modify cache parameter group.")
247 return response
248
249
250 def reset(module, conn, name, values):
251 """Reset ElastiCache parameter group if the current information is different from the new information."""
252 # used to compare with the reset parameters' dict to see if there have been changes
253 old_parameters_dict = make_current_modifiable_param_dict(module, conn, name)
254
255 format_parameters = []
256
257 # determine whether to reset all or specific parameters
258 if values:
259 all_parameters = False
260 format_parameters = []
261 for key in values:
262 value = to_text(values[key])
263 format_parameters.append({"ParameterName": key, "ParameterValue": value})
264 else:
265 all_parameters = True
266
267 try:
268 response = conn.reset_cache_parameter_group(
269 CacheParameterGroupName=name, ParameterNameValues=format_parameters, ResetAllParameters=all_parameters
270 )
271 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
272 module.fail_json_aws(e, msg="Unable to reset cache parameter group.")
273
274 # determine changed
275 new_parameters_dict = make_current_modifiable_param_dict(module, conn, name)
276 changed = check_changed_parameter_values(values, old_parameters_dict, new_parameters_dict)
277
278 return response, changed
279
280
281 def get_info(conn, name):
282 """Gets info about the ElastiCache parameter group. Returns false if it doesn't exist or we don't have access."""
283 try:
284 data = conn.describe_cache_parameters(CacheParameterGroupName=name)
285 return data
286 except botocore.exceptions.ClientError:
287 return False
288
289
290 def main():
291 argument_spec = dict(
292 group_family=dict(
293 type="str",
294 choices=[
295 "memcached1.4",
296 "memcached1.5",
297 "redis2.6",
298 "redis2.8",
299 "redis3.2",
300 "redis4.0",
301 "redis5.0",
302 "redis6.x",
303 ],
304 ),
305 name=dict(required=True, type="str"),
306 description=dict(default="", type="str"),
307 state=dict(required=True, choices=["present", "absent", "reset"]),
308 values=dict(type="dict"),
309 )
310 module = AnsibleAWSModule(argument_spec=argument_spec)
311
312 parameter_group_family = module.params.get("group_family")
313 parameter_group_name = module.params.get("name")
314 group_description = module.params.get("description")
315 state = module.params.get("state")
316 values = module.params.get("values")
317
318 try:
319 connection = module.client("elasticache")
320 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
321 module.fail_json_aws(e, msg="Failed to connect to AWS")
322
323 exists = get_info(connection, parameter_group_name)
324
325 # check that the needed requirements are available
326 if state == "present" and not (exists or parameter_group_family):
327 module.fail_json(msg="Creating a group requires a family group.")
328 elif state == "reset" and not exists:
329 module.fail_json(
330 msg=f"No group {parameter_group_name} to reset. Please create the group before using the state 'reset'."
331 )
332
333 # Taking action
334 changed = False
335 if state == "present":
336 if exists:
337 # confirm that the group exists without any actions
338 if not values:
339 response = exists
340 changed = False
341 # modify existing group
342 else:
343 modifiable_params = make_current_modifiable_param_dict(module, connection, parameter_group_name)
344 changed, values = check_valid_modification(module, values, modifiable_params)
345 response = modify(module, connection, parameter_group_name, values)
346 # create group
347 else:
348 response, changed = create(
349 module, connection, parameter_group_name, parameter_group_family, group_description
350 )
351 if values:
352 modifiable_params = make_current_modifiable_param_dict(module, connection, parameter_group_name)
353 changed, values = check_valid_modification(module, values, modifiable_params)
354 response = modify(module, connection, parameter_group_name, values)
355 elif state == "absent":
356 if exists:
357 # delete group
358 response, changed = delete(module, connection, parameter_group_name)
359 else:
360 response = {}
361 changed = False
362 elif state == "reset":
363 response, changed = reset(module, connection, parameter_group_name, values)
364
365 facts_result = dict(changed=changed, elasticache=camel_dict_to_snake_dict(response))
366
367 module.exit_json(**facts_result)
368
369
370 if __name__ == "__main__":
371 main()