Debian Codegraph @

ansible_collections/community/aws/plugins/modules/elasticache.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2017 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
10 version_added: 1.0.0
11 short_description: Manage cache clusters in Amazon ElastiCache
12 description:
13 - Manage cache clusters in Amazon ElastiCache.
14 - Returns information about the specified cache cluster.
15 author:
16 - "Jim Dalton (@jsdalton)"
17 options:
18 state:
19 description:
20 - C(absent) or C(present) are idempotent actions that will create or destroy a cache cluster as needed.
21 - C(rebooted) will reboot the cluster, resulting in a momentary outage.
22 choices: ['present', 'absent', 'rebooted']
23 required: true
24 type: str
25 name:
26 description:
27 - The cache cluster identifier.
28 required: true
29 type: str
30 engine:
31 description:
32 - Name of the cache engine to be used.
33 - Supported values are C(redis) and C(memcached).
34 default: memcached
35 type: str
36 cache_engine_version:
37 description:
38 - The version number of the cache engine.
39 type: str
40 default: ''
41 node_type:
42 description:
43 - The compute and memory capacity of the nodes in the cache cluster.
44 default: cache.t2.small
45 type: str
46 num_nodes:
47 description:
48 - The initial number of cache nodes that the cache cluster will have.
49 - Required when I(state=present).
50 type: int
51 default: 1
52 cache_port:
53 description:
54 - The port number on which each of the cache nodes will accept
55 connections.
56 type: int
57 cache_parameter_group:
58 description:
59 - The name of the cache parameter group to associate with this cache cluster. If this argument is omitted, the default cache parameter group
60 for the specified engine will be used.
61 aliases: [ 'parameter_group' ]
62 type: str
63 default: ''
64 cache_subnet_group:
65 description:
66 - The subnet group name to associate with. Only use if inside a VPC.
67 - Required if inside a VPC.
68 type: str
69 default: ''
70 security_group_ids:
71 description:
72 - A list of VPC security group IDs to associate with this cache cluster. Only use if inside a VPC.
73 type: list
74 elements: str
75 default: []
76 cache_security_groups:
77 description:
78 - A list of cache security group names to associate with this cache cluster.
79 - Don't use if your Cache is inside a VPC. In that case use I(security_group_ids) instead!
80 type: list
81 elements: str
82 default: []
83 zone:
84 description:
85 - The EC2 Availability Zone in which the cache cluster will be created.
86 type: str
87 wait:
88 description:
89 - Wait for cache cluster result before returning.
90 type: bool
91 default: true
92 hard_modify:
93 description:
94 - Whether to destroy and recreate an existing cache cluster if necessary in order to modify its state.
95 - Defaults to C(false).
96 type: bool
97 extends_documentation_fragment:
98 - amazon.aws.common.modules
99 - amazon.aws.region.modules
100 - amazon.aws.boto3
101 """
102
103 RETURN = r""" # """
104
105 EXAMPLES = r"""
106 # Note: These examples do not set authentication details, see the AWS Guide for details.
107
108 - name: Basic example
109 community.aws.elasticache:
110 name: "test-please-delete"
111 state: present
112 engine: memcached
113 cache_engine_version: 1.4.14
114 node_type: cache.m3.small
115 num_nodes: 1
116 cache_port: 11211
117 cache_security_groups:
118 - default
119 zone: us-east-1d
120
121
122 - name: Ensure cache cluster is gone
123 community.aws.elasticache:
124 name: "test-please-delete"
125 state: absent
126
127 - name: Reboot cache cluster
128 community.aws.elasticache:
129 name: "test-please-delete"
130 state: rebooted
131 """
132
133 from time import sleep
134
135 try:
136 import botocore
137 except ImportError:
138 pass # Handled by AnsibleAWSModule
139
140 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
141
142 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
143
144
145 class ElastiCacheManager:
146 """Handles elasticache creation and destruction"""
147
148 EXIST_STATUSES = ["available", "creating", "rebooting", "modifying"]
149
150 def __init__(
151 self,
152 module,
153 name,
154 engine,
155 cache_engine_version,
156 node_type,
157 num_nodes,
158 cache_port,
159 cache_parameter_group,
160 cache_subnet_group,
161 cache_security_groups,
162 security_group_ids,
163 zone,
164 wait,
165 hard_modify,
166 ):
167 self.module = module
168 self.name = name
169 self.engine = engine.lower()
170 self.cache_engine_version = cache_engine_version
171 self.node_type = node_type
172 self.num_nodes = num_nodes
173 self.cache_port = cache_port
174 self.cache_parameter_group = cache_parameter_group
175 self.cache_subnet_group = cache_subnet_group
176 self.cache_security_groups = cache_security_groups
177 self.security_group_ids = security_group_ids
178 self.zone = zone
179 self.wait = wait
180 self.hard_modify = hard_modify
181
182 self.changed = False
183 self.data = None
184 self.status = "gone"
185 self.conn = self._get_elasticache_connection()
186 self._refresh_data()
187
188 def ensure_present(self):
189 """Ensure cache cluster exists or create it if not"""
190 if self.exists():
191 self.sync()
192 else:
193 self.create()
194
195 def ensure_absent(self):
196 """Ensure cache cluster is gone or delete it if not"""
197 self.delete()
198
199 def ensure_rebooted(self):
200 """Ensure cache cluster is gone or delete it if not"""
201 self.reboot()
202
203 def exists(self):
204 """Check if cache cluster exists"""
205 return self.status in self.EXIST_STATUSES
206
207 def create(self):
208 """Create an ElastiCache cluster"""
209 if self.status == "available":
210 return
211 if self.status in ["creating", "rebooting", "modifying"]:
212 if self.wait:
213 self._wait_for_status("available")
214 return
215 if self.status == "deleting":
216 if self.wait:
217 self._wait_for_status("gone")
218 else:
219 self.module.fail_json(msg=f"'{self.name}' is currently deleting. Cannot create.")
220
221 kwargs = dict(
222 CacheClusterId=self.name,
223 NumCacheNodes=self.num_nodes,
224 CacheNodeType=self.node_type,
225 Engine=self.engine,
226 EngineVersion=self.cache_engine_version,
227 CacheSecurityGroupNames=self.cache_security_groups,
228 SecurityGroupIds=self.security_group_ids,
229 CacheParameterGroupName=self.cache_parameter_group,
230 CacheSubnetGroupName=self.cache_subnet_group,
231 )
232 if self.cache_port is not None:
233 kwargs["Port"] = self.cache_port
234 if self.zone is not None:
235 kwargs["PreferredAvailabilityZone"] = self.zone
236
237 try:
238 self.conn.create_cache_cluster(**kwargs)
239
240 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
241 self.module.fail_json_aws(e, msg="Failed to create cache cluster")
242
243 self._refresh_data()
244
245 self.changed = True
246 if self.wait:
247 self._wait_for_status("available")
248 return True
249
250 def delete(self):
251 """Destroy an ElastiCache cluster"""
252 if self.status == "gone":
253 return
254 if self.status == "deleting":
255 if self.wait:
256 self._wait_for_status("gone")
257 return
258 if self.status in ["creating", "rebooting", "modifying"]:
259 if self.wait:
260 self._wait_for_status("available")
261 else:
262 self.module.fail_json(msg=f"'{self.name}' is currently {self.status}. Cannot delete.")
263
264 try:
265 response = self.conn.delete_cache_cluster(CacheClusterId=self.name)
266 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
267 self.module.fail_json_aws(e, msg="Failed to delete cache cluster")
268
269 cache_cluster_data = response["CacheCluster"]
270 self._refresh_data(cache_cluster_data)
271
272 self.changed = True
273 if self.wait:
274 self._wait_for_status("gone")
275
276 def sync(self):
277 """Sync settings to cluster if required"""
278 if not self.exists():
279 self.module.fail_json(msg=f"'{self.name}' is {self.status}. Cannot sync.")
280
281 if self.status in ["creating", "rebooting", "modifying"]:
282 if self.wait:
283 self._wait_for_status("available")
284 else:
285 # Cluster can only be synced if available. If we can't wait
286 # for this, then just be done.
287 return
288
289 if self._requires_destroy_and_create():
290 if not self.hard_modify:
291 self.module.fail_json(
292 msg=f"'{self.name}' requires destructive modification. 'hard_modify' must be set to true to proceed."
293 )
294 if not self.wait:
295 self.module.fail_json(
296 msg=f"'{self.name}' requires destructive modification. 'wait' must be set to true to proceed."
297 )
298 self.delete()
299 self.create()
300 return
301
302 if self._requires_modification():
303 self.modify()
304
305 def modify(self):
306 """Modify the cache cluster. Note it's only possible to modify a few select options."""
307 nodes_to_remove = self._get_nodes_to_remove()
308 try:
309 self.conn.modify_cache_cluster(
310 CacheClusterId=self.name,
311 NumCacheNodes=self.num_nodes,
312 CacheNodeIdsToRemove=nodes_to_remove,
313 CacheSecurityGroupNames=self.cache_security_groups,
314 CacheParameterGroupName=self.cache_parameter_group,
315 SecurityGroupIds=self.security_group_ids,
316 ApplyImmediately=True,
317 EngineVersion=self.cache_engine_version,
318 )
319 except botocore.exceptions.ClientError as e:
320 self.module.fail_json_aws(e, msg="Failed to modify cache cluster")
321
322 self._refresh_data()
323
324 self.changed = True
325 if self.wait:
326 self._wait_for_status("available")
327
328 def reboot(self):
329 """Reboot the cache cluster"""
330 if not self.exists():
331 self.module.fail_json(msg=f"'{self.name}' is {self.status}. Cannot reboot.")
332 if self.status == "rebooting":
333 return
334 if self.status in ["creating", "modifying"]:
335 if self.wait:
336 self._wait_for_status("available")
337 else:
338 self.module.fail_json(msg=f"'{self.name}' is currently {self.status}. Cannot reboot.")
339
340 # Collect ALL nodes for reboot
341 cache_node_ids = [cn["CacheNodeId"] for cn in self.data["CacheNodes"]]
342 try:
343 self.conn.reboot_cache_cluster(CacheClusterId=self.name, CacheNodeIdsToReboot=cache_node_ids)
344 except botocore.exceptions.ClientError as e:
345 self.module.fail_json_aws(e, msg="Failed to reboot cache cluster")
346
347 self._refresh_data()
348
349 self.changed = True
350 if self.wait:
351 self._wait_for_status("available")
352
353 def get_info(self):
354 """Return basic info about the cache cluster"""
355 info = {"name": self.name, "status": self.status}
356 if self.data:
357 info["data"] = self.data
358 return info
359
360 def _wait_for_status(self, awaited_status):
361 """Wait for status to change from present status to awaited_status"""
362 status_map = {"creating": "available", "rebooting": "available", "modifying": "available", "deleting": "gone"}
363 if self.status == awaited_status:
364 # No need to wait, we're already done
365 return
366 if status_map[self.status] != awaited_status:
367 self.module.fail_json(
368 msg=f"Invalid awaited status. '{self.status}' cannot transition to '{awaited_status}'"
369 )
370
371 if awaited_status not in set(status_map.values()):
372 self.module.fail_json(msg=f"'{awaited_status}' is not a valid awaited status.")
373
374 while True:
375 sleep(1)
376 self._refresh_data()
377 if self.status == awaited_status:
378 break
379
380 def _requires_modification(self):
381 """Check if cluster requires (nondestructive) modification"""
382 # Check modifiable data attributes
383 modifiable_data = {"NumCacheNodes": self.num_nodes, "EngineVersion": self.cache_engine_version}
384 for key, value in modifiable_data.items():
385 if value is not None and value and self.data[key] != value:
386 return True
387
388 # Check cache security groups
389 cache_security_groups = []
390 for sg in self.data["CacheSecurityGroups"]:
391 cache_security_groups.append(sg["CacheSecurityGroupName"])
392 if set(cache_security_groups) != set(self.cache_security_groups):
393 return True
394
395 # check vpc security groups
396 if self.security_group_ids:
397 vpc_security_groups = []
398 security_groups = self.data.get("SecurityGroups", [])
399 for sg in security_groups:
400 vpc_security_groups.append(sg["SecurityGroupId"])
401 if set(vpc_security_groups) != set(self.security_group_ids):
402 return True
403
404 return False
405
406 def _requires_destroy_and_create(self):
407 """
408 Check whether a destroy and create is required to synchronize cluster.
409 """
410 unmodifiable_data = {
411 "node_type": self.data["CacheNodeType"],
412 "engine": self.data["Engine"],
413 "cache_port": self._get_port(),
414 }
415 # Only check for modifications if zone is specified
416 if self.zone is not None:
417 unmodifiable_data["zone"] = self.data["PreferredAvailabilityZone"]
418 for key, value in unmodifiable_data.items():
419 if getattr(self, key) is not None and getattr(self, key) != value:
420 return True
421 return False
422
423 def _get_elasticache_connection(self):
424 """Get an elasticache connection"""
425 try:
426 return self.module.client("elasticache")
427 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
428 self.module.fail_json_aws(e, msg="Failed to connect to AWS")
429
430 def _get_port(self):
431 """Get the port. Where this information is retrieved from is engine dependent."""
432 if self.data["Engine"] == "memcached":
433 return self.data["ConfigurationEndpoint"]["Port"]
434 elif self.data["Engine"] == "redis":
435 # Redis only supports a single node (presently) so just use
436 # the first and only
437 return self.data["CacheNodes"][0]["Endpoint"]["Port"]
438
439 def _refresh_data(self, cache_cluster_data=None):
440 """Refresh data about this cache cluster"""
441
442 if cache_cluster_data is None:
443 try:
444 response = self.conn.describe_cache_clusters(CacheClusterId=self.name, ShowCacheNodeInfo=True)
445 except is_boto3_error_code("CacheClusterNotFound"):
446 self.data = None
447 self.status = "gone"
448 return
449 except botocore.exceptions.ClientError as e: # pylint: disable=duplicate-except
450 self.module.fail_json_aws(e, msg="Failed to describe cache clusters")
451 cache_cluster_data = response["CacheClusters"][0]
452 self.data = cache_cluster_data
453 self.status = self.data["CacheClusterStatus"]
454
455 # The documentation for elasticache lies -- status on rebooting is set
456 # to 'rebooting cache cluster nodes' instead of 'rebooting'. Fix it
457 # here to make status checks etc. more sane.
458 if self.status == "rebooting cache cluster nodes":
459 self.status = "rebooting"
460
461 def _get_nodes_to_remove(self):
462 """If there are nodes to remove, it figures out which need to be removed"""
463 num_nodes_to_remove = self.data["NumCacheNodes"] - self.num_nodes
464 if num_nodes_to_remove <= 0:
465 return []
466
467 if not self.hard_modify:
468 self.module.fail_json(
469 msg=f"'{self.name}' requires removal of cache nodes. 'hard_modify' must be set to true to proceed."
470 )
471
472 cache_node_ids = [cn["CacheNodeId"] for cn in self.data["CacheNodes"]]
473 return cache_node_ids[-num_nodes_to_remove:]
474
475
476 def main():
477 """elasticache ansible module"""
478 argument_spec = dict(
479 state=dict(required=True, choices=["present", "absent", "rebooted"]),
480 name=dict(required=True),
481 engine=dict(default="memcached"),
482 cache_engine_version=dict(default=""),
483 node_type=dict(default="cache.t2.small"),
484 num_nodes=dict(default=1, type="int"),
485 # alias for compat with the original PR 1950
486 cache_parameter_group=dict(default="", aliases=["parameter_group"]),
487 cache_port=dict(type="int"),
488 cache_subnet_group=dict(default=""),
489 cache_security_groups=dict(default=[], type="list", elements="str"),
490 security_group_ids=dict(default=[], type="list", elements="str"),
491 zone=dict(),
492 wait=dict(default=True, type="bool"),
493 hard_modify=dict(type="bool"),
494 )
495
496 module = AnsibleAWSModule(
497 argument_spec=argument_spec,
498 )
499
500 name = module.params["name"]
501 state = module.params["state"]
502 engine = module.params["engine"]
503 cache_engine_version = module.params["cache_engine_version"]
504 node_type = module.params["node_type"]
505 num_nodes = module.params["num_nodes"]
506 cache_port = module.params["cache_port"]
507 cache_subnet_group = module.params["cache_subnet_group"]
508 cache_security_groups = module.params["cache_security_groups"]
509 security_group_ids = module.params["security_group_ids"]
510 zone = module.params["zone"]
511 wait = module.params["wait"]
512 hard_modify = module.params["hard_modify"]
513 cache_parameter_group = module.params["cache_parameter_group"]
514
515 if cache_subnet_group and cache_security_groups:
516 module.fail_json(msg="Can't specify both cache_subnet_group and cache_security_groups")
517
518 if state == "present" and not num_nodes:
519 module.fail_json(msg="'num_nodes' is a required parameter. Please specify num_nodes > 0")
520
521 elasticache_manager = ElastiCacheManager(
522 module,
523 name,
524 engine,
525 cache_engine_version,
526 node_type,
527 num_nodes,
528 cache_port,
529 cache_parameter_group,
530 cache_subnet_group,
531 cache_security_groups,
532 security_group_ids,
533 zone,
534 wait,
535 hard_modify,
536 )
537
538 if state == "present":
539 elasticache_manager.ensure_present()
540 elif state == "absent":
541 elasticache_manager.ensure_absent()
542 elif state == "rebooted":
543 elasticache_manager.ensure_rebooted()
544
545 facts_result = dict(changed=elasticache_manager.changed, elasticache=elasticache_manager.get_info())
546
547 module.exit_json(**facts_result)
548
549
550 if __name__ == "__main__":
551 main()