Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2016, Pierre Jodouin <[email protected]>
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: lambda_event
10 version_added: 5.0.0
11 short_description: Creates, updates or deletes AWS Lambda function event mappings
12 description:
13 - This module allows the management of AWS Lambda function event source mappings such as DynamoDB and Kinesis stream
14 events via the Ansible framework. These event source mappings are relevant only in the AWS Lambda pull model, where
15 AWS Lambda invokes the function.
16 It is idempotent and supports "Check" mode. Use module M(amazon.aws.lambda) to manage the lambda
17 function itself and M(amazon.aws.lambda_alias) to manage function aliases.
18 - This module was originally added to C(community.aws) in release 1.0.0.
19
20 author:
21 - Pierre Jodouin (@pjodouin)
22 - Ryan Brown (@ryansb)
23 options:
24 lambda_function_arn:
25 description:
26 - The name or ARN of the lambda function.
27 required: true
28 aliases: ['function_name', 'function_arn']
29 type: str
30 state:
31 description:
32 - Describes the desired state.
33 default: "present"
34 choices: ["present", "absent"]
35 type: str
36 alias:
37 description:
38 - Name of the function alias.
39 - Mutually exclusive with O(version).
40 type: str
41 version:
42 description:
43 - Version of the Lambda function.
44 - Mutually exclusive with O(alias).
45 type: int
46 default: 0
47 event_source:
48 description:
49 - Source of the event that triggers the lambda function.
50 - For DynamoDB and Kinesis events, select V(stream).
51 - For SQS queues, select V(sqs).
52 default: stream
53 choices: ['stream', 'sqs']
54 type: str
55 source_params:
56 description:
57 - Sub-parameters required for event source.
58 suboptions:
59 source_arn:
60 description:
61 - The Amazon Resource Name (ARN) of the SQS queue, Kinesis stream or DynamoDB stream that is the event source.
62 type: str
63 required: true
64 enabled:
65 description:
66 - Indicates whether AWS Lambda should begin polling or readin from the event source.
67 default: true
68 type: bool
69 batch_size:
70 description:
71 - The largest number of records that AWS Lambda will retrieve from your event source at the time of invoking your function.
72 - Amazon Kinesis - Default V(100). Max V(10000).
73 - Amazon DynamoDB Streams - Default V(100). Max V(10000).
74 - Amazon Simple Queue Service - Default V(10). For standard queues the max is V(10000). For FIFO queues the max is V(10).
75 - Amazon Managed Streaming for Apache Kafka - Default V(100). Max V(10000).
76 - Self-managed Apache Kafka - Default C(100). Max V(10000).
77 - Amazon MQ (ActiveMQ and RabbitMQ) - Default V(100). Max V(10000).
78 - DocumentDB - Default V(100). Max V(10000).
79 type: int
80 starting_position:
81 description:
82 - The position in the stream where AWS Lambda should start reading.
83 - Required when O(event_source=stream).
84 choices: [TRIM_HORIZON,LATEST]
85 type: str
86 function_response_types:
87 description:
88 - (Streams and Amazon SQS) A list of current response type enums applied to the event source mapping.
89 type: list
90 elements: str
91 choices: [ReportBatchItemFailures]
92 version_added: 5.5.0
93 maximum_batching_window_in_seconds:
94 description:
95 - The maximum amount of time, in seconds, that Lambda spends gathering records before invoking the function.
96 - You can configure O(source_params.maximum_batching_window_in_seconds) to any value from V(0) seconds to V(300) seconds in increments of seconds.
97 - For streams and Amazon SQS event sources, when O(source_params.batch_size) is set to a value greater than V(10),
98 O(source_params.maximum_batching_window_in_seconds) defaults to V(1).
99 - O(source_params.maximum_batching_window_in_seconds) is not supported by FIFO queues.
100 type: int
101 version_added: 8.0.0
102 required: true
103 type: dict
104 extends_documentation_fragment:
105 - amazon.aws.common.modules
106 - amazon.aws.region.modules
107 - amazon.aws.boto3
108 """
109
110 EXAMPLES = r"""
111 # Example that creates a lambda event notification for a DynamoDB stream
112 - name: DynamoDB stream event mapping
113 amazon.aws.lambda_event:
114 state: present
115 event_source: stream
116 function_name: "{{ function_name }}"
117 alias: Dev
118 source_params:
119 source_arn: arn:aws:dynamodb:us-east-1:123456789012:table/tableName/stream/2016-03-19T19:51:37.457
120 enabled: true
121 batch_size: 100
122 starting_position: TRIM_HORIZON
123 register: event
124
125 # Example that creates a lambda event notification for a DynamoDB stream
126 - name: DynamoDB stream event mapping
127 amazon.aws.lambda_event:
128 state: present
129 event_source: stream
130 function_name: "{{ function_name }}"
131 source_params:
132 source_arn: arn:aws:dynamodb:us-east-1:123456789012:table/tableName/stream/2016-03-19T19:51:37.457
133 enabled: true
134 batch_size: 100
135 starting_position: LATEST
136 function_response_types:
137 - ReportBatchItemFailures
138 register: event
139
140 - name: Show source event
141 ansible.builtin.debug:
142 var: event.lambda_stream_events
143 """
144
145 RETURN = r"""
146 ---
147 events:
148 description: Dictionary returned by the API describing stream event mappings
149 returned: success
150 type: dict
151 contains:
152 batch_size:
153 description: The maximum number of records in each batch that Lambda pulls.
154 type: int
155 returned: always
156 bisect_batch_on_function_error:
157 description: If the function returns an error, split the batch in two and retry.
158 type: bool
159 returned: for Kinesis and DynamoDB Streams only
160 sample: false
161 destination_config:
162 description: Configuration object that specifies the destination of an event after Lambda processes it.
163 type: dict
164 returned: For Kinesis, DynamoDB Streams, Amazon MSK, and self-managed Kafka only
165 contains:
166 on_failure:
167 description: The destination configuration for failed invocations.
168 type: dict
169 contains:
170 destination:
171 description: Destination resource ARN.
172 type: str
173 on_success:
174 description: The destination configuration for failed invocations.
175 type: dict
176 contains:
177 destination:
178 description: Destination resource ARN.
179 type: str
180 event_source_arn:
181 description: The Amazon Resource Name (ARN) of the event source.
182 type: str
183 returned: always
184 sample: "arn:aws:dynamodb:us-west-2:123456789012:table/yyyy/stream/2024-06-06T07:03:58.956"
185 function_arn:
186 description: The ARN of the Lambda function.
187 type: str
188 returned: always
189 sample: "arn:aws:lambda:us-west-2:123456789012:function:test-lambda-3a0a29d0dbb5:1"
190 function_response_types:
191 description: A list of current response type enums applied to the event source mapping.
192 type: list
193 returned: For Kinesis, DynamoDB Streams, and Amazon SQS
194 sample: ["ReportBatchItemFailures"]
195 last_modified:
196 description: The date that the event source mapping was last updated or that its state changed.
197 type: str
198 returned: always
199 sample: "2024-06-06T12:34:21.990000+05:30"
200 last_processing_result:
201 description: The result of the last Lambda invocation of your function.
202 type: str
203 returned: always
204 sample: "No records processed"
205 maximum_batching_window_in_seconds:
206 description: The maximum amount of time, in seconds, that Lambda spends gathering records before invoking the function.
207 type: int
208 returned: always
209 sample: 1
210 maximum_record_age_in_seconds:
211 description: Discard records older than the specified age. The default value is infinite (-1).
212 type: int
213 returned: For Kinesis and DynamoDB Streams only
214 sample: -1
215 maximum_retry_attempts:
216 description: Discard records after the specified number of retries.
217 type: int
218 returned: For Kinesis and DynamoDB Streams only
219 sample: -1
220 parallelization_factor:
221 description: The number of batches to process concurrently from each shard.
222 type: int
223 returned: For Kinesis and DynamoDB Streams only
224 sample: 1
225 starting_position:
226 description: The position in a stream from which to start reading.
227 type: str
228 returned: For Kinesis and DynamoDB Streams only
229 sample: "LATEST"
230 state:
231 description: The state of the event source mapping.
232 type: str
233 returned: always
234 sample: "deleting"
235 state_transition_reason:
236 description: Indicates whether a user or Lambda made the last change to the event source mapping.
237 type: str
238 returned: always
239 sample: "USER_INITIATED"
240 tumbling_window_in_seconds:
241 description: The duration in seconds of a processing window for DynamoDB and Kinesis Streams event sources.
242 type: int
243 returned: For Kinesis and DynamoDB Streams only
244 sample: 1
245 uuid:
246 description: The identifier of the event source mapping.
247 type: str
248 returned: always
249 sample: "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
250 """
251
252 import copy
253 import re
254
255 try:
256 from botocore.exceptions import BotoCoreError
257 from botocore.exceptions import ClientError
258 from botocore.exceptions import MissingParametersError
259 from botocore.exceptions import ParamValidationError
260 except ImportError:
261 pass # Handled by AnsibleAWSModule
262
263 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
264
265 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
266 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
267 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
268
269 # ---------------------------------------------------------------------------------------------------
270 #
271 # Helper Functions & classes
272 #
273 # ---------------------------------------------------------------------------------------------------
274
275
276 def validate_params(module, client):
277 """
278 Performs basic parameter validation.
279
280 :param module: The AnsibleAWSModule object
281 :param client: The client used to perform requests to AWS
282 :return:
283 """
284
285 function_name = module.params["lambda_function_arn"]
286 qualifier = get_qualifier(module)
287
288 # validate function name
289 if not re.search(r"^[\w\-:]+$", function_name):
290 module.fail_json(
291 msg=f"Function name {function_name} is invalid. Names must contain only alphanumeric characters and hyphens.",
292 )
293
294 # lamba_fuction_arn contains only the function name (not the arn)
295 if not function_name.startswith("arn:aws:lambda:"):
296 if len(function_name) > 64:
297 module.fail_json(msg=f'Function name "{function_name}" exceeds 64 character limit')
298 try:
299 params = {"FunctionName": function_name}
300 if qualifier:
301 params["Qualifier"] = qualifier
302 response = client.get_function(**params)
303 module.params["lambda_function_arn"] = response["Configuration"]["FunctionArn"]
304 except is_boto3_error_code("ResourceNotFoundException"):
305 msg = f"An error occurred: The function '{function_name}' does not exist."
306 if qualifier:
307 msg = f"An error occurred: The function '{function_name}' (qualifier={qualifier}) does not exist."
308 module.fail_json(msg=msg)
309 except ClientError as e: # pylint: disable=duplicate-except
310 module.fail_json(msg=f"An error occurred while trying to describe function '{function_name}': {e}")
311 else:
312 if len(function_name) > 140:
313 module.fail_json(msg=f'ARN "{function_name}" exceeds 140 character limit')
314
315 if qualifier:
316 module.params["lambda_function_arn"] = f"{function_name}:{qualifier}"
317
318
319 def get_qualifier(module):
320 """
321 Returns the function qualifier as a version or alias or None.
322
323 :param module:
324 :return:
325 """
326
327 qualifier = None
328 if module.params["version"] > 0:
329 qualifier = str(module.params["version"])
330 elif module.params["alias"]:
331 qualifier = str(module.params["alias"])
332
333 return qualifier
334
335
336 # ---------------------------------------------------------------------------------------------------
337 #
338 # Lambda Event Handlers
339 #
340 # This section defines a lambda_event_X function where X is an AWS service capable of initiating
341 # the execution of a Lambda function (pull only).
342 #
343 # ---------------------------------------------------------------------------------------------------
344
345
346 def set_default_values(module, source_params):
347 _source_params_cpy = copy.deepcopy(source_params)
348
349 if module.params["event_source"].lower() == "sqs":
350 # Default 10. For standard queues the max is 10,000. For FIFO queues the max is 10.
351 _source_params_cpy.setdefault("batch_size", 10)
352
353 if source_params["source_arn"].endswith(".fifo"):
354 if _source_params_cpy["batch_size"] > 10:
355 module.fail_json(msg="For FIFO queues the maximum batch_size is 10.")
356 if _source_params_cpy.get("maximum_batching_window_in_seconds"):
357 module.fail_json(
358 msg="maximum_batching_window_in_seconds is not supported by Amazon SQS FIFO event sources."
359 )
360 else:
361 if _source_params_cpy["batch_size"] >= 10000:
362 module.fail_json(msg="For standard queue batch_size must be between lower than 10000.")
363
364 elif module.params["event_source"].lower() == "stream":
365 # Default 100.
366 _source_params_cpy.setdefault("batch_size", 100)
367
368 if not (100 <= _source_params_cpy["batch_size"] <= 10000):
369 module.fail_json(msg="batch_size for streams must be between 100 and 10000")
370
371 if _source_params_cpy["batch_size"] > 10 and not _source_params_cpy.get("maximum_batching_window_in_seconds"):
372 _source_params_cpy["maximum_batching_window_in_seconds"] = 1
373
374 return _source_params_cpy
375
376
377 def lambda_event_stream(module, client):
378 """
379 Adds, updates or deletes lambda stream (DynamoDb, Kinesis) event notifications.
380 :param module:
381 :param aws:
382 :return:
383 """
384
385 facts = dict()
386 changed = False
387 current_state = "absent"
388 state = module.params["state"]
389
390 api_params = dict(FunctionName=module.params["lambda_function_arn"])
391
392 # check if required sub-parameters are present and valid
393 source_params = module.params["source_params"]
394
395 source_arn = source_params.get("source_arn")
396 if source_arn:
397 api_params.update(EventSourceArn=source_arn)
398 else:
399 module.fail_json(msg="Source parameter 'source_arn' is required for stream event notification.")
400
401 if state == "present":
402 source_params = set_default_values(module, source_params)
403
404 # optional boolean value needs special treatment as not present does not imply False
405 source_param_enabled = module.boolean(source_params.get("enabled", "True"))
406
407 # check if event mapping exist
408 try:
409 facts = client.list_event_source_mappings(**api_params)["EventSourceMappings"]
410 if facts:
411 current_state = "present"
412 except ClientError as e:
413 module.fail_json(msg=f"Error retrieving stream event notification configuration: {e}")
414
415 if state == "present":
416 if current_state == "absent":
417 starting_position = source_params.get("starting_position")
418 event_source = module.params.get("event_source")
419 if event_source == "stream":
420 if not starting_position:
421 module.fail_json(
422 msg="Source parameter 'starting_position' is required for stream event notification."
423 )
424 api_params.update(StartingPosition=starting_position)
425
426 api_params.update(Enabled=source_param_enabled)
427 if source_params.get("batch_size"):
428 api_params.update(BatchSize=source_params.get("batch_size"))
429 if source_params.get("maximum_batching_window_in_seconds"):
430 api_params.update(
431 MaximumBatchingWindowInSeconds=source_params.get("maximum_batching_window_in_seconds")
432 )
433 if source_params.get("function_response_types"):
434 api_params.update(FunctionResponseTypes=source_params.get("function_response_types"))
435
436 try:
437 if not module.check_mode:
438 facts = client.create_event_source_mapping(**api_params)
439 changed = True
440 except (ClientError, ParamValidationError, MissingParametersError) as e:
441 module.fail_json(msg=f"Error creating stream source event mapping: {e}")
442
443 else:
444 # current_state is 'present'
445 current_mapping = facts[0]
446 api_params = dict(FunctionName=module.params["lambda_function_arn"], UUID=current_mapping["UUID"])
447 mapping_changed = False
448
449 # check if anything changed
450 if source_params.get("batch_size") and source_params["batch_size"] != current_mapping["BatchSize"]:
451 api_params.update(BatchSize=source_params["batch_size"])
452 mapping_changed = True
453
454 if source_param_enabled is not None:
455 if source_param_enabled:
456 if current_mapping["State"] not in ("Enabled", "Enabling"):
457 api_params.update(Enabled=True)
458 mapping_changed = True
459 else:
460 if current_mapping["State"] not in ("Disabled", "Disabling"):
461 api_params.update(Enabled=False)
462 mapping_changed = True
463
464 if mapping_changed:
465 try:
466 if not module.check_mode:
467 facts = client.update_event_source_mapping(**api_params)
468 changed = True
469 except (ClientError, ParamValidationError, MissingParametersError) as e:
470 module.fail_json(msg=f"Error updating stream source event mapping: {e}")
471
472 else:
473 if current_state == "present":
474 # remove the stream event mapping
475 api_params = dict(UUID=facts[0]["UUID"])
476
477 try:
478 if not module.check_mode:
479 facts = client.delete_event_source_mapping(**api_params)
480 changed = True
481 except (ClientError, ParamValidationError, MissingParametersError) as e:
482 module.fail_json(msg=f"Error removing stream source event mapping: {e}")
483
484 return camel_dict_to_snake_dict(dict(changed=changed, events=facts))
485
486
487 def main():
488 """Produce a list of function suffixes which handle lambda events."""
489 source_choices = ["stream", "sqs"]
490
491 argument_spec = dict(
492 state=dict(required=False, default="present", choices=["present", "absent"]),
493 lambda_function_arn=dict(required=True, aliases=["function_name", "function_arn"]),
494 event_source=dict(required=False, default="stream", choices=source_choices),
495 source_params=dict(
496 type="dict",
497 required=True,
498 options=dict(
499 source_arn=dict(type="str", required=True),
500 enabled=dict(type="bool", default=True),
501 batch_size=dict(type="int"),
502 starting_position=dict(type="str", choices=["TRIM_HORIZON", "LATEST"]),
503 function_response_types=dict(type="list", elements="str", choices=["ReportBatchItemFailures"]),
504 maximum_batching_window_in_seconds=dict(type="int"),
505 ),
506 ),
507 alias=dict(required=False, default=None),
508 version=dict(type="int", required=False, default=0),
509 )
510
511 module = AnsibleAWSModule(
512 argument_spec=argument_spec,
513 supports_check_mode=True,
514 mutually_exclusive=[["alias", "version"]],
515 required_together=[],
516 )
517
518 try:
519 client = module.client("lambda", retry_decorator=AWSRetry.jittered_backoff())
520 except (ClientError, BotoCoreError) as e:
521 module.fail_json_aws(e, msg="Trying to connect to AWS")
522
523 validate_params(module, client)
524
525 if module.params["event_source"].lower() in ("stream", "sqs"):
526 results = lambda_event_stream(module, client)
527 else:
528 module.fail_json(msg="Please select `stream` or `sqs` as the event type")
529
530 module.exit_json(**results)
531
532
533 if __name__ == "__main__":
534 main()