Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_import_image.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
8 DOCUMENTATION = r"""
9 ---
10 module: ec2_import_image
11 version_added: 7.0.0
12 short_description: Manage AWS EC2 import image tasks
13 description:
14 - Import single or multi-volume disk images or EBS snapshots into an Amazon Machine Image (AMI).
15 - Cancel an in-process import virtual machine task.
16 options:
17 state:
18 description:
19 - Use O(state=present) to import single or multi-volume disk images or EBS snapshots into an Amazon Machine Image (AMI).
20 - Use O(state=absent) to cancel an in-process import virtual machine task.
21 default: "present"
22 choices: ["present", "absent"]
23 type: str
24 task_name:
25 description:
26 - The name of the EC2 image import task.
27 type: str
28 aliases: ["name"]
29 required: true
30 architecture:
31 description:
32 - The architecture of the virtual machine.
33 type: str
34 choices: ["i386", "x86_64"]
35 client_data:
36 description:
37 - The client-specific data.
38 type: dict
39 suboptions:
40 comment:
41 description:
42 - A user-defined comment about the disk upload.
43 type: str
44 upload_end:
45 description:
46 - The time that the disk upload ends.
47 type: str
48 upload_size:
49 description:
50 - The size of the uploaded disk image, in GiB.
51 type: float
52 upload_start:
53 description:
54 - The time that the disk upload starts.
55 type: str
56 description:
57 description:
58 - A description string for the import image task.
59 type: str
60 disk_containers:
61 description:
62 - Information about the disk containers.
63 type: list
64 elements: dict
65 suboptions:
66 description:
67 description:
68 - The description of the disk image.
69 type: str
70 device_name:
71 description:
72 - The block device mapping for the disk.
73 type: str
74 format:
75 description:
76 - The format of the disk image being imported.
77 type: str
78 choices: ["OVA", "ova", "VHD", "vhd", "VHDX", "vhdx", "VMDK", "vmdk", "RAW", "raw"]
79 snapshot_id:
80 description:
81 - The ID of the EBS snapshot to be used for importing the snapshot.
82 type: str
83 url:
84 description:
85 - The URL to the Amazon S3-based disk image being imported.
86 The URL can either be a https URL (https://..) or an Amazon S3 URL (s3://..).
87 type: str
88 user_bucket:
89 description:
90 - The S3 bucket for the disk image.
91 type: dict
92 suboptions:
93 s3_bucket:
94 description:
95 - The name of the Amazon S3 bucket where the disk image is located.
96 type: str
97 s3_key:
98 description:
99 - The file name of the disk image.
100 type: str
101 encrypted:
102 description:
103 - Specifies whether the destination AMI of the imported image should be encrypted.
104 - The default KMS key for EBS is used unless you specify a non-default KMS key using O(kms_key_id).
105 type: bool
106 hypervisor:
107 description:
108 - The target hypervisor platform.
109 type: str
110 choices: ["xen"]
111 kms_key_id:
112 description:
113 - An identifier for the symmetric KMS key to use when creating the encrypted AMI.
114 This parameter is only required if you want to use a non-default KMS key;
115 if this parameter is not specified, the default KMS key for EBS is used.
116 If a O(kms_key_id) is specified, the O(encrypted) flag must also be set.
117 type: str
118 license_type:
119 description:
120 - The license type to be used for the Amazon Machine Image (AMI) after importing.
121 type: str
122 platform:
123 description:
124 - The operating system of the virtual machine.
125 type: str
126 choices: ["Windows", "Linux"]
127 role_name:
128 description:
129 - The name of the role to use when not using the default role, 'vmimport'.
130 type: str
131 license_specifications:
132 description:
133 - The ARNs of the license configurations.
134 type: list
135 elements: dict
136 suboptions:
137 license_configuration_arn:
138 description:
139 - The ARN of a license configuration.
140 type: str
141 boot_mode:
142 description:
143 - The boot mode of the virtual machine.
144 type: str
145 choices: ["legacy-bios", "uefi"]
146 cancel_reason:
147 description:
148 - The reason for canceling the task.
149 type: str
150 usage_operation:
151 description:
152 - The usage operation value.
153 type: str
154 tags:
155 description:
156 - The tags to apply to the import image task during creation.
157 type: dict
158 aliases: ["resource_tags"]
159 author:
160 - Alina Buzachis (@alinabuzachis)
161 extends_documentation_fragment:
162 - amazon.aws.common.modules
163 - amazon.aws.region.modules
164 - amazon.aws.boto3
165 """
166
167 EXAMPLES = r"""
168 # Note: These examples do not set authentication details, see the AWS Guide for details.
169 - name: Import image
170 amazon.aws.ec2_import_image:
171 state: present
172 task_name: "clone-vm-import-image"
173 disk_containers:
174 - format: raw
175 user_bucket:
176 s3_bucket: "clone-vm-s3-bucket"
177 s3_key: "clone-vm-s3-bucket/ubuntu-vm-clone.raw"
178
179 - name: Cancel an import image task
180 amazon.aws.ec2_import_image:
181 state: absent
182 task_name: "clone-vm-import-image"
183 """
184
185 RETURN = r"""
186 import_image:
187 description: A dict containing information about an EC2 import task.
188 returned: always
189 type: complex
190 contains:
191 task_name:
192 description:
193 - The name of the EC2 image import task.
194 type: str
195 architecture:
196 description:
197 - The architecture of the virtual machine.
198 type: str
199 image_id:
200 description:
201 - The ID of the Amazon Machine Image (AMI) created by the import task.
202 type: str
203 import_task_id:
204 description:
205 - The task ID of the import image task.
206 type: str
207 progress:
208 description:
209 - The progress of the task.
210 type: str
211 snapshot_details:
212 description:
213 - Describes the snapshot created from the imported disk.
214 type: dict
215 contains:
216 description:
217 description:
218 - A description for the snapshot.
219 type: str
220 device_name:
221 description:
222 - The block device mapping for the snapshot.
223 type: str
224 disk_image_size:
225 description:
226 - The size of the disk in the snapshot, in GiB.
227 type: float
228 format:
229 description:
230 - The format of the disk image from which the snapshot is created.
231 type: str
232 progress:
233 description:
234 - The percentage of progress for the task.
235 type: str
236 snapshot_id:
237 description:
238 - The snapshot ID of the disk being imported.
239 type: str
240 status:
241 description:
242 - A brief status of the snapshot creation.
243 type: str
244 status_message:
245 description:
246 - A detailed status message for the snapshot creation.
247 type: str
248 url:
249 description:
250 - The URL used to access the disk image.
251 type: str
252 user_bucket:
253 description:
254 - The Amazon S3 bucket for the disk image.
255 type: dict
256 status:
257 description:
258 - A brief status of the task.
259 type: str
260 status_message:
261 description:
262 - A detailed status message of the import task.
263 type: str
264 license_specifications:
265 description:
266 - The ARNs of the license configurations.
267 type: dict
268 usage_operation:
269 description:
270 - The usage operation value.
271 type: dict
272 description:
273 description:
274 - A description string for the import image task.
275 type: str
276 encrypted:
277 description:
278 - Specifies whether the destination AMI of the imported image should be encrypted.
279 type: bool
280 hypervisor:
281 description:
282 - The target hypervisor platform.
283 type: str
284 kms_key_id:
285 description:
286 - The identifier for the symmetric KMS key that was used to create the encrypted AMI.
287 type: str
288 license_type:
289 description:
290 - The license type to be used for the Amazon Machine Image (AMI) after importing.
291 type: str
292 platform:
293 description:
294 - The operating system of the virtual machine.
295 type: str
296 role_name:
297 description:
298 - The name of the role to use when not using the default role, 'vmimport'.
299 type: str
300 tags:
301 description:
302 - The tags to apply to the import image task during creation.
303 type: dict
304 """
305
306 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
307
308 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
309 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import cancel_import_task
310 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_import_image_tasks_as_snake_dict
311 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import import_image
312 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
313 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
314 from ansible_collections.amazon.aws.plugins.module_utils.transformation import scrub_none_parameters
315
316
317 def absent(client, module: AnsibleAWSModule) -> None:
318 """
319 Cancel an in-process import virtual machine
320 """
321
322 filters = {
323 "Filters": [
324 {"Name": "tag:Name", "Values": [module.params["task_name"]]},
325 {"Name": "task-state", "Values": ["active"]},
326 ]
327 }
328
329 try:
330 import_image_info = describe_import_image_tasks_as_snake_dict(client, **filters)
331 except AnsibleEC2Error as e:
332 module.fail_json_aws_error(e)
333
334 if import_image_info:
335 result = import_image_info[0]
336 result["task_name"] = module.params["task_name"]
337
338 if module.check_mode:
339 module.exit_json(changed=True, msg="Would have cancelled the import task if not in check mode")
340
341 try:
342 changed = cancel_import_task(
343 client,
344 import_task_id=result["import_task_id"],
345 cancel_reason=module.params.get("cancel_reason"),
346 )
347 module.exit_json(changed=changed, import_image=result)
348 except AnsibleEC2Error as e:
349 module.fail_json_aws_error(e)
350 else:
351 module.exit_json(
352 changed=False,
353 msg="The specified import task does not exist or it cannot be cancelled",
354 import_image={},
355 )
356
357
358 def present(client, module: AnsibleAWSModule) -> None:
359 params = {}
360 tags = module.params.get("tags") or {}
361 tags.update({"Name": module.params["task_name"]})
362
363 if module.params.get("architecture"):
364 params["Architecture"] = module.params["architecture"]
365 if module.params.get("client_data"):
366 params["ClientData"] = snake_dict_to_camel_dict(module.params["client_data"], capitalize_first=True)
367 if module.params.get("description"):
368 params["Description"] = module.params["description"]
369 if module.params.get("disk_containers"):
370 params["DiskContainers"] = snake_dict_to_camel_dict(module.params["disk_containers"], capitalize_first=True)
371 if module.params.get("encrypted"):
372 params["Encrypted"] = module.params["encrypted"]
373 if module.params.get("hypervisor"):
374 params["Hypervisor"] = module.params["hypervisor"]
375 if module.params.get("kms_key_id"):
376 params["KmsKeyId"] = module.params["kms_key_id"]
377 if module.params.get("license_type"):
378 params["LicenseType"] = module.params["license_type"]
379 if module.params.get("platform"):
380 params["Platform"] = module.params["platform"]
381 if module.params.get("role_name"):
382 params["RoleName"] = module.params["role_name"]
383 if module.params.get("license_specifications"):
384 params["LicenseSpecifications"] = snake_dict_to_camel_dict(
385 module.params["license_specifications"], capitalize_first=True
386 )
387 if module.params.get("usage_operation"):
388 params["UsageOperation"] = module.params["usage_operation"]
389 if module.params.get("boot_mode"):
390 params["BootMode"] = module.params.get("boot_mode")
391 params["TagSpecifications"] = boto3_tag_specifications(tags, ["import-image-task"])
392
393 filters = {
394 "Filters": [
395 {"Name": "tag:Name", "Values": [module.params["task_name"]]},
396 {"Name": "task-state", "Values": ["completed", "active", "deleting"]},
397 ]
398 }
399 try:
400 import_image_info = describe_import_image_tasks_as_snake_dict(client, **filters)
401 except AnsibleEC2Error as e:
402 module.fail_json_aws_error(e)
403
404 if import_image_info:
405 result = import_image_info[0]
406 result["task_name"] = module.params["task_name"]
407 module.exit_json(
408 changed=False,
409 msg="An import task with the specified name already exists",
410 import_image=result,
411 )
412 else:
413 if module.check_mode:
414 module.exit_json(changed=True, msg="Would have created the import task if not in check mode")
415
416 params = scrub_none_parameters(params)
417
418 try:
419 import_image(client, **params)
420 import_image_info = describe_import_image_tasks_as_snake_dict(client, **filters)
421 result = {}
422 if import_image_info:
423 result = import_image_info[0]
424 result["task_name"] = module.params["task_name"]
425 module.exit_json(
426 changed=True,
427 import_image=result,
428 )
429 except AnsibleEC2Error as e:
430 module.fail_json_aws_error(e)
431
432
433 def main():
434 argument_spec = dict(
435 architecture=dict(type="str", choices=["i386", "x86_64"]),
436 client_data=dict(
437 type="dict",
438 options=dict(
439 comment=dict(type="str"),
440 upload_end=dict(type="str"),
441 upload_size=dict(type="float"),
442 upload_start=dict(type="str"),
443 ),
444 ),
445 description=dict(type="str"),
446 license_specifications=dict(
447 type="list",
448 elements="dict",
449 options=dict(
450 license_configuration_arn=dict(type="str"),
451 ),
452 ),
453 encrypted=dict(type="bool"),
454 state=dict(default="present", choices=["present", "absent"]),
455 hypervisor=dict(type="str", choices=["xen"]),
456 kms_key_id=dict(type="str"),
457 license_type=dict(type="str", no_log=False),
458 tags=dict(required=False, type="dict", aliases=["resource_tags"]),
459 platform=dict(type="str", choices=["Windows", "Linux"]),
460 role_name=dict(type="str"),
461 disk_containers=dict(
462 type="list",
463 elements="dict",
464 options=dict(
465 description=dict(type="str"),
466 device_name=dict(type="str"),
467 format=dict(
468 type="str", choices=["OVA", "ova", "VHD", "vhd", "VHDX", "vhdx", "VMDK", "vmdk", "RAW", "raw"]
469 ),
470 snapshot_id=dict(type="str"),
471 url=dict(type="str"),
472 user_bucket=dict(
473 type="dict",
474 options=dict(
475 s3_bucket=dict(type="str"),
476 s3_key=dict(type="str", no_log=True),
477 ),
478 ),
479 ),
480 ),
481 usage_operation=dict(type="str"),
482 boot_mode=dict(type="str", choices=["legacy-bios", "uefi"]),
483 cancel_reason=dict(type="str"),
484 task_name=dict(type="str", aliases=["name"], required=True),
485 )
486
487 module = AnsibleAWSModule(
488 argument_spec=argument_spec,
489 supports_check_mode=True,
490 )
491
492 state = module.params.get("state")
493 client = module.client("ec2")
494
495 if state == "present":
496 present(client, module)
497 else:
498 absent(client, module)
499
500
501 if __name__ == "__main__":
502 main()