Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/lambda_layer.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: lambda_layer
10 version_added: 5.5.0
11 short_description: Creates an AWS Lambda layer or deletes an AWS Lambda layer version
12 description:
13 - This module allows the management of AWS Lambda functions aliases via the Ansible
14 - Creates an Lambda layer from a ZIP archive.
15 Each time you call this module with the same layer name, a new version is created.
16 - Deletes a version of an Lambda layer.
17 author: "Aubin Bikouo (@abikouo)"
18 options:
19 state:
20 description:
21 - Determines if an Lambda layer should be created, or deleted. When set to V(present), an Lambda layer version will be
22 created. If set to V(absent), an existing Lambda layer version will be deleted.
23 type: str
24 default: present
25 choices: [ absent, present ]
26 name:
27 description:
28 - The name or Amazon Resource Name (ARN) of the Lambda layer.
29 type: str
30 required: true
31 aliases:
32 - layer_name
33 description:
34 description:
35 - The description of the version.
36 - Ignored when O(state=absent).
37 - Mutually exclusive with O(version).
38 type: str
39 content:
40 description:
41 - The function layer archive.
42 - Required when O(state=present).
43 - Ignored when O(state=absent).
44 - Mutually exclusive with o(version).
45 type: dict
46 suboptions:
47 s3_bucket:
48 description:
49 - The Amazon S3 bucket of the layer archive.
50 type: str
51 s3_key:
52 description:
53 - The Amazon S3 key of the layer archive.
54 type: str
55 s3_object_version:
56 description:
57 - For versioned objects, the version of the layer archive object to use.
58 type: str
59 zip_file:
60 description:
61 - Path to the base64-encoded file of the layer archive.
62 type: path
63 compatible_runtimes:
64 description:
65 - A list of compatible function runtimes.
66 - Ignored when O(state=absent).
67 - Mutually exclusive with O(version).
68 type: list
69 elements: str
70 license_info:
71 description:
72 - The layer's software license. It can be any of an SPDX license identifier,
73 the URL of a license hosted on the internet or the full text of the license.
74 - Ignored when O(state=absent).
75 - Mutually exclusive with O(version).
76 type: str
77 compatible_architectures:
78 description:
79 - A list of compatible instruction set architectures. For example, x86_64.
80 - Mutually exclusive with O(version).
81 type: list
82 elements: str
83 version:
84 description:
85 - The version number of the layer to delete.
86 - Set to V(-1) to delete all versions for the specified layer name.
87 - Required when O(state=absent).
88 - Ignored when O(state=present).
89 - Mutually exclusive with O(description), O(content), O(compatible_runtimes),
90 O(license_info), O(compatible_architectures).
91 type: int
92 extends_documentation_fragment:
93 - amazon.aws.common.modules
94 - amazon.aws.region.modules
95 - amazon.aws.boto3
96 """
97
98 EXAMPLES = r"""
99 ---
100 # Create a new Python library layer version from a zip archive located into a S3 bucket
101 - name: Create a new python library layer
102 amazon.aws.lambda_layer:
103 state: present
104 name: sample-layer
105 description: 'My Python layer'
106 content:
107 s3_bucket: 'lambda-layers-us-west-2-123456789012'
108 s3_key: 'python_layer.zip'
109 compatible_runtimes:
110 - python3.6
111 - python3.7
112 license_info: MIT
113 compatible_architectures:
114 - x86_64
115
116 # Create a layer version from a zip in the local filesystem
117 - name: Create a new layer from a zip in the local filesystem
118 amazon.aws.lambda_layer:
119 state: present
120 name: sample-layer
121 description: 'My Python layer'
122 content:
123 zip_file: 'python_layer.zip'
124 compatible_runtimes:
125 - python3.6
126 - python3.7
127 license_info: MIT
128 compatible_architectures:
129 - x86_64
130
131 # Delete a layer version
132 - name: Delete a layer version
133 amazon.aws.lambda_layer:
134 state: absent
135 name: sample-layer
136 version: 2
137
138 # Delete all versions of test-layer
139 - name: Delete all versions
140 amazon.aws.lambda_layer:
141 state: absent
142 name: test-layer
143 version: -1
144 """
145
146 RETURN = r"""
147 layer_version:
148 description: Info about the layer version that was created or deleted.
149 returned: always
150 type: list
151 elements: dict
152 contains:
153 content:
154 description: Details about the layer version.
155 returned: O(state=present)
156 type: complex
157 contains:
158 location:
159 description: A link to the layer archive in Amazon S3 that is valid for 10 minutes.
160 returned: O(state=present)
161 type: str
162 sample: "https://awslambda-us-east-1-layers.s3.us-east-1.amazonaws.com/snapshots/123456789012/pylayer-9da91deffd3b4941b8baeeae5daeffe4"
163 code_sha256:
164 description: The SHA-256 hash of the layer archive.
165 returned: O(state=present)
166 type: str
167 sample: "VLluleJZ3HTwDrdYolSMrS+8iPwEkcoXXaegjXf+dmc="
168 code_size:
169 description: The size of the layer archive in bytes.
170 returned: O(state=present)
171 type: int
172 sample: 9473675
173 signing_profile_version_arn:
174 description: The Amazon Resource Name (ARN) for a signing profile version.
175 returned: When a signing profile is defined
176 type: str
177 signing_job_arn:
178 description: The Amazon Resource Name (ARN) of a signing job.
179 returned: When a signing profile is defined
180 type: str
181 layer_arn:
182 description: The ARN of the layer.
183 returned: if the layer version exists or has been created
184 type: str
185 sample: "arn:aws:lambda:eu-west-2:123456789012:layer:pylayer"
186 layer_version_arn:
187 description: The ARN of the layer version.
188 returned: if the layer version exists or has been created
189 type: str
190 sample: "arn:aws:lambda:eu-west-2:123456789012:layer:pylayer:2"
191 description:
192 description: The description of the version.
193 returned: O(state=present)
194 type: str
195 compatible_runtimes:
196 description: A list of compatible runtimes.
197 returned: if it was defined for the layer version.
198 type: list
199 sample: ["python3.7"]
200 created_date:
201 description: The date that the layer version was created, in ISO-8601 format (YYYY-MM-DDThh:mm:ss.sTZD).
202 returned: if the layer version exists or has been created
203 type: str
204 sample: "2022-09-28T14:27:35.866+0000"
205 version:
206 description: The version number.
207 returned: if the layer version exists or has been created
208 type: int
209 sample: 1
210 license_info:
211 description: The layer's software license.
212 returned: if it was defined for the layer version.
213 type: str
214 sample: "GPL-3.0-only"
215 compatible_architectures:
216 description: A list of compatible instruction set architectures.
217 returned: if it was defined for the layer version.
218 type: list
219 """
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
228 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
229 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
230
231
232 @AWSRetry.jittered_backoff()
233 def _list_layer_versions(client, **params):
234 paginator = client.get_paginator("list_layer_versions")
235 return paginator.paginate(**params).build_full_result()
236
237
238 class LambdaLayerFailure(Exception):
239 def __init__(self, exc, msg):
240 self.exc = exc
241 self.msg = msg
242 super().__init__(self)
243
244
245 def list_layer_versions(lambda_client, name):
246 try:
247 layer_versions = _list_layer_versions(lambda_client, LayerName=name)["LayerVersions"]
248 return [camel_dict_to_snake_dict(layer) for layer in layer_versions]
249 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
250 raise LambdaLayerFailure(e, f"Unable to list layer versions for name {name}")
251
252
253 def create_layer_version(lambda_client, params, check_mode=False):
254 if check_mode:
255 return {"msg": "Create operation skipped - running in check mode", "changed": True}
256
257 opt = {"LayerName": params.get("name"), "Content": {}}
258 keys = [
259 ("description", "Description"),
260 ("compatible_runtimes", "CompatibleRuntimes"),
261 ("license_info", "LicenseInfo"),
262 ("compatible_architectures", "CompatibleArchitectures"),
263 ]
264 for k, d in keys:
265 if params.get(k) is not None:
266 opt[d] = params.get(k)
267
268 # Read zip file if any
269 zip_file = params["content"].get("zip_file")
270 if zip_file is not None:
271 with open(zip_file, "rb") as zf:
272 opt["Content"]["ZipFile"] = zf.read()
273 else:
274 opt["Content"]["S3Bucket"] = params["content"].get("s3_bucket")
275 opt["Content"]["S3Key"] = params["content"].get("s3_key")
276 if params["content"].get("s3_object_version") is not None:
277 opt["Content"]["S3ObjectVersion"] = params["content"].get("s3_object_version")
278
279 try:
280 layer_version = lambda_client.publish_layer_version(**opt)
281 layer_version.pop("ResponseMetadata", None)
282 return {"changed": True, "layer_versions": [camel_dict_to_snake_dict(layer_version)]}
283 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
284 raise LambdaLayerFailure(e, "Failed to publish a new layer version (check that you have required permissions).")
285
286
287 def delete_layer_version(lambda_client, params, check_mode=False):
288 name = params.get("name")
289 version = params.get("version")
290 layer_versions = list_layer_versions(lambda_client, name)
291 deleted_versions = []
292 changed = False
293 for layer in layer_versions:
294 if version == -1 or layer["version"] == version:
295 deleted_versions.append(layer)
296 changed = True
297 if not check_mode:
298 try:
299 lambda_client.delete_layer_version(LayerName=name, VersionNumber=layer["version"])
300 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
301 raise LambdaLayerFailure(
302 e, f"Failed to delete layer version LayerName={name}, VersionNumber={version}."
303 )
304 return {"changed": changed, "layer_versions": deleted_versions}
305
306
307 def execute_module(module, lambda_client):
308 try:
309 state = module.params.get("state")
310 f_operation = create_layer_version
311 if state == "absent":
312 f_operation = delete_layer_version
313
314 module.exit_json(**f_operation(lambda_client, module.params, module.check_mode))
315 except LambdaLayerFailure as e:
316 module.fail_json_aws(e.exc, msg=e.msg)
317
318
319 def main():
320 argument_spec = dict(
321 state=dict(type="str", choices=["present", "absent"], default="present"),
322 name=dict(type="str", required=True, aliases=["layer_name"]),
323 description=dict(type="str"),
324 content=dict(
325 type="dict",
326 options=dict(
327 s3_bucket=dict(type="str"),
328 s3_key=dict(type="str", no_log=False),
329 s3_object_version=dict(type="str"),
330 zip_file=dict(type="path"),
331 ),
332 required_together=[["s3_bucket", "s3_key"]],
333 required_one_of=[["s3_bucket", "zip_file"]],
334 mutually_exclusive=[["s3_bucket", "zip_file"]],
335 ),
336 compatible_runtimes=dict(type="list", elements="str"),
337 license_info=dict(type="str"),
338 compatible_architectures=dict(type="list", elements="str"),
339 version=dict(type="int"),
340 )
341
342 module = AnsibleAWSModule(
343 argument_spec=argument_spec,
344 required_if=[
345 ("state", "present", ["content"]),
346 ("state", "absent", ["version"]),
347 ],
348 mutually_exclusive=[
349 ["version", "description"],
350 ["version", "content"],
351 ["version", "compatible_runtimes"],
352 ["version", "license_info"],
353 ["version", "compatible_architectures"],
354 ],
355 supports_check_mode=True,
356 )
357
358 lambda_client = module.client("lambda")
359 execute_module(module, lambda_client)
360
361
362 if __name__ == "__main__":
363 main()