Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/lambda_info.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: lambda_info
10 version_added: 5.0.0
11 short_description: Gathers AWS Lambda function details
12 description:
13 - Gathers various details related to Lambda functions, including aliases, versions and event source mappings.
14 - Use module M(amazon.aws.lambda) to manage the lambda function itself, M(amazon.aws.lambda_alias) to manage function aliases,
15 M(amazon.aws.lambda_event) to manage lambda event source mappings, and M(amazon.aws.lambda_policy) to manage policy statements.
16 - This module was originally added to C(community.aws) in release 1.0.0.
17 options:
18 query:
19 description:
20 - Specifies the resource type for which to gather information.
21 - Defaults to V(all) when O(function_name) is specified.
22 - Defaults to V(config) when O(function_name) is NOT specified.
23 choices: [ "aliases", "all", "config", "mappings", "policy", "versions", "tags" ]
24 type: str
25 function_name:
26 description:
27 - The name of the lambda function for which information is requested.
28 aliases: [ "function", "name"]
29 type: str
30 event_source_arn:
31 description:
32 - When O(query=mappings), this is the Amazon Resource Name (ARN) of the Amazon Kinesis or DynamoDB stream.
33 type: str
34 author:
35 - Pierre Jodouin (@pjodouin)
36 extends_documentation_fragment:
37 - amazon.aws.common.modules
38 - amazon.aws.region.modules
39 - amazon.aws.boto3
40 """
41
42 EXAMPLES = r"""
43 ---
44 # Simple example of listing all info for a function
45 - name: List all for a specific function
46 amazon.aws.lambda_info:
47 query: all
48 function_name: myFunction
49 register: my_function_details
50
51 # Get basic information about AWS Lambda Functions in the current region
52 - name: List Lambda Functions
53 amazon.aws.lambda_info:
54 register: lambda_functions
55
56 # List all versions of a function
57 - name: List function versions
58 amazon.aws.lambda_info:
59 query: versions
60 function_name: myFunction
61 register: my_function_versions
62
63 # List all info for all functions
64 - name: List all functions
65 amazon.aws.lambda_info:
66 query: all
67 register: output
68
69 - name: show Lambda information
70 ansible.builtin.debug:
71 msg: "{{ output['function'] }}"
72 """
73
74 RETURN = r"""
75 ---
76 functions:
77 description: List of information for each lambda function matching the query.
78 returned: always
79 type: list
80 elements: dict
81 version_added: 4.1.0
82 version_added_collection: community.aws
83 contains:
84 aliases:
85 description: The aliases associated with the function.
86 returned: when O(query=aliases) or O(query=all)
87 type: list
88 elements: str
89 architectures:
90 description: The architectures supported by the function.
91 returned: success
92 type: list
93 elements: str
94 sample: ['arm64']
95 code_sha256:
96 description: The SHA256 hash of the function's deployment package.
97 returned: success
98 type: str
99 sample: 'zOAGfF5JLFuzZoSNirUtOrQp+S341IOA3BcoXXoaIaU='
100 code_size:
101 description: The size of the function's deployment package in bytes.
102 returned: success
103 type: int
104 sample: 123
105 dead_letter_config:
106 description: The function's dead letter queue.
107 returned: when the function has a dead letter queue configured
108 type: dict
109 sample: { 'target_arn': arn:aws:lambda:us-east-1:123456789012:function:myFunction:1 }
110 contains:
111 target_arn:
112 description: The ARN of an SQS queue or SNS topic.
113 returned: when the function has a dead letter queue configured
114 type: str
115 sample: arn:aws:lambda:us-east-1:123456789012:function:myFunction:1
116 description:
117 description: The function's description.
118 returned: success
119 type: str
120 sample: 'My function'
121 ephermal_storage:
122 description: The size of the function /tmp directory in MB.
123 type: dict
124 contains:
125 size:
126 description: The size of the function /tmp directory.
127 type: int
128 returned: always
129 sample: 512
130 environment:
131 description: The function's environment variables.
132 returned: when environment variables exist
133 type: dict
134 contains:
135 variables:
136 description: Environment variable key-value pairs.
137 returned: when environment variables exist
138 type: dict
139 sample: {'key': 'value'}
140 error:
141 description: Error message for environment variables that could not be applied.
142 returned: when there is an error applying environment variables
143 type: dict
144 contains:
145 error_code:
146 description: The error code.
147 returned: when there is an error applying environment variables
148 type: str
149 message:
150 description: The error message.
151 returned: when there is an error applying environment variables
152 type: str
153 function_arn:
154 description: The function's Amazon Resource Name (ARN).
155 returned: on success
156 type: str
157 sample: 'arn:aws:lambda:us-east-1:123456789012:function:myFunction:1'
158 function_name:
159 description: The function's name.
160 returned: on success
161 type: str
162 sample: 'myFunction'
163 handler:
164 description: The function Lambda calls to begin executing your function.
165 returned: on success
166 type: str
167 sample: 'index.handler'
168 last_modified:
169 description: The date and time that the function was last updated, in ISO-8601 format (YYYY-MM-DDThh:mm:ssTZD).
170 returned: on success
171 type: str
172 sample: '2017-08-01T00:00:00.000+0000'
173 mappings:
174 description: List of configuration information for each event source mapping.
175 returned: when O(query=all) or O(query=mappings)
176 type: list
177 elements: dict
178 contains:
179 uuid:
180 description: The AWS Lambda assigned opaque identifier for the mapping.
181 returned: on success
182 type: str
183 batch_size:
184 description: The largest number of records that AWS Lambda will retrieve from the event source at the time of invoking the function.
185 returned: on success
186 type: int
187 event_source_arn:
188 description: The ARN of the Amazon Kinesis or DyanmoDB stream that is the source of events.
189 returned: on success
190 type: str
191 function_arn:
192 description: The Lambda function to invoke when AWS Lambda detects an event on the poll-based source.
193 returned: on success
194 type: str
195 last_modified:
196 description: The UTC time string indicating the last time the event mapping was updated.
197 returned: on success
198 type: str
199 last_processing_result:
200 description: The result of the last AWS Lambda invocation of your Lambda function.
201 returned: on success
202 type: str
203 state:
204 description: The state of the event source mapping.
205 returned: on success
206 type: str
207 state_transition_reason:
208 description: The reason the event source mapping is in its current state.
209 returned: on success
210 type: str
211 memory_size:
212 description: The memory allocated to the function.
213 returned: on success
214 type: int
215 sample: 128
216 package_type:
217 description: The type of deployment package.
218 type: str
219 returned: always
220 sample: "Zip"
221 policy:
222 description: The policy associated with the function.
223 returned: when O(query=all) or O(query=policy)
224 type: dict
225 revision_id:
226 description: The latest updated revision of the function or alias.
227 returned: on success
228 type: str
229 sample: 'a2x9886d-d48a-4a0c-ab64-82abc005x80c'
230 role:
231 description: The function's execution role.
232 returned: on success
233 type: str
234 sample: 'arn:aws:iam::123456789012:role/lambda_basic_execution'
235 runtime:
236 description: The funtime environment for the Lambda function.
237 returned: on success
238 type: str
239 sample: 'nodejs6.10'
240 runtime_version_config:
241 description: The ARN of the runtime and any errors that occured.
242 type: dict
243 contains:
244 runtime_version_arn:
245 description: The ARN of the runtime version you want the function to use.
246 type: str
247 returned: always
248 sample: "arn:aws:lambda:us-west-2::runtime:123456789012"
249 snap_start:
250 description: Snapshot of the initialized execution environment when you publish a function version.
251 type: dict
252 contains:
253 apply_on:
254 description: When set to V(PublishedVersions), Lambda creates a snapshot of the execution environment when you publish a function version.
255 type: str
256 sample: "None"
257 returned: always
258 optimization_status:
259 description: This element indicates whether SnapStart is activated for the specified function version.
260 type: str
261 returned: always
262 sample: "Off"
263 tracing_config:
264 description: The function's AWS X-Ray tracing configuration.
265 returned: on success
266 type: dict
267 sample: { 'mode': 'Active' }
268 contains:
269 mode:
270 description: The tracing mode.
271 returned: on success
272 type: str
273 sample: 'Active'
274 timeout:
275 description: The amount of time that Lambda allows a function to run before terminating it.
276 returned: on success
277 type: int
278 sample: 3
279 version:
280 description: The version of the Lambda function.
281 returned: on success
282 type: str
283 sample: '1'
284 versions:
285 description: List of Lambda function versions.
286 returned: when O(query=all) or O(query=versions)
287 type: list
288 elements: dict
289 vpc_config:
290 description: The function's networking configuration.
291 returned: on success
292 type: dict
293 sample: {
294 'security_group_ids': [],
295 'subnet_ids': [],
296 'vpc_id': '123'
297 }
298 """
299
300 import json
301 import re
302
303 try:
304 import botocore
305 except ImportError:
306 pass # caught by AnsibleAWSModule
307
308 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
309
310 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
311 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
312 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
313
314
315 @AWSRetry.jittered_backoff()
316 def _paginate(client, function, **params):
317 paginator = client.get_paginator(function)
318 return paginator.paginate(**params).build_full_result()
319
320
321 def alias_details(client, module, function_name):
322 """
323 Returns list of aliases for a specified function.
324
325 :param client: AWS API client reference (boto3)
326 :param module: Ansible module reference
327 :param function_name (str): Name of Lambda function to query
328 :return dict:
329 """
330
331 lambda_info = dict()
332
333 try:
334 lambda_info.update(aliases=_paginate(client, "list_aliases", FunctionName=function_name)["Aliases"])
335 except is_boto3_error_code("ResourceNotFoundException"):
336 lambda_info.update(aliases=[])
337 except (
338 botocore.exceptions.ClientError,
339 botocore.exceptions.BotoCoreError,
340 ) as e: # pylint: disable=duplicate-except
341 module.fail_json_aws(e, msg="Trying to get aliases")
342
343 return camel_dict_to_snake_dict(lambda_info)
344
345
346 def _get_query(query, function_name):
347 # create default values for query if not specified.
348 # if function name exists, query should default to 'all'.
349 # if function name does not exist, query should default to 'config' to limit the runtime when listing all lambdas.
350 if query:
351 return query
352 if function_name:
353 return "all"
354 return "config"
355
356
357 def list_functions(client, module):
358 """
359 Returns queried facts for a specified function (or all functions).
360
361 :param client: AWS API client reference (boto3)
362 :param module: Ansible module reference
363 """
364
365 function_name = module.params.get("function_name")
366 if function_name:
367 # Function name is specified - retrieve info on that function
368 function_names = [function_name]
369
370 else:
371 # Function name is not specified - retrieve all function names
372 all_function_info = _paginate(client, "list_functions")["Functions"]
373 function_names = [function_info["FunctionName"] for function_info in all_function_info]
374
375 query = _get_query(module.params["query"], function_name)
376 functions = []
377
378 for function_name in function_names:
379 function = {}
380
381 # query = 'config' returns info such as FunctionName, FunctionArn, Description, etc
382 # these details should be returned regardless of the query
383 function.update(config_details(client, module, function_name))
384
385 if query in ["all", "aliases"]:
386 function.update(alias_details(client, module, function_name))
387
388 if query in ["all", "policy"]:
389 function.update(policy_details(client, module, function_name))
390
391 if query in ["all", "versions"]:
392 function.update(version_details(client, module, function_name))
393
394 if query in ["all", "mappings"]:
395 function.update(mapping_details(client, module, function_name))
396
397 if query in ["all", "tags"]:
398 function.update(tags_details(client, module, function_name))
399
400 functions.append(function)
401
402 module.exit_json(functions=functions, changed=False)
403
404
405 def config_details(client, module, function_name):
406 """
407 Returns configuration details for a lambda function.
408
409 :param client: AWS API client reference (boto3)
410 :param module: Ansible module reference
411 :param function_name (str): Name of Lambda function to query
412 :return dict:
413 """
414
415 lambda_info = dict()
416
417 try:
418 lambda_info.update(client.get_function_configuration(aws_retry=True, FunctionName=function_name))
419 except is_boto3_error_code("ResourceNotFoundException"):
420 lambda_info.update(function={})
421 except (
422 botocore.exceptions.ClientError,
423 botocore.exceptions.BotoCoreError,
424 ) as e: # pylint: disable=duplicate-except
425 module.fail_json_aws(e, msg=f"Trying to get {function_name} configuration")
426
427 if "Environment" in lambda_info and "Variables" in lambda_info["Environment"]:
428 env_vars = lambda_info["Environment"]["Variables"]
429 snaked_lambda_info = camel_dict_to_snake_dict(lambda_info)
430 snaked_lambda_info["environment"]["variables"] = env_vars
431 else:
432 snaked_lambda_info = camel_dict_to_snake_dict(lambda_info)
433
434 return snaked_lambda_info
435
436
437 def mapping_details(client, module, function_name):
438 """
439 Returns all lambda event source mappings.
440
441 :param client: AWS API client reference (boto3)
442 :param module: Ansible module reference
443 :param function_name (str): Name of Lambda function to query
444 :return dict:
445 """
446
447 lambda_info = dict()
448 params = dict()
449
450 params["FunctionName"] = function_name
451
452 if module.params.get("event_source_arn"):
453 params["EventSourceArn"] = module.params.get("event_source_arn")
454
455 try:
456 lambda_info.update(mappings=_paginate(client, "list_event_source_mappings", **params)["EventSourceMappings"])
457 except is_boto3_error_code("ResourceNotFoundException"):
458 lambda_info.update(mappings=[])
459 except (
460 botocore.exceptions.ClientError,
461 botocore.exceptions.BotoCoreError,
462 ) as e: # pylint: disable=duplicate-except
463 module.fail_json_aws(e, msg="Trying to get source event mappings")
464
465 return camel_dict_to_snake_dict(lambda_info)
466
467
468 def policy_details(client, module, function_name):
469 """
470 Returns policy attached to a lambda function.
471
472 :param client: AWS API client reference (boto3)
473 :param module: Ansible module reference
474 :param function_name (str): Name of Lambda function to query
475 :return dict:
476 """
477
478 lambda_info = dict()
479
480 try:
481 # get_policy returns a JSON string so must convert to dict before reassigning to its key
482 lambda_info.update(policy=json.loads(client.get_policy(aws_retry=True, FunctionName=function_name)["Policy"]))
483 except is_boto3_error_code("ResourceNotFoundException"):
484 lambda_info.update(policy={})
485 except (
486 botocore.exceptions.ClientError,
487 botocore.exceptions.BotoCoreError,
488 ) as e: # pylint: disable=duplicate-except
489 module.fail_json_aws(e, msg=f"Trying to get {function_name} policy")
490
491 return camel_dict_to_snake_dict(lambda_info)
492
493
494 def version_details(client, module, function_name):
495 """
496 Returns all lambda function versions.
497
498 :param client: AWS API client reference (boto3)
499 :param module: Ansible module reference
500 :param function_name (str): Name of Lambda function to query
501 :return dict:
502 """
503
504 lambda_info = dict()
505
506 try:
507 lambda_info.update(
508 versions=_paginate(client, "list_versions_by_function", FunctionName=function_name)["Versions"]
509 )
510 except is_boto3_error_code("ResourceNotFoundException"):
511 lambda_info.update(versions=[])
512 except (
513 botocore.exceptions.ClientError,
514 botocore.exceptions.BotoCoreError,
515 ) as e: # pylint: disable=duplicate-except
516 module.fail_json_aws(e, msg=f"Trying to get {function_name} versions")
517
518 return camel_dict_to_snake_dict(lambda_info)
519
520
521 def tags_details(client, module, function_name):
522 """
523 Returns tag details for a lambda function.
524
525 :param client: AWS API client reference (boto3)
526 :param module: Ansible module reference
527 :param function_name (str): Name of Lambda function to query
528 :return dict:
529 """
530
531 lambda_info = dict()
532
533 try:
534 lambda_info.update(tags=client.get_function(aws_retry=True, FunctionName=function_name).get("Tags", {}))
535 except is_boto3_error_code("ResourceNotFoundException"):
536 lambda_info.update(function={})
537 except (
538 botocore.exceptions.ClientError,
539 botocore.exceptions.BotoCoreError,
540 ) as e: # pylint: disable=duplicate-except
541 module.fail_json_aws(e, msg=f"Trying to get {function_name} tags")
542
543 return camel_dict_to_snake_dict(lambda_info)
544
545
546 def main():
547 """
548 Main entry point.
549
550 :return dict: ansible facts
551 """
552 argument_spec = dict(
553 function_name=dict(required=False, default=None, aliases=["function", "name"]),
554 query=dict(
555 required=False, choices=["aliases", "all", "config", "mappings", "policy", "versions", "tags"], default=None
556 ),
557 event_source_arn=dict(required=False, default=None),
558 )
559
560 module = AnsibleAWSModule(
561 argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=[], required_together=[]
562 )
563
564 # validate function_name if present
565 function_name = module.params["function_name"]
566 if function_name:
567 if not re.search(r"^[\w\-:]+$", function_name):
568 module.fail_json(
569 msg=f"Function name {function_name} is invalid. Names must contain only alphanumeric characters and hyphens.",
570 )
571 if len(function_name) > 64:
572 module.fail_json(msg=f'Function name "{function_name}" exceeds 64 character limit')
573
574 client = module.client("lambda", retry_decorator=AWSRetry.jittered_backoff())
575
576 list_functions(client, module)
577
578
579 if __name__ == "__main__":
580 main()