Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/cloudwatchevent_rule.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 ---
9 module: cloudwatchevent_rule
10 version_added: 5.0.0
11 short_description: Manage CloudWatch Event rules and targets
12 description:
13 - This module creates and manages CloudWatch event rules and targets.
14 - This module was originally added to C(community.aws) in release 1.0.0.
15 extends_documentation_fragment:
16 - amazon.aws.common.modules
17 - amazon.aws.region.modules
18 - amazon.aws.boto3
19
20 author:
21 - "Jim Dalton (@jsdalton) <[email protected]>"
22 notes:
23 - A rule must contain at least an O(event_pattern) or O(schedule_expression). A
24 rule can have both an O(event_pattern) and a O(schedule_expression), in which
25 case the rule will trigger on matching events as well as on a schedule.
26 - When specifying targets, O(targets.input), O(targets.input_path),
27 O(targets.input_transformer.input_paths_map) and O(targets.input_transformer.input_template)
28 are mutually-exclusive and optional parameters.
29 options:
30 name:
31 description:
32 - The name of the rule you are creating, updating or deleting. No spaces
33 or special characters allowed (i.e. must match C([\.\-_A-Za-z0-9]+)).
34 required: true
35 type: str
36 schedule_expression:
37 description:
38 - A cron or rate expression that defines the schedule the rule will
39 trigger on. For example, C(cron(0 20 * * ? *)), C(rate(5 minutes)).
40 required: false
41 type: str
42 event_pattern:
43 description:
44 - A string pattern that is used to match against incoming events to determine if the rule
45 should be triggered.
46 required: false
47 type: json
48 state:
49 description:
50 - Whether the rule is present (and enabled), disabled, or absent.
51 choices: ["present", "disabled", "absent"]
52 default: present
53 required: false
54 type: str
55 description:
56 description:
57 - A description of the rule.
58 required: false
59 type: str
60 role_arn:
61 description:
62 - The Amazon Resource Name (ARN) of the IAM role associated with the rule.
63 required: false
64 type: str
65 targets:
66 type: list
67 elements: dict
68 default: []
69 description:
70 - A list of targets to add to or update for the rule.
71 suboptions:
72 id:
73 type: str
74 required: true
75 description: The unique target assignment ID.
76 arn:
77 type: str
78 required: true
79 description: The ARN associated with the target.
80 role_arn:
81 type: str
82 description: The ARN of the IAM role to be used for this target when the rule is triggered.
83 input:
84 type: json
85 description:
86 - A JSON object that will override the event data passed to the target.
87 - If neither O(targets.input) nor O(targets.input_path) nor O(targets.input_transformer)
88 is specified, then the entire event is passed to the target in JSON form.
89 input_path:
90 type: str
91 description:
92 - A JSONPath string (e.g. V($.detail)) that specifies the part of the event data to be
93 passed to the target.
94 - If neither O(targets.input) nor O(targets.input_path) nor O(targets.input_transformer)
95 is specified, then the entire event is passed to the target in JSON form.
96 input_transformer:
97 type: dict
98 description:
99 - Settings to support providing custom input to a target based on certain event data.
100 version_added: 4.1.0
101 version_added_collection: community.aws
102 suboptions:
103 input_paths_map:
104 type: dict
105 description:
106 - A dict that specifies the transformation of the event data to
107 custom input parameters.
108 input_template:
109 type: json
110 description:
111 - A string that templates the values input_paths_map extracted from the event data.
112 It is used to produce the output you want to be sent to the target.
113 ecs_parameters:
114 type: dict
115 description:
116 - Contains the ECS task definition and task count to be used, if the event target is an ECS task.
117 suboptions:
118 task_definition_arn:
119 type: str
120 description: The full ARN of the task definition.
121 required: true
122 task_count:
123 type: int
124 description: The number of tasks to create based on task definition.
125 required: false
126 """
127
128 EXAMPLES = r"""
129 - amazon.aws.cloudwatchevent_rule:
130 name: MyCronTask
131 schedule_expression: "cron(0 20 * * ? *)"
132 description: Run my scheduled task
133 targets:
134 - id: MyTargetId
135 arn: arn:aws:lambda:us-east-1:123456789012:function:MyFunction
136
137 - amazon.aws.cloudwatchevent_rule:
138 name: MyDisabledCronTask
139 schedule_expression: "rate(5 minutes)"
140 description: Run my disabled scheduled task
141 state: disabled
142 targets:
143 - id: MyOtherTargetId
144 arn: arn:aws:lambda:us-east-1:123456789012:function:MyFunction
145 input: '{"foo": "bar"}'
146
147 - amazon.aws.cloudwatchevent_rule:
148 name: MyInstanceLaunchEvent
149 description: "Rule for EC2 instance launch"
150 state: present
151 event_pattern: '{"source":["aws.ec2"],"detail-type":["EC2 Instance State-change Notification"],"detail":{"state":["pending"]}}'
152 targets:
153 - id: MyTargetSnsTopic
154 arn: arn:aws:sns:us-east-1:123456789012:MySNSTopic
155 input_transformer:
156 input_paths_map:
157 instance: "$.detail.instance-id"
158 state: "$.detail.state"
159 input_template: "<instance> is in state <state>"
160
161 - amazon.aws.cloudwatchevent_rule:
162 name: MyCronTask
163 state: absent
164 """
165
166 RETURN = r"""
167 rule:
168 description: CloudWatch Event rule data.
169 returned: success
170 type: dict
171 contains:
172 name:
173 description:
174 - The name of the rule you are creating, updating or deleting.
175 returned: success
176 type: str
177 sample: "MyCronTask"
178 schedule_expression:
179 description:
180 - A cron or rate expression that defines the schedule the rule will trigger on.
181 returned: success
182 type: str
183 sample: 'cron(0 20 * * ? *)'
184 state:
185 description:
186 - Whether the rule is present (and enabled), disabled, or absent.
187 returned: success
188 type: str
189 sample: "enabled"
190 description:
191 description:
192 - A description of the rule.
193 returned: success
194 type: str
195 sample: "Run my scheduled task"
196 arn:
197 description: The ARN associated with the rule.
198 type: str
199 returned: success
200 sample: 'arn:aws:events:us-east-1:123456789012:rule/MyCronTask'
201 targets:
202 description: CloudWatch Event target(s) assigned to the rule.
203 returned: success
204 type: list
205 elements: dict
206 contains:
207 id:
208 description: The unique target assignment ID.
209 type: str
210 returned: success
211 sample: 'MyTargetId'
212 arn:
213 description: The ARN associated with the target.
214 type: str
215 returned: success
216 sample: 'arn:aws:lambda:us-east-1:123456789012:function:MyFunction'
217 """
218
219 import json
220
221 try:
222 import botocore
223 except ImportError:
224 pass # handled by AnsibleAWSModule
225
226 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
227 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
228
229 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
230 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
231 from ansible_collections.amazon.aws.plugins.module_utils.transformation import scrub_none_parameters
232
233
234 def _format_json(json_string):
235 # When passed a simple string, Ansible doesn't quote it to ensure it's a *quoted* string
236 try:
237 json.loads(json_string)
238 return json_string
239 except json.decoder.JSONDecodeError:
240 return str(json.dumps(json_string))
241
242
243 def _validate_json(s):
244 try:
245 json.loads(s)
246 return True
247 except json.JSONDecodeError:
248 return False
249
250
251 class CloudWatchEventRule:
252 def __init__(
253 self, module, name, client, schedule_expression=None, event_pattern=None, description=None, role_arn=None
254 ):
255 self.name = name
256 self.client = client
257 self.changed = False
258 self.schedule_expression = schedule_expression
259 self.event_pattern = event_pattern
260 self.description = description
261 self.role_arn = role_arn
262 self.module = module
263
264 def describe(self):
265 """Returns the existing details of the rule in AWS"""
266 try:
267 rule_info = self.client.describe_rule(Name=self.name)
268 except is_boto3_error_code("ResourceNotFoundException"):
269 return {}
270 except (
271 botocore.exceptions.BotoCoreError,
272 botocore.exceptions.ClientError,
273 ) as e: # pylint: disable=duplicate-except
274 self.module.fail_json_aws(e, msg=f"Could not describe rule {self.name}")
275 return camel_dict_to_snake_dict(rule_info)
276
277 def put(self, enabled=True):
278 """Creates or updates the rule in AWS"""
279 request = {
280 "Name": self.name,
281 "State": "ENABLED" if enabled else "DISABLED",
282 }
283 if self.schedule_expression:
284 request["ScheduleExpression"] = self.schedule_expression
285 if self.event_pattern:
286 request["EventPattern"] = self.event_pattern
287 if self.description:
288 request["Description"] = self.description
289 if self.role_arn:
290 request["RoleArn"] = self.role_arn
291 try:
292 response = self.client.put_rule(**request)
293 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
294 self.module.fail_json_aws(e, msg=f"Could not create/update rule {self.name}")
295 self.changed = True
296 return response
297
298 def delete(self):
299 """Deletes the rule in AWS"""
300 self.remove_all_targets()
301
302 try:
303 response = self.client.delete_rule(Name=self.name)
304 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
305 self.module.fail_json_aws(e, msg=f"Could not delete rule {self.name}")
306 self.changed = True
307 return response
308
309 def enable(self):
310 """Enables the rule in AWS"""
311 try:
312 response = self.client.enable_rule(Name=self.name)
313 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
314 self.module.fail_json_aws(e, msg=f"Could not enable rule {self.name}")
315 self.changed = True
316 return response
317
318 def disable(self):
319 """Disables the rule in AWS"""
320 try:
321 response = self.client.disable_rule(Name=self.name)
322 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
323 self.module.fail_json_aws(e, msg=f"Could not disable rule {self.name}")
324 self.changed = True
325 return response
326
327 def list_targets(self):
328 """Lists the existing targets for the rule in AWS"""
329 try:
330 targets = self.client.list_targets_by_rule(Rule=self.name)
331 except is_boto3_error_code("ResourceNotFoundException"):
332 return []
333 except (
334 botocore.exceptions.BotoCoreError,
335 botocore.exceptions.ClientError,
336 ) as e: # pylint: disable=duplicate-except
337 self.module.fail_json_aws(e, msg=f"Could not find target for rule {self.name}")
338 return camel_dict_to_snake_dict(targets)["targets"]
339
340 def put_targets(self, targets):
341 """Creates or updates the provided targets on the rule in AWS"""
342 if not targets:
343 return
344 request = {
345 "Rule": self.name,
346 "Targets": self._targets_request(targets),
347 }
348 try:
349 response = self.client.put_targets(**request)
350 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
351 self.module.fail_json_aws(e, msg=f"Could not create/update rule targets for rule {self.name}")
352 self.changed = True
353 return response
354
355 def remove_targets(self, target_ids):
356 """Removes the provided targets from the rule in AWS"""
357 if not target_ids:
358 return
359 request = {"Rule": self.name, "Ids": target_ids}
360 try:
361 response = self.client.remove_targets(**request)
362 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
363 self.module.fail_json_aws(e, msg=f"Could not remove rule targets from rule {self.name}")
364 self.changed = True
365 return response
366
367 def remove_all_targets(self):
368 """Removes all targets on rule"""
369 targets = self.list_targets()
370 return self.remove_targets([t["id"] for t in targets])
371
372 def _targets_request(self, targets):
373 """Formats each target for the request"""
374 targets_request = []
375 for target in targets:
376 target_request = scrub_none_parameters(snake_dict_to_camel_dict(target, True))
377 if target_request.get("Input", None):
378 target_request["Input"] = _format_json(target_request["Input"])
379 if target_request.get("InputTransformer", None):
380 if target_request.get("InputTransformer").get("InputTemplate", None):
381 target_request["InputTransformer"]["InputTemplate"] = _format_json(
382 target_request["InputTransformer"]["InputTemplate"]
383 )
384 if target_request.get("InputTransformer").get("InputPathsMap", None):
385 target_request["InputTransformer"]["InputPathsMap"] = target["input_transformer"]["input_paths_map"]
386 targets_request.append(target_request)
387 return targets_request
388
389
390 class CloudWatchEventRuleManager:
391 RULE_FIELDS = ["name", "event_pattern", "schedule_expression", "description", "role_arn"]
392
393 def __init__(self, rule, targets):
394 self.rule = rule
395 self.targets = targets
396
397 def ensure_present(self, enabled=True):
398 """Ensures the rule and targets are present and synced"""
399 rule_description = self.rule.describe()
400 if rule_description:
401 # Rule exists so update rule, targets and state
402 self._sync_rule(enabled)
403 self._sync_targets()
404 self._sync_state(enabled)
405 else:
406 # Rule does not exist, so create new rule and targets
407 self._create(enabled)
408
409 def ensure_disabled(self):
410 """Ensures the rule and targets are present, but disabled, and synced"""
411 self.ensure_present(enabled=False)
412
413 def ensure_absent(self):
414 """Ensures the rule and targets are absent"""
415 rule_description = self.rule.describe()
416 if not rule_description:
417 # Rule doesn't exist so don't need to delete
418 return
419 self.rule.delete()
420
421 def fetch_aws_state(self):
422 """Retrieves rule and target state from AWS"""
423 aws_state = {"rule": {}, "targets": [], "changed": self.rule.changed}
424 rule_description = self.rule.describe()
425 if not rule_description:
426 return aws_state
427
428 # Don't need to include response metadata noise in response
429 del rule_description["response_metadata"]
430
431 aws_state["rule"] = rule_description
432 aws_state["targets"].extend(self.rule.list_targets())
433 return aws_state
434
435 def _sync_rule(self, enabled=True):
436 """Syncs local rule state with AWS"""
437 if not self._rule_matches_aws():
438 self.rule.put(enabled)
439
440 def _sync_targets(self):
441 """Syncs local targets with AWS"""
442 # Identify and remove extraneous targets on AWS
443 target_ids_to_remove = self._remote_target_ids_to_remove()
444 if target_ids_to_remove:
445 self.rule.remove_targets(target_ids_to_remove)
446
447 # Identify targets that need to be added or updated on AWS
448 targets_to_put = self._targets_to_put()
449 if targets_to_put:
450 self.rule.put_targets(targets_to_put)
451
452 def _sync_state(self, enabled=True):
453 """Syncs local rule state with AWS"""
454 remote_state = self._remote_state()
455 if enabled and remote_state != "ENABLED":
456 self.rule.enable()
457 elif not enabled and remote_state != "DISABLED":
458 self.rule.disable()
459
460 def _create(self, enabled=True):
461 """Creates rule and targets on AWS"""
462 self.rule.put(enabled)
463 self.rule.put_targets(self.targets)
464
465 def _rule_matches_aws(self):
466 """Checks if the local rule data matches AWS"""
467 aws_rule_data = self.rule.describe()
468
469 # The rule matches AWS only if all rule data fields are equal
470 # to their corresponding local value defined in the task
471 return all(getattr(self.rule, field) == aws_rule_data.get(field, None) for field in self.RULE_FIELDS)
472
473 def _targets_to_put(self):
474 """Returns a list of targets that need to be updated or added remotely"""
475 remote_targets = self.rule.list_targets()
476
477 # keys with none values must be scrubbed off of self.targets
478 temp = []
479 for t in self.targets:
480 if t["input_transformer"] is not None and t["input_transformer"]["input_template"] is not None:
481 # The remote_targets contain quotes, so add
482 # quotes to temp
483 val = t["input_transformer"]["input_template"]
484 # list_targets_by_rule return input_template as string
485 # if existing value is string "<instance> is in state <state>", it returns '"<instance> is in state <state>"'
486 # if existing value is <JSON>, it returns '<JSON>'
487 # therefore add quotes to provided input_template value only if it is not a JSON
488 valid_json = _validate_json(val)
489 if not valid_json:
490 t["input_transformer"]["input_template"] = '"' + val + '"'
491 temp.append(scrub_none_parameters(t))
492 self.targets = temp
493 # remote_targets is snakified output of client.list_targets_by_rule()
494 # therefore snakified version of t should be compared to avoid wrong result of below conditional
495 return [t for t in self.targets if camel_dict_to_snake_dict(t) not in remote_targets]
496
497 def _remote_target_ids_to_remove(self):
498 """Returns a list of targets that need to be removed remotely"""
499 target_ids = [t["id"] for t in self.targets]
500 remote_targets = self.rule.list_targets()
501 return [rt["id"] for rt in remote_targets if rt["id"] not in target_ids]
502
503 def _remote_state(self):
504 """Returns the remote state from AWS"""
505 description = self.rule.describe()
506 if not description:
507 return
508 return description["state"]
509
510
511 def main():
512 target_args = dict(
513 type="list",
514 elements="dict",
515 default=[],
516 options=dict(
517 id=dict(type="str", required=True),
518 arn=dict(type="str", required=True),
519 role_arn=dict(type="str"),
520 input=dict(type="json"),
521 input_path=dict(type="str"),
522 input_transformer=dict(
523 type="dict",
524 options=dict(
525 input_paths_map=dict(type="dict"),
526 input_template=dict(type="json"),
527 ),
528 ),
529 ecs_parameters=dict(
530 type="dict",
531 options=dict(
532 task_definition_arn=dict(type="str", required=True),
533 task_count=dict(type="int"),
534 ),
535 ),
536 ),
537 )
538 argument_spec = dict(
539 name=dict(required=True),
540 schedule_expression=dict(),
541 event_pattern=dict(type="json"),
542 state=dict(choices=["present", "disabled", "absent"], default="present"),
543 description=dict(),
544 role_arn=dict(),
545 targets=target_args,
546 )
547 module = AnsibleAWSModule(argument_spec=argument_spec)
548
549 rule_data = dict([(rf, module.params.get(rf)) for rf in CloudWatchEventRuleManager.RULE_FIELDS])
550 targets = module.params.get("targets")
551 state = module.params.get("state")
552 client = module.client("events")
553
554 cwe_rule = CloudWatchEventRule(module, client=client, **rule_data)
555 cwe_rule_manager = CloudWatchEventRuleManager(cwe_rule, targets)
556
557 if state == "present":
558 cwe_rule_manager.ensure_present()
559 elif state == "disabled":
560 cwe_rule_manager.ensure_disabled()
561 elif state == "absent":
562 cwe_rule_manager.ensure_absent()
563 else:
564 module.fail_json(msg=f"Invalid state '{state}' provided")
565
566 module.exit_json(**cwe_rule_manager.fetch_aws_state())
567
568
569 if __name__ == "__main__":
570 main()