Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/lambda.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
10 version_added: 5.0.0
11 short_description: Manage AWS Lambda functions
12 description:
13 - Allows for the management of Lambda functions.
14 - This module was originally added to C(community.aws) in release 1.0.0.
15 options:
16 name:
17 description:
18 - The name you want to assign to the function you are uploading. Cannot be changed.
19 required: true
20 type: str
21 state:
22 description:
23 - Create or delete Lambda function.
24 default: present
25 choices: [ 'present', 'absent' ]
26 type: str
27 runtime:
28 description:
29 - The runtime environment for the Lambda function you are uploading.
30 - Required when creating a function. Uses parameters as described in boto3 docs.
31 - Required when O(state=present).
32 - For supported list of runtimes, see U(https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html).
33 type: str
34 role:
35 description:
36 - The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes your function to access any other Amazon Web Services (AWS)
37 resources. You may use the bare ARN if the role belongs to the same AWS account.
38 - Required when O(state=present).
39 type: str
40 handler:
41 description:
42 - The function within your code that Lambda calls to begin execution.
43 type: str
44 zip_file:
45 description:
46 - A .zip file containing your deployment package
47 - If O(state=present) then either O(zip_file) or O(s3_bucket) must be present.
48 aliases: [ 'src' ]
49 type: str
50 s3_bucket:
51 description:
52 - Amazon S3 bucket name where the .zip file containing your deployment package is stored.
53 - If O(state=present) then either O(zip_file) or O(s3_bucket) must be present.
54 - O(s3_bucket) and O(s3_key) are required together.
55 type: str
56 s3_key:
57 description:
58 - The Amazon S3 object (the deployment package) key name you want to upload.
59 - O(s3_bucket) and O(s3_key) are required together.
60 type: str
61 s3_object_version:
62 description:
63 - The Amazon S3 object (the deployment package) version you want to upload.
64 type: str
65 description:
66 description:
67 - A short, user-defined function description. Lambda does not use this value. Assign a meaningful description as you see fit.
68 type: str
69 default: ''
70 timeout:
71 description:
72 - The function maximum execution time in seconds after which Lambda should terminate the function.
73 default: 3
74 type: int
75 memory_size:
76 description:
77 - The amount of memory, in MB, your Lambda function is given.
78 default: 128
79 type: int
80 vpc_subnet_ids:
81 description:
82 - List of subnet IDs to run Lambda function in.
83 - Use this option if you need to access resources in your VPC. Leave empty if you don't want to run the function in a VPC.
84 - If set, O(vpc_security_group_ids) must also be set.
85 type: list
86 elements: str
87 vpc_security_group_ids:
88 description:
89 - List of VPC security group IDs to associate with the Lambda function.
90 - Required when O(vpc_subnet_ids) is used.
91 type: list
92 elements: str
93 environment_variables:
94 description:
95 - A dictionary of environment variables the Lambda function is given.
96 type: dict
97 dead_letter_arn:
98 description:
99 - The parent object that contains the target Amazon Resource Name (ARN) of an Amazon SQS queue or Amazon SNS topic.
100 type: str
101 tracing_mode:
102 description:
103 - Set mode to 'Active' to sample and trace incoming requests with AWS X-Ray. Turned off (set to 'PassThrough') by default.
104 choices: ['Active', 'PassThrough']
105 type: str
106 kms_key_arn:
107 description:
108 - The KMS key ARN used to encrypt the function's environment variables.
109 type: str
110 version_added: 3.3.0
111 version_added_collection: community.aws
112 architecture:
113 description:
114 - The instruction set architecture that the function supports.
115 - Requires one of O(s3_bucket) or O(zip_file).
116 type: str
117 choices: ['x86_64', 'arm64']
118 aliases: ['architectures']
119 version_added: 5.0.0
120 layers:
121 description:
122 - A list of function layers to add to the function's execution environment.
123 - Specify each layer by its ARN, including the version.
124 suboptions:
125 layer_version_arn:
126 description:
127 - The ARN of the layer version.
128 - Mutually exclusive with O(layers.layer_name).
129 type: str
130 layer_name:
131 description:
132 - The name or Amazon Resource Name (ARN) of the layer.
133 - Mutually exclusive with O(layers.layer_version_arn).
134 type: str
135 aliases: ['layer_arn']
136 version:
137 description:
138 - The version number.
139 - Required when O(layers.layer_name) is provided, ignored if not.
140 type: int
141 aliases: ['layer_version']
142 type: list
143 elements: dict
144 version_added: 5.5.0
145 image_uri:
146 description:
147 - The Amazon ECR URI of the image to use.
148 - Required (alternative to runtime zip_file and s3_bucket) when creating a function.
149 - Required when O(state=present).
150 type: str
151 version_added: 7.3.0
152 author:
153 - 'Steyn Huizinga (@steynovich)'
154 extends_documentation_fragment:
155 - amazon.aws.common.modules
156 - amazon.aws.region.modules
157 - amazon.aws.tags
158 - amazon.aws.boto3
159 """
160
161 EXAMPLES = r"""
162 # Create Lambda functions
163 - name: looped creation
164 amazon.aws.lambda:
165 name: '{{ item.name }}'
166 state: present
167 zip_file: '{{ item.zip_file }}'
168 runtime: 'python2.7'
169 role: 'arn:aws:iam::123456789012:role/lambda_basic_execution'
170 handler: 'hello_python.my_handler'
171 vpc_subnet_ids:
172 - subnet-123abcde
173 - subnet-edcba321
174 vpc_security_group_ids:
175 - sg-123abcde
176 - sg-edcba321
177 environment_variables: '{{ item.env_vars }}'
178 tags:
179 key1: 'value1'
180 loop:
181 - name: HelloWorld
182 zip_file: hello-code.zip
183 env_vars:
184 key1: "first"
185 key2: "second"
186 - name: ByeBye
187 zip_file: bye-code.zip
188 env_vars:
189 key1: "1"
190 key2: "2"
191
192 # To remove previously added tags pass an empty dict
193 - name: remove tags
194 amazon.aws.lambda:
195 name: 'Lambda function'
196 state: present
197 zip_file: 'code.zip'
198 runtime: 'python2.7'
199 role: 'arn:aws:iam::123456789012:role/lambda_basic_execution'
200 handler: 'hello_python.my_handler'
201 tags: {}
202
203 # Basic Lambda function deletion
204 - name: Delete Lambda functions HelloWorld and ByeBye
205 amazon.aws.lambda:
206 name: '{{ item }}'
207 state: absent
208 loop:
209 - HelloWorld
210 - ByeBye
211
212 # Create Lambda functions with function layers
213 - name: looped creation
214 amazon.aws.lambda:
215 name: 'HelloWorld'
216 state: present
217 zip_file: 'hello-code.zip'
218 runtime: 'python2.7'
219 role: 'arn:aws:iam::123456789012:role/lambda_basic_execution'
220 handler: 'hello_python.my_handler'
221 layers:
222 - layer_version_arn: 'arn:aws:lambda:us-east-1:123456789012:layer:python27-env:7'
223 """
224
225 RETURN = r"""
226 code:
227 description: The lambda function's code returned by get_function in boto3.
228 returned: success
229 type: dict
230 contains:
231 location:
232 description:
233 - The presigned URL you can use to download the function's .zip file that you previously uploaded.
234 - The URL is valid for up to 10 minutes.
235 returned: success
236 type: str
237 sample: 'https://prod-04-2014-tasks.s3.us-east-1.amazonaws.com/snapshots/sample'
238 repository_type:
239 description: The repository from which you can download the function.
240 returned: success
241 type: str
242 sample: 'S3'
243 configuration:
244 description: The Lambda function's configuration metadata returned by get_function in boto3.
245 returned: success
246 type: dict
247 contains:
248 architectures:
249 description: The architectures supported by the function.
250 type: list
251 elements: str
252 sample: ['arm64']
253 code_sha256:
254 description: The SHA256 hash of the function's deployment package.
255 returned: success
256 type: str
257 sample: 'zOAGfF5JLFuzZoSNirUtOrQp+S341IOA3BcoXXoaIaU='
258 code_size:
259 description: The size of the function's deployment package in bytes.
260 returned: success
261 type: int
262 sample: 123
263 dead_letter_config:
264 description: The function's dead letter queue.
265 returned: when the function has a dead letter queue configured
266 type: dict
267 sample: { 'target_arn': arn:aws:lambda:us-east-1:123456789012:function:myFunction:1 }
268 contains:
269 target_arn:
270 description: The ARN of an SQS queue or SNS topic.
271 returned: when the function has a dead letter queue configured
272 type: str
273 sample: arn:aws:lambda:us-east-1:123456789012:function:myFunction:1
274 description:
275 description: The function's description.
276 returned: success
277 type: str
278 sample: 'My function'
279 environment:
280 description: The function's environment variables.
281 returned: when environment variables exist
282 type: dict
283 contains:
284 variables:
285 description: Environment variable key-value pairs.
286 returned: when environment variables exist
287 type: dict
288 sample: {'key': 'value'}
289 error:
290 description: Error message for environment variables that could not be applied.
291 returned: when there is an error applying environment variables
292 type: dict
293 contains:
294 error_code:
295 description: The error code.
296 returned: when there is an error applying environment variables
297 type: str
298 message:
299 description: The error message.
300 returned: when there is an error applying environment variables
301 type: str
302 function_arn:
303 description: The function's Amazon Resource Name (ARN).
304 returned: on success
305 type: str
306 sample: 'arn:aws:lambda:us-east-1:123456789012:function:myFunction:1'
307 function_name:
308 description: The function's name.
309 returned: on success
310 type: str
311 sample: 'myFunction'
312 handler:
313 description: The function Lambda calls to begin executing your function.
314 returned: on success
315 type: str
316 sample: 'index.handler'
317 last_modified:
318 description: The date and time that the function was last updated, in ISO-8601 format (YYYY-MM-DDThh:mm:ssTZD).
319 returned: on success
320 type: str
321 sample: '2017-08-01T00:00:00.000+0000'
322 memory_size:
323 description: The memory allocated to the function.
324 returned: on success
325 type: int
326 sample: 128
327 revision_id:
328 description: The latest updated revision of the function or alias.
329 returned: on success
330 type: str
331 sample: 'a2x9886d-d48a-4a0c-ab64-82abc005x80c'
332 role:
333 description: The function's execution role.
334 returned: on success
335 type: str
336 sample: 'arn:aws:iam::123456789012:role/lambda_basic_execution'
337 runtime:
338 description: The funtime environment for the Lambda function.
339 returned: on success
340 type: str
341 sample: 'nodejs6.10'
342 tracing_config:
343 description: The function's AWS X-Ray tracing configuration.
344 returned: on success
345 type: dict
346 sample: { 'mode': 'Active' }
347 contains:
348 mode:
349 description: The tracing mode.
350 returned: on success
351 type: str
352 sample: 'Active'
353 timeout:
354 description: The amount of time that Lambda allows a function to run before terminating it.
355 returned: on success
356 type: int
357 sample: 3
358 version:
359 description: The version of the Lambda function.
360 returned: on success
361 type: str
362 sample: '1'
363 vpc_config:
364 description: The function's networking configuration.
365 returned: on success
366 type: dict
367 sample: {
368 'security_group_ids': [],
369 'subnet_ids': [],
370 'vpc_id': '123'
371 }
372 layers:
373 description: The function's layers.
374 returned: on success
375 version_added: 5.5.0
376 type: complex
377 contains:
378 arn:
379 description: The Amazon Resource Name (ARN) of the function layer.
380 returned: always
381 type: str
382 sample: active
383 code_size:
384 description: The size of the layer archive in bytes.
385 returned: always
386 type: str
387 signing_profile_version_arn:
388 description: The Amazon Resource Name (ARN) for a signing profile version.
389 returned: always
390 type: str
391 signing_job_arn:
392 description: The Amazon Resource Name (ARN) of a signing job.
393 returned: always
394 type: str
395 """
396
397 import base64
398 import hashlib
399 import re
400 import traceback
401 from collections import Counter
402
403 try:
404 from botocore.exceptions import BotoCoreError
405 from botocore.exceptions import ClientError
406 from botocore.exceptions import WaiterError
407 except ImportError:
408 pass # protected by AnsibleAWSModule
409
410 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
411
412 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
413 from ansible_collections.amazon.aws.plugins.module_utils.iam import get_aws_account_info
414 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
415 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
416 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
417
418
419 def get_current_function(connection, function_name, qualifier=None):
420 try:
421 if qualifier is not None:
422 return connection.get_function(FunctionName=function_name, Qualifier=qualifier, aws_retry=True)
423 return connection.get_function(FunctionName=function_name, aws_retry=True)
424 except is_boto3_error_code("ResourceNotFoundException"):
425 return None
426
427
428 def get_layer_version_arn(module, connection, layer_name, version_number):
429 try:
430 layer_versions = connection.list_layer_versions(LayerName=layer_name, aws_retry=True)["LayerVersions"]
431 for v in layer_versions:
432 if v["Version"] == version_number:
433 return v["LayerVersionArn"]
434 module.fail_json(msg=f"Unable to find version {version_number} from Lambda layer {layer_name}")
435 except is_boto3_error_code("ResourceNotFoundException"):
436 module.fail_json(msg=f"Lambda layer {layer_name} not found")
437
438
439 def sha256sum(filename):
440 hasher = hashlib.sha256()
441 with open(filename, "rb") as f:
442 hasher.update(f.read())
443
444 code_hash = hasher.digest()
445 code_b64 = base64.b64encode(code_hash)
446 hex_digest = code_b64.decode("utf-8")
447
448 return hex_digest
449
450
451 def set_tag(client, module, tags, function, purge_tags):
452 if tags is None:
453 return False
454
455 changed = False
456 arn = function["Configuration"]["FunctionArn"]
457
458 try:
459 current_tags = client.list_tags(Resource=arn, aws_retry=True).get("Tags", {})
460 except (BotoCoreError, ClientError) as e:
461 module.fail_json_aws(e, msg="Unable to list tags")
462
463 tags_to_add, tags_to_remove = compare_aws_tags(current_tags, tags, purge_tags=purge_tags)
464
465 if not tags_to_remove and not tags_to_add:
466 return False
467
468 if module.check_mode:
469 return True
470
471 try:
472 if tags_to_remove:
473 client.untag_resource(
474 Resource=arn,
475 TagKeys=tags_to_remove,
476 aws_retry=True,
477 )
478 changed = True
479
480 if tags_to_add:
481 client.tag_resource(
482 Resource=arn,
483 Tags=tags_to_add,
484 aws_retry=True,
485 )
486 changed = True
487
488 except (BotoCoreError, ClientError) as e:
489 module.fail_json_aws(e, msg=f"Unable to tag resource {arn}")
490
491 return changed
492
493
494 def wait_for_lambda(client, module, name):
495 try:
496 client_active_waiter = client.get_waiter("function_active")
497 client_updated_waiter = client.get_waiter("function_updated")
498 client_active_waiter.wait(FunctionName=name)
499 client_updated_waiter.wait(FunctionName=name)
500 except WaiterError as e:
501 module.fail_json_aws(e, msg="Timeout while waiting on lambda to finish updating")
502 except (ClientError, BotoCoreError) as e:
503 module.fail_json_aws(e, msg="Failed while waiting on lambda to finish updating")
504
505
506 def format_response(response):
507 tags = response.get("Tags", {})
508 result = camel_dict_to_snake_dict(response)
509 # Lambda returns a dict rather than the usual boto3 list of dicts
510 result["tags"] = tags
511 return result
512
513
514 def _zip_args(zip_file, current_config, ignore_checksum):
515 if not zip_file:
516 return {}
517
518 # If there's another change that needs to happen, we always re-upload the code
519 if not ignore_checksum:
520 local_checksum = sha256sum(zip_file)
521 remote_checksum = current_config.get("CodeSha256", "")
522 if local_checksum == remote_checksum:
523 return {}
524
525 with open(zip_file, "rb") as f:
526 zip_content = f.read()
527 return {"ZipFile": zip_content}
528
529
530 def _s3_args(s3_bucket, s3_key, s3_object_version):
531 if not s3_bucket:
532 return {}
533 if not s3_key:
534 return {}
535
536 code = {"S3Bucket": s3_bucket, "S3Key": s3_key}
537 if s3_object_version:
538 code.update({"S3ObjectVersion": s3_object_version})
539
540 return code
541
542
543 def _image_args(image_uri):
544 if not image_uri:
545 return {}
546
547 code = {"ImageUri": image_uri}
548 return code
549
550
551 def _code_args(module, current_config):
552 s3_bucket = module.params.get("s3_bucket")
553 s3_key = module.params.get("s3_key")
554 s3_object_version = module.params.get("s3_object_version")
555 zip_file = module.params.get("zip_file")
556 architectures = module.params.get("architecture")
557 image_uri = module.params.get("image_uri")
558
559 code_kwargs = {}
560
561 if architectures and current_config.get("Architectures", None) != [architectures]:
562 module.warn("Arch Change")
563 code_kwargs.update({"Architectures": [architectures]})
564
565 try:
566 code_kwargs.update(_zip_args(zip_file, current_config, bool(code_kwargs)))
567 except IOError as e:
568 module.fail_json(msg=str(e), exception=traceback.format_exc())
569
570 code_kwargs.update(_s3_args(s3_bucket, s3_key, s3_object_version))
571 code_kwargs.update(_image_args(image_uri))
572
573 if not code_kwargs:
574 return {}
575
576 if not architectures and current_config.get("Architectures", None):
577 code_kwargs.update({"Architectures": current_config.get("Architectures", None)})
578
579 return code_kwargs
580
581
582 def main():
583 argument_spec = dict(
584 name=dict(required=True),
585 state=dict(default="present", choices=["present", "absent"]),
586 image_uri=dict(),
587 runtime=dict(),
588 role=dict(),
589 handler=dict(),
590 zip_file=dict(aliases=["src"]),
591 s3_bucket=dict(),
592 s3_key=dict(no_log=False),
593 s3_object_version=dict(),
594 description=dict(default=""),
595 timeout=dict(type="int", default=3),
596 memory_size=dict(type="int", default=128),
597 vpc_subnet_ids=dict(type="list", elements="str"),
598 vpc_security_group_ids=dict(type="list", elements="str"),
599 environment_variables=dict(type="dict"),
600 dead_letter_arn=dict(),
601 kms_key_arn=dict(type="str", no_log=False),
602 tracing_mode=dict(choices=["Active", "PassThrough"]),
603 architecture=dict(choices=["x86_64", "arm64"], type="str", aliases=["architectures"]),
604 tags=dict(type="dict", aliases=["resource_tags"]),
605 purge_tags=dict(type="bool", default=True),
606 layers=dict(
607 type="list",
608 elements="dict",
609 options=dict(
610 layer_version_arn=dict(type="str"),
611 layer_name=dict(type="str", aliases=["layer_arn"]),
612 version=dict(type="int", aliases=["layer_version"]),
613 ),
614 required_together=[["layer_name", "version"]],
615 required_one_of=[["layer_version_arn", "layer_name"]],
616 mutually_exclusive=[["layer_name", "layer_version_arn"], ["version", "layer_version_arn"]],
617 ),
618 )
619
620 mutually_exclusive = [
621 ["zip_file", "s3_key"],
622 ["zip_file", "s3_bucket"],
623 ["zip_file", "s3_object_version"],
624 ["image_uri", "zip_file"],
625 ["image_uri", "runtime"],
626 ["image_uri", "handler"],
627 ["image_uri", "s3_key"],
628 ["image_uri", "s3_bucket"],
629 ["image_uri", "s3_object_version"],
630 ]
631
632 required_together = [
633 ["s3_key", "s3_bucket"],
634 ["vpc_subnet_ids", "vpc_security_group_ids"],
635 ["runtime", "handler"],
636 ]
637
638 required_if = [
639 ["state", "present", ["role"]],
640 ["state", "present", ["runtime", "image_uri"], True],
641 ["architecture", "x86_64", ["zip_file", "s3_bucket", "image_uri"], True],
642 ["architecture", "arm64", ["zip_file", "s3_bucket", "image_uri"], True],
643 ]
644
645 module = AnsibleAWSModule(
646 argument_spec=argument_spec,
647 supports_check_mode=True,
648 mutually_exclusive=mutually_exclusive,
649 required_together=required_together,
650 required_if=required_if,
651 )
652
653 name = module.params.get("name")
654 state = module.params.get("state").lower()
655 runtime = module.params.get("runtime")
656 role = module.params.get("role")
657 handler = module.params.get("handler")
658 description = module.params.get("description")
659 timeout = module.params.get("timeout")
660 memory_size = module.params.get("memory_size")
661 vpc_subnet_ids = module.params.get("vpc_subnet_ids")
662 vpc_security_group_ids = module.params.get("vpc_security_group_ids")
663 environment_variables = module.params.get("environment_variables")
664 dead_letter_arn = module.params.get("dead_letter_arn")
665 tracing_mode = module.params.get("tracing_mode")
666 tags = module.params.get("tags")
667 purge_tags = module.params.get("purge_tags")
668 kms_key_arn = module.params.get("kms_key_arn")
669 image_uri = module.params.get("image_uri")
670 layers = []
671
672 check_mode = module.check_mode
673 changed = False
674
675 try:
676 client = module.client("lambda", retry_decorator=AWSRetry.jittered_backoff())
677 except (ClientError, BotoCoreError) as e:
678 module.fail_json_aws(e, msg="Trying to connect to AWS")
679
680 if state == "present":
681 if re.match(r"^arn:aws(-([a-z\-]+))?:iam", role):
682 role_arn = role
683 else:
684 # get account ID and assemble ARN
685 account_id, partition = get_aws_account_info(module)
686 role_arn = f"arn:{partition}:iam::{account_id}:role/{role}"
687
688 # create list of layer version arn
689 if module.params.get("layers"):
690 for layer in module.params.get("layers"):
691 layer_version_arn = layer.get("layer_version_arn")
692 if layer_version_arn is None:
693 layer_version_arn = get_layer_version_arn(
694 module, client, layer.get("layer_name"), layer.get("version")
695 )
696 layers.append(layer_version_arn)
697
698 # Get function configuration if present, False otherwise
699 current_function = get_current_function(client, name)
700
701 # Update existing Lambda function
702 if state == "present" and current_function:
703 # Get current state
704 current_config = current_function["Configuration"]
705 current_version = None
706
707 # Update function configuration
708 func_kwargs = {"FunctionName": name}
709
710 # Update configuration if needed
711 if role_arn and current_config["Role"] != role_arn:
712 func_kwargs.update({"Role": role_arn})
713 if handler and current_config["Handler"] != handler:
714 func_kwargs.update({"Handler": handler})
715 if description and current_config["Description"] != description:
716 func_kwargs.update({"Description": description})
717 if timeout and current_config["Timeout"] != timeout:
718 func_kwargs.update({"Timeout": timeout})
719 if memory_size and current_config["MemorySize"] != memory_size:
720 func_kwargs.update({"MemorySize": memory_size})
721 if image_uri is not None and current_config["PackageType"] != "Image":
722 func_kwargs.update({"PackageType": "Image"})
723 if runtime and current_config["Runtime"] != runtime:
724 func_kwargs.update({"Runtime": runtime})
725 if (environment_variables is not None) and (
726 current_config.get("Environment", {}).get("Variables", {}) != environment_variables
727 ):
728 func_kwargs.update({"Environment": {"Variables": environment_variables}})
729 if dead_letter_arn is not None:
730 if current_config.get("DeadLetterConfig"):
731 if current_config["DeadLetterConfig"]["TargetArn"] != dead_letter_arn:
732 func_kwargs.update({"DeadLetterConfig": {"TargetArn": dead_letter_arn}})
733 else:
734 if dead_letter_arn != "":
735 func_kwargs.update({"DeadLetterConfig": {"TargetArn": dead_letter_arn}})
736 if tracing_mode and (current_config.get("TracingConfig", {}).get("Mode", "PassThrough") != tracing_mode):
737 func_kwargs.update({"TracingConfig": {"Mode": tracing_mode}})
738 if kms_key_arn:
739 func_kwargs.update({"KMSKeyArn": kms_key_arn})
740
741 # If VPC configuration is desired
742 if vpc_subnet_ids:
743 if "VpcConfig" in current_config:
744 # Compare VPC config with current config
745 current_vpc_subnet_ids = current_config["VpcConfig"]["SubnetIds"]
746 current_vpc_security_group_ids = current_config["VpcConfig"]["SecurityGroupIds"]
747
748 subnet_net_id_changed = sorted(vpc_subnet_ids) != sorted(current_vpc_subnet_ids)
749 vpc_security_group_ids_changed = sorted(vpc_security_group_ids) != sorted(
750 current_vpc_security_group_ids
751 )
752
753 if "VpcConfig" not in current_config or subnet_net_id_changed or vpc_security_group_ids_changed:
754 new_vpc_config = {"SubnetIds": vpc_subnet_ids, "SecurityGroupIds": vpc_security_group_ids}
755 func_kwargs.update({"VpcConfig": new_vpc_config})
756 else:
757 # No VPC configuration is desired, assure VPC config is empty when present in current config
758 if "VpcConfig" in current_config and current_config["VpcConfig"].get("VpcId"):
759 func_kwargs.update({"VpcConfig": {"SubnetIds": [], "SecurityGroupIds": []}})
760
761 # Check layers
762 if layers:
763 # compare two lists to see if the target layers are equal to the current
764 current_layers = current_config.get("Layers", [])
765 if Counter(layers) != Counter((f["Arn"] for f in current_layers)):
766 func_kwargs.update({"Layers": layers})
767
768 # Upload new configuration if configuration has changed
769 if len(func_kwargs) > 1:
770 if not check_mode:
771 wait_for_lambda(client, module, name)
772
773 try:
774 if not check_mode:
775 response = client.update_function_configuration(aws_retry=True, **func_kwargs)
776 current_version = response["Version"]
777 changed = True
778 except (BotoCoreError, ClientError) as e:
779 module.fail_json_aws(e, msg="Trying to update lambda configuration")
780
781 # Tag Function
782 if tags is not None:
783 if set_tag(client, module, tags, current_function, purge_tags):
784 changed = True
785
786 code_kwargs = _code_args(module, current_config)
787 if code_kwargs:
788 # Update code configuration
789 code_kwargs.update({"FunctionName": name, "Publish": True})
790
791 if not check_mode:
792 wait_for_lambda(client, module, name)
793
794 try:
795 if not check_mode:
796 response = client.update_function_code(aws_retry=True, **code_kwargs)
797 current_version = response["Version"]
798 changed = True
799 except (BotoCoreError, ClientError) as e:
800 module.fail_json_aws(e, msg="Trying to upload new code")
801
802 # Describe function code and configuration
803 response = get_current_function(client, name, qualifier=current_version)
804 if not response:
805 module.fail_json(msg="Unable to get function information after updating")
806 response = format_response(response)
807 # We're done
808 # "ZipFile" attribute contains non UTF-8 data. Ansible considers it an error
809 # starting with version 2.18. Removing it from the output avoids the error.
810 code_kwargs.pop("ZipFile", None)
811 module.exit_json(changed=changed, code_kwargs=code_kwargs, func_kwargs=func_kwargs, **response)
812
813 # Function doesn't exist, create new Lambda function
814 elif state == "present":
815 func_kwargs = {
816 "FunctionName": name,
817 "Publish": True,
818 "Role": role_arn,
819 "Timeout": timeout,
820 "MemorySize": memory_size,
821 }
822
823 code = _code_args(module, {})
824 if not code:
825 module.fail_json(msg="Either S3 object or path to zipfile required")
826 if "Architectures" in code:
827 func_kwargs.update({"Architectures": code.pop("Architectures")})
828 func_kwargs.update({"Code": code})
829
830 if description is not None:
831 func_kwargs.update({"Description": description})
832
833 if image_uri is not None:
834 func_kwargs.update({"PackageType": "Image"})
835
836 if runtime is not None:
837 func_kwargs.update({"Runtime": runtime})
838
839 if handler is not None:
840 func_kwargs.update({"Handler": handler})
841
842 if environment_variables:
843 func_kwargs.update({"Environment": {"Variables": environment_variables}})
844
845 if dead_letter_arn:
846 func_kwargs.update({"DeadLetterConfig": {"TargetArn": dead_letter_arn}})
847
848 if tracing_mode:
849 func_kwargs.update({"TracingConfig": {"Mode": tracing_mode}})
850
851 if kms_key_arn:
852 func_kwargs.update({"KMSKeyArn": kms_key_arn})
853
854 # If VPC configuration is given
855 if vpc_subnet_ids:
856 func_kwargs.update({"VpcConfig": {"SubnetIds": vpc_subnet_ids, "SecurityGroupIds": vpc_security_group_ids}})
857
858 # Layers
859 if layers:
860 func_kwargs.update({"Layers": layers})
861
862 # Tag Function
863 if tags:
864 func_kwargs.update({"Tags": tags})
865
866 # Function would have been created if not check mode
867 if check_mode:
868 module.exit_json(changed=True)
869
870 # Finally try to create function
871 current_version = None
872 try:
873 response = client.create_function(aws_retry=True, **func_kwargs)
874 current_version = response["Version"]
875 changed = True
876 except (BotoCoreError, ClientError) as e:
877 module.fail_json_aws(e, msg="Trying to create function")
878
879 response = get_current_function(client, name, qualifier=current_version)
880 if not response:
881 module.fail_json(msg="Unable to get function information after creating")
882 response = format_response(response)
883 module.exit_json(changed=changed, **response)
884
885 # Delete existing Lambda function
886 if state == "absent" and current_function:
887 try:
888 if not check_mode:
889 client.delete_function(FunctionName=name, aws_retry=True)
890 changed = True
891 except (BotoCoreError, ClientError) as e:
892 module.fail_json_aws(e, msg="Trying to delete Lambda function")
893
894 module.exit_json(changed=changed)
895
896 # Function already absent, do nothing
897 elif state == "absent":
898 module.exit_json(changed=changed)
899
900
901 if __name__ == "__main__":
902 main()