Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2018 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: ec2_launch_template
10 version_added: 1.0.0
11 version_added_collection: community.aws
12 short_description: Manage EC2 launch templates
13 description:
14 - Create, modify, and delete EC2 Launch Templates, which can be used to
15 create individual instances or with Autoscaling Groups.
16 - The M(amazon.aws.ec2_instance) and M(community.aws.autoscaling_group) modules can, instead of specifying all
17 parameters on those tasks, be passed a Launch Template which contains
18 settings like instance size, disk type, subnet, and more.
19 author:
20 - Ryan Scott Brown (@ryansb)
21 options:
22 template_id:
23 description:
24 - The ID for the launch template, can be used for all cases except creating a new Launch Template.
25 - At least one of O(template_id) and O(template_name) must be specified.
26 aliases: [id]
27 type: str
28 template_name:
29 description:
30 - The template name. This must be unique in the region-account combination you are using.
31 - If no launch template exists with the specified name, a new launch template is created.
32 - If a launch template with the specified name already exists and the configuration has not changed,
33 nothing happens.
34 - If a launch template with the specified name already exists and the configuration has changed,
35 a new version of the launch template is created.
36 - At least one of O(template_id) and O(template_name) must be specified.
37 aliases: [name]
38 type: str
39 default_version:
40 description:
41 - Which version should be the default when users spin up new instances based on this template? By default, the latest version will be made the default.
42 type: str
43 default: latest
44 version_description:
45 version_added: 5.5.0
46 description:
47 - The description of a launch template version.
48 default: ""
49 type: str
50 versions_to_delete:
51 description:
52 - The version numbers of a launch template versions to delete.
53 - Use O(default_version) to specify a new default version when deleting the current default version.
54 - By default, the latest version will be made the default.
55 - Ignored when O(state=present).
56 type: list
57 elements: int
58 version_added: 9.0.0
59 state:
60 description:
61 - Whether the launch template should exist or not.
62 - Deleting specific versions of a launch template is not supported at this time.
63 choices: [present, absent]
64 default: present
65 type: str
66 block_device_mappings:
67 description:
68 - The block device mapping. Supplying both a snapshot ID and an encryption
69 value as arguments for block-device mapping results in an error. This is
70 because only blank volumes can be encrypted on start, and these are not
71 created from a snapshot. If a snapshot is the basis for the volume, it
72 contains data by definition and its encryption status cannot be changed
73 using this action.
74 type: list
75 elements: dict
76 suboptions:
77 device_name:
78 description: The device name (for example, V(/dev/sdh) or V(xvdh)).
79 type: str
80 no_device:
81 description: Suppresses the specified device included in the block device mapping of the AMI.
82 type: str
83 virtual_name:
84 description: >
85 The virtual device name (ephemeralN). Instance store volumes are
86 numbered starting from 0. An instance type with 2 available instance
87 store volumes can specify mappings for ephemeral0 and ephemeral1. The
88 number of available instance store volumes depends on the instance
89 type. After you connect to the instance, you must mount the volume.
90 type: str
91 ebs:
92 description: Parameters used to automatically set up EBS volumes when the instance is launched.
93 type: dict
94 suboptions:
95 delete_on_termination:
96 description: Indicates whether the EBS volume is deleted on instance termination.
97 type: bool
98 encrypted:
99 description: >
100 Indicates whether the EBS volume is encrypted. Encrypted volumes
101 can only be attached to instances that support Amazon EBS
102 encryption. If you are creating a volume from a snapshot, you
103 can't specify an encryption value.
104 type: bool
105 iops:
106 description:
107 - The number of I/O operations per second (IOPS) that the volume
108 supports. For io1, this represents the number of IOPS that are
109 provisioned for the volume. For gp2, this represents the baseline
110 performance of the volume and the rate at which the volume
111 accumulates I/O credits for bursting. For more information about
112 General Purpose SSD baseline performance, I/O credits, and
113 bursting, see Amazon EBS Volume Types in the Amazon Elastic
114 Compute Cloud User Guide.
115 - >
116 Condition: This parameter is required for requests to create io1
117 volumes; it is not used in requests to create gp2, st1, sc1, or
118 standard volumes.
119 type: int
120 kms_key_id:
121 description: The ARN of the AWS Key Management Service (AWS KMS) CMK used for encryption.
122 type: str
123 snapshot_id:
124 description: The ID of the snapshot to create the volume from.
125 type: str
126 volume_size:
127 description:
128 - The size of the volume, in GiB.
129 - "Default: If you're creating the volume from a snapshot and don't specify a volume size, the default is the snapshot size."
130 type: int
131 volume_type:
132 description: The volume type
133 type: str
134 throughput:
135 description: >
136 The throughput to provision for a gp3 volume, with a maximum of 2,000 MiB/s.
137 Valid Range - Minimum value of V(125). Maximum value of V(2000).
138 type: int
139 version_added: 9.0.0
140 cpu_options:
141 description:
142 - Choose CPU settings for the EC2 instances that will be created with this template.
143 - For more information, see U(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html)
144 type: dict
145 suboptions:
146 core_count:
147 description: The number of CPU cores for the instance.
148 type: int
149 threads_per_core:
150 description: >
151 The number of threads per CPU core. To disable Intel Hyper-Threading
152 Technology for the instance, specify a value of V(1). Otherwise, specify
153 the default value of V(2).
154 type: int
155 credit_specification:
156 description: The credit option for CPU usage of the instance. Valid for T2 or T3 instances only.
157 type: dict
158 suboptions:
159 cpu_credits:
160 description:
161 - The credit option for CPU usage of a T2 or T3 instance. Valid values are C(standard) and C(unlimited).
162 type: str
163 disable_api_termination:
164 description:
165 - This helps protect instances from accidental termination.
166 - If set to V(true), you can't terminate the instance using the Amazon EC2 console, CLI, or API.
167 type: bool
168 ebs_optimized:
169 description: >
170 Indicates whether the instance is optimized for Amazon EBS I/O. This
171 optimization provides dedicated throughput to Amazon EBS and an optimized
172 configuration stack to provide optimal Amazon EBS I/O performance. This
173 optimization isn't available with all instance types. Additional usage
174 charges apply when using an EBS-optimized instance.
175 type: bool
176 elastic_gpu_specifications:
177 type: list
178 elements: dict
179 description: Settings for Elastic GPU attachments. See U(https://aws.amazon.com/ec2/elastic-gpus/) for details.
180 suboptions:
181 type:
182 description: The type of Elastic GPU to attach
183 type: str
184 iam_instance_profile:
185 description: >
186 The name or ARN of an IAM instance profile. Requires permissions to
187 describe existing instance roles to confirm ARN is properly formed.
188 type: str
189 image_id:
190 description: >
191 The AMI ID to use for new instances launched with this template. This
192 value is region-dependent since AMIs are not global resources.
193 type: str
194 instance_initiated_shutdown_behavior:
195 description: >
196 Indicates whether an instance stops or terminates when you initiate
197 shutdown from the instance using the operating system shutdown command.
198 choices: [stop, terminate]
199 type: str
200 instance_market_options:
201 description: Options for alternative instance markets, currently only the spot market is supported.
202 type: dict
203 suboptions:
204 market_type:
205 description: The market type. This should always be V(spot).
206 type: str
207 spot_options:
208 description: Spot-market specific settings.
209 type: dict
210 suboptions:
211 block_duration_minutes:
212 description:
213 - The required duration for the Spot Instances (also known as Spot blocks), in minutes.
214 - This value must be a multiple of V(60) (V(60), V(120), V(180), V(240), V(300), or V(360)).
215 type: int
216 instance_interruption_behavior:
217 description: The behavior when a Spot Instance is interrupted. The default is V(terminate).
218 choices: [hibernate, stop, terminate]
219 type: str
220 max_price:
221 description: The highest hourly price you're willing to pay for this Spot Instance.
222 type: str
223 spot_instance_type:
224 description: The request type to send.
225 choices: [one-time, persistent]
226 type: str
227 instance_type:
228 description:
229 - The instance type, such as V(c5.2xlarge). For a full list of instance types, see
230 U(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html).
231 type: str
232 kernel_id:
233 description:
234 - The ID of the kernel.
235 - We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, see
236 U(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html)
237 type: str
238 key_name:
239 description:
240 - The name of the key pair. You can create a key pair using M(amazon.aws.ec2_key).
241 - If you do not specify a key pair, you can't connect to the instance
242 unless you choose an AMI that is configured to allow users another way to log in.
243 type: str
244 monitoring:
245 description: Settings for instance monitoring.
246 type: dict
247 suboptions:
248 enabled:
249 type: bool
250 description: Whether to turn on detailed monitoring for new instances. This will incur extra charges.
251 network_interfaces:
252 description: One or more network interfaces.
253 type: list
254 elements: dict
255 suboptions:
256 associate_public_ip_address:
257 description: Associates a public IPv4 address with eth0 for a new network interface.
258 type: bool
259 delete_on_termination:
260 description: Indicates whether the network interface is deleted when the instance is terminated.
261 type: bool
262 description:
263 description: A description for the network interface.
264 type: str
265 device_index:
266 description: The device index for the network interface attachment.
267 type: int
268 groups:
269 description: List of security group IDs to include on this instance.
270 type: list
271 elements: str
272 ipv6_address_count:
273 description:
274 - The number of IPv6 addresses to assign to a network interface.
275 - Amazon EC2 automatically selects the IPv6 addresses from the subnet range.
276 - You can't use this option if specifying the O(network_interfaces.ipv6_addresses) option.
277 type: int
278 ipv6_addresses:
279 description:
280 - A list of one or more specific IPv6 addresses from the IPv6 CIDR block range of your subnet.
281 - You can't use this option if you're specifying the O(network_interfaces.ipv6_address_count) option.
282 type: list
283 elements: str
284 network_interface_id:
285 description: The eni ID of a network interface to attach.
286 type: str
287 private_ip_address:
288 description: The primary private IPv4 address of the network interface.
289 type: str
290 subnet_id:
291 description: The ID of the subnet for the network interface.
292 type: str
293 placement:
294 description: The placement group settings for the instance.
295 type: dict
296 suboptions:
297 affinity:
298 description: The affinity setting for an instance on a Dedicated Host.
299 type: str
300 availability_zone:
301 description: The Availability Zone for the instance.
302 type: str
303 group_name:
304 description: The name of the placement group for the instance.
305 type: str
306 host_id:
307 description: The ID of the Dedicated Host for the instance.
308 type: str
309 tenancy:
310 description: >
311 The tenancy of the instance (if the instance is running in a VPC). An
312 instance with a tenancy of dedicated runs on single-tenant hardware.
313 type: str
314 ram_disk_id:
315 description: >
316 The ID of the RAM disk to launch the instance with. We recommend that you
317 use PV-GRUB instead of kernels and RAM disks. For more information, see
318 U(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html)
319 type: str
320 security_group_ids:
321 description: A list of security group IDs (VPC or EC2-Classic) that the new instances will be added to.
322 type: list
323 elements: str
324 security_groups:
325 description: >
326 A list of security group names (Default VPC or EC2-Classic) that the new instances will be added to.
327 For any VPC other than Default, you must use O(security_group_ids).
328 type: list
329 elements: str
330 source_version:
331 description:
332 - The version number of the launch template version on which to base the new version.
333 - The new version inherits the same launch parameters as the source version, except for parameters that you explicity specify.
334 - Snapshots applied to the O(block_device_mappings) are ignored when creating a new version unless they are explicitly included.
335 type: str
336 default: latest
337 version_added: 4.1.0
338 tag_specifications:
339 description:
340 - The tags to apply to the resources when this Launch template is used.
341 type: list
342 elements: dict
343 version_added: 9.0.0
344 suboptions:
345 resource_type:
346 description:
347 - The type of resource to tag.
348 - If the instance does not include the resource type that you specify, the instance launch fails.
349 type: str
350 default: instance
351 choices:
352 - instance
353 - volume
354 - network-interface
355 - spot-instances-request
356 tags:
357 description:
358 - A set of key-value pairs to be applied to the resource type.
359 - "Tag key constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with I(aws:)"
360 - "Tag value constraints: Tag values are case-sensitive and accept a maximum of 255 Unicode characters."
361 type: dict
362 user_data:
363 description: >
364 The Base64-encoded user data to make available to the instance. For more information, see the Linux
365 U(http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) and Windows
366 U(http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data)
367 documentation on user-data.
368 type: str
369 metadata_options:
370 description:
371 - Configure EC2 Metadata options.
372 - For more information see the IMDS documentation
373 U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html).
374 type: dict
375 version_added: 1.5.0
376 suboptions:
377 http_endpoint:
378 type: str
379 description: This parameter enables or disables the HTTP metadata endpoint on your instances.
380 choices: [enabled, disabled]
381 default: 'enabled'
382 http_put_response_hop_limit:
383 type: int
384 description:
385 - The desired HTTP PUT response hop limit for instance metadata requests.
386 - The larger the number, the further instance metadata requests can travel.
387 default: 1
388 http_tokens:
389 type: str
390 description: The state of token usage for your instance metadata requests.
391 choices: [optional, required]
392 default: 'optional'
393 http_protocol_ipv6:
394 version_added: 3.1.0
395 type: str
396 description:
397 - Whether the instance metadata endpoint is available via IPv6.
398 choices: [enabled, disabled]
399 default: 'disabled'
400 instance_metadata_tags:
401 version_added: 3.1.0
402 type: str
403 description:
404 - Whether the instance tags are availble (V(enabled)) via metadata endpoint or not (V(disabled)).
405 choices: [enabled, disabled]
406 default: 'disabled'
407 notes:
408 - The O(tags) option used has been in release 9.0.0 to be applied to the launch template resource instead of launch template resource.
409 - Use O(tag_specifications) to define tags to be applied to resources when this Launch Template is used.
410 - Support for O(purge_tags) was added in release 9.0.0.
411 extends_documentation_fragment:
412 - amazon.aws.common.modules
413 - amazon.aws.region.modules
414 - amazon.aws.boto3
415 - amazon.aws.tags
416 """
417
418 EXAMPLES = r"""
419 - name: Create an ec2 launch template
420 amazon.aws.ec2_launch_template:
421 name: "my_template"
422 image_id: "ami-04b762b4289fba92b"
423 key_name: my_ssh_key
424 instance_type: t2.micro
425 iam_instance_profile: myTestProfile
426 disable_api_termination: true
427
428 - name: >
429 Create a new version of an existing ec2 launch template with a different instance type,
430 while leaving an older version as the default version
431 amazon.aws.ec2_launch_template:
432 name: "my_template"
433 default_version: 1
434 instance_type: c5.4xlarge
435
436 - name: Delete an ec2 launch template
437 amazon.aws.ec2_launch_template:
438 name: "my_template"
439 state: absent
440
441 - name: Delete a specific version of an ec2 launch template
442 amazon.aws.ec2_launch_template:
443 name: "my_template"
444 versions_to_delete:
445 - 2
446 state: absent
447
448 - name: Delete a specific version of an ec2 launch template and change the default version
449 amazon.aws.ec2_launch_template:
450 name: "my_template"
451 versions_to_delete:
452 - 1
453 default_version: 2
454 state: absent
455
456 - name: Create an ec2 launch template with specific tags
457 amazon.aws.ec2_launch_template:
458 name: "my_template"
459 image_id: "ami-04b762b4289fba92b"
460 instance_type: t2.micro
461 disable_api_termination: true
462 tags:
463 Some: tag
464 Another: tag
465
466 - name: Create an ec2 launch template with different tag for volume and instance
467 amazon.aws.ec2_launch_template:
468 name: "my_template"
469 image_id: "ami-04b762b4289fba92b"
470 instance_type: t2.micro
471 block_device_mappings:
472 - device_name: /dev/sdb
473 ebs:
474 volume_size: 20
475 delete_on_termination: true
476 volume_type: standard
477 tag_specifications:
478 - resource_type: instance
479 tags:
480 OsType: Linux
481 - resource_type: volume
482 tags:
483 foo: bar
484 """
485
486 RETURN = r"""
487 latest_version:
488 description: The latest available version number of the launch template.
489 returned: when RV(latest_template) has a version number.
490 type: int
491 default_version:
492 description: The version that will be used if only the template name is specified. Often this is the same as the latest version, but not always.
493 returned: when RV(default_template) has a version number.
494 type: int
495 template:
496 description: Latest available version of the launch template.
497 returned: when O(state=present)
498 type: complex
499 contains:
500 launch_template_id:
501 description: The ID of the launch template.
502 type: str
503 returned: always
504 launch_template_name:
505 description: The name of the launch template.
506 type: str
507 returned: always
508 create_time:
509 description: The time launch template was created.
510 type: str
511 returned: always
512 created_by:
513 description: The principal that created the launch template.
514 type: str
515 returned: always
516 default_version_number:
517 description: The version number of the default version of the launch template.
518 type: int
519 returned: always
520 latest_version_number:
521 description: The version number of the latest version of the launch template.
522 type: int
523 returned: always
524 tags:
525 description: A dictionary of tags assigned to image.
526 returned: when AMI is created or already exists
527 type: dict
528 sample: {
529 "Env": "devel",
530 "Name": "nat-server"
531 }
532 versions:
533 description: All available versions of the launch template.
534 returned: when O(state=present)
535 type: list
536 elements: dict
537 contains:
538 launch_template_id:
539 description: The ID of the launch template.
540 type: str
541 returned: always
542 launch_template_name:
543 description: The name of the launch template.
544 type: str
545 returned: always
546 create_time:
547 description: The time the version was created.
548 type: str
549 returned: always
550 created_by:
551 description: The principal that created the version.
552 type: str
553 returned: always
554 default_version:
555 description: Indicates whether the version is the default version.
556 type: bool
557 returned: always
558 version_number:
559 description: The version number.
560 type: int
561 returned: always
562 version_description:
563 description: The description for the version.
564 type: str
565 returned: always
566 launch_template_data:
567 description: Information about the launch template.
568 returned: always
569 type: dict
570 contains:
571 kernel_id:
572 description:
573 - The ID of the kernel.
574 returned: if applicable
575 type: str
576 image_id:
577 description: The ID of the AMI or a Systems Manager parameter.
578 type: str
579 returned: if applicable
580 instance_type:
581 description: The instance type.
582 type: str
583 returned: if applicable
584 key_name:
585 description: The name of the key pair.
586 type: str
587 returned: if applicable
588 monitoring:
589 description: The monitoring for the instance.
590 type: dict
591 returned: if applicable
592 contains:
593 enabled:
594 description: Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled.
595 type: bool
596 returned: always
597 placement:
598 description: The placement of the instance.
599 type: dict
600 returned: if applicable
601 contains:
602 availability_zone:
603 description: The Availability Zone of the instance.
604 type: str
605 returned: if applicable
606 affinity:
607 description: The affinity setting for the instance on the Dedicated Host.
608 type: str
609 returned: if applicable
610 group_name:
611 description: The name of the placement group for the instance.
612 type: str
613 returned: if applicable
614 host_id:
615 description: The ID of the Dedicated Host for the instance.
616 type: str
617 returned: if applicable
618 tenancy:
619 description: The tenancy of the instance.
620 type: str
621 returned: if applicable
622 host_resource_group_arn:
623 description: The ARN of the host resource group in which to launch the instances.
624 type: str
625 returned: if applicable
626 partition_number:
627 description: The number of the partition the instance should launch in.
628 type: int
629 returned: if applicable
630 group_id:
631 description: The Group ID of the placement group.
632 type: str
633 returned: if applicable
634 ebs_optimized:
635 description:
636 - Indicates whether the instance is optimized for Amazon EBS I/O.
637 type: bool
638 returned: always
639 iam_instance_profile:
640 description:
641 - The IAM instance profile.
642 type: dict
643 returned: if application
644 contains:
645 arn:
646 description: The Amazon Resource Name (ARN) of the instance profile.
647 type: str
648 returned: always
649 name:
650 description: The name of the instance profile.
651 type: str
652 returned: always
653 block_device_mappings:
654 description: The block device mappings.
655 type: list
656 elements: dict
657 returned: if applicable
658 contains:
659 device_name:
660 description: The device name.
661 type: str
662 returned: always
663 virtual_name:
664 description: The virtual device name.
665 type: str
666 returned: always
667 ebs:
668 description: Information about the block device for an EBS volume.
669 type: str
670 returned: if applicable
671 contains:
672 encrypted:
673 description: Indicates whether the EBS volume is encrypted.
674 type: bool
675 returned: always
676 delete_on_termination:
677 description: Indicates whether the EBS volume is deleted on instance termination.
678 type: bool
679 returned: always
680 iops:
681 description: The number of I/O operations per second (IOPS) that the volume supports.
682 type: int
683 returned: always
684 kms_key_id:
685 description: The ARN of the Key Management Service (KMS) CMK used for encryption.
686 type: int
687 returned: always
688 snapshot_id:
689 description: The ID of the snapshot.
690 type: str
691 returned: always
692 volume_size:
693 description: The size of the volume, in GiB.
694 type: int
695 returned: always
696 volume_type:
697 description: The volume type.
698 type: str
699 returned: always
700 throughput:
701 description: The throughput that the volume supports, in MiB/s.
702 type: int
703 returned: always
704 no_device:
705 description: To omit the device from the block device mapping, specify an empty string.
706 type: str
707 network_interfaces:
708 description: The network interfaces.
709 type: list
710 elements: dict
711 returned: if applicable
712 contains:
713 associate_carrier_ip_address:
714 description: Indicates whether to associate a Carrier IP address with eth0 for a new network interface.
715 type: bool
716 returned: always
717 associate_public_ip_address:
718 description: Indicates whether to associate a public IPv4 address with eth0 for a new network interface.
719 type: bool
720 returned: always
721 delete_on_termination:
722 description: Indicates whether the network interface is deleted when the instance is terminated.
723 type: bool
724 returned: always
725 description:
726 description: A description for the network interface.
727 type: str
728 returned: always
729 device_index:
730 description: The device index for the network interface attachment.
731 type: int
732 returned: always
733 groups:
734 description: The IDs of one or more security groups.
735 type: list
736 elements: str
737 returned: if applicable
738 interface_type:
739 description: The type of network interface.
740 type: str
741 returned: always
742 ipv6_address_count:
743 description: The number of IPv6 addresses for the network interface.
744 type: int
745 returned: if applicable
746 ipv6_addresses:
747 description: The IPv6 addresses for the network interface.
748 returned: if applicable
749 type: list
750 elements: dict
751 contains:
752 ipv6_address:
753 description: The IPv6 address.
754 type: str
755 returned: always
756 is_primary_ipv6:
757 description: Determines if an IPv6 address associated with a network interface is the primary IPv6 address.
758 type: bool
759 returned: always
760 network_interface_id:
761 description: The ID of the network interface.
762 type: str
763 returned: always
764 private_ip_address:
765 description: The primary private IPv4 address of the network interface.
766 type: str
767 returned: if applicable
768 private_ip_addresses:
769 description: A list of private IPv4 addresses.
770 type: list
771 elements: str
772 returned: if applicable
773 contains:
774 primary:
775 description: Indicates whether the private IPv4 address is the primary private IPv4 address.
776 type: bool
777 returned: always
778 private_ip_address:
779 description: The private IPv4 address.
780 type: bool
781 returned: always
782 secondary_private_ip_address_count:
783 description: The number of secondary private IPv4 addresses for the network interface.
784 type: int
785 returned: if applicable
786 subnet_id:
787 description: The ID of the subnet for the network interface.
788 type: str
789 returned: always
790 network_card_index:
791 description: The index of the network card.
792 type: int
793 returned: if applicable
794 ipv4_prefixes:
795 description: A list of IPv4 prefixes assigned to the network interface.
796 type: list
797 elements: dict
798 returned: if applicable
799 contains:
800 ipv4_prefix:
801 description: The IPv4 delegated prefixes assigned to the network interface.
802 type: str
803 returned: always
804 ipv4_prefix_count:
805 description: The number of IPv4 prefixes that Amazon Web Services automatically assigned to the network interface.
806 type: int
807 returned: if applicable
808 ipv6_prefixes:
809 description: A list of IPv6 prefixes assigned to the network interface.
810 type: list
811 elements: dict
812 returned: if applicable
813 contains:
814 ipv6_prefix:
815 description: The IPv6 delegated prefixes assigned to the network interface.
816 type: str
817 returned: always
818 ipv6_prefix_count:
819 description: The number of IPv6 prefixes that Amazon Web Services automatically assigned to the network interface.
820 type: int
821 returned: if applicable
822 primary_ipv6:
823 description: The primary IPv6 address of the network interface.
824 type: str
825 returned: if applicable
826 ena_srd_specification:
827 description: Contains the ENA Express settings for instances launched from your launch template.
828 type: dict
829 returned: if applicable
830 contains:
831 ena_srd_enabled:
832 description: Indicates whether ENA Express is enabled for the network interface.
833 type: bool
834 returned: always
835 ena_srd_udp_specification:
836 description: Configures ENA Express for UDP network traffic.
837 type: dict
838 returned: always
839 contains:
840 ena_srd_udp_enabled:
841 description: Indicates whether UDP traffic to and from the instance uses ENA Express.
842 type: bool
843 returned: always
844 connection_tracking_specification:
845 description:
846 - A security group connection tracking specification that enables you to set the timeout
847 for connection tracking on an Elastic network interface.
848 type: dict
849 returned: if applicable
850 contains:
851 tcp_established_timeout:
852 description: Timeout (in seconds) for idle TCP connections in an established state.
853 type: int
854 returned: always
855 udp_timeout:
856 description:
857 - Timeout (in seconds) for idle UDP flows that have seen traffic only in a single direction
858 or a single request-response transaction.
859 type: int
860 returned: always
861 udp_stream_timeout:
862 description:
863 - Timeout (in seconds) for idle UDP flows classified as streams which have seen more
864 than one request-response transaction.
865 type: int
866 returned: always
867 ram_disk_id:
868 description: The ID of the RAM disk, if applicable.
869 type: str
870 returned: if applicable
871 disable_api_termination:
872 description: If set to true, indicates that the instance cannot be terminated using the Amazon EC2 console, command line tool, or API.
873 type: bool
874 returned: if applicable
875 instance_initiated_shutdown_behavior:
876 description: Indicates whether an instance stops or terminates when you initiate shutdown from the instance.
877 type: str
878 returned: if applicable
879 user_data:
880 description: The user data for the instance.
881 type: str
882 returned: if applicable
883 tag_specifications:
884 description: The tags that are applied to the resources that are created during instance launch.
885 type: list
886 elements: dict
887 returned: if applicable
888 contains:
889 resource_type:
890 description: The type of resource to tag.
891 type: str
892 returned: always
893 tags:
894 description: The tags for the resource.
895 type: list
896 elements: dict
897 contains:
898 key:
899 description: The key of the tag.
900 type: str
901 returned: always
902 value:
903 description: The value of the tag.
904 type: str
905 returned: always
906 enclave_options:
907 description: Indicates whether the instance is enabled for Amazon Web Services Nitro Enclaves.
908 type: dict
909 returned: if applicable
910 contains:
911 enabled:
912 description: If this parameter is set to true, the instance is enabled for Amazon Web Services Nitro Enclaves.
913 type: bool
914 returned: always
915 metadata_options:
916 description: The metadata options for the instance.
917 type: dict
918 returned: if applicable
919 contains:
920 state:
921 description: The state of the metadata option changes.
922 type: str
923 returned: if applicable
924 http_tokens:
925 description: Indicates whether IMDSv2 is required.
926 type: str
927 returned: if applicable
928 http_put_response_hop_limit:
929 description: The desired HTTP PUT response hop limit for instance metadata requests.
930 type: int
931 returned: if applicable
932 http_endpoint:
933 description: Enables or disables the HTTP metadata endpoint on your instances.
934 type: str
935 returned: if applicable
936 http_protocol_ipv6:
937 description: Enables or disables the IPv6 endpoint for the instance metadata service.
938 type: str
939 returned: if applicable
940 instance_metadata_tags:
941 description: Set to enabled to allow access to instance tags from the instance metadata.
942 type: str
943 returned: if applicable
944 cpu_options:
945 description: The CPU options for the instance.
946 type: dict
947 returned: if applicable
948 contains:
949 core_count:
950 description: The number of CPU cores for the instance.
951 type: int
952 returned: if applicable
953 threads_per_core:
954 description: The number of threads per CPU core.
955 type: int
956 returned: if applicable
957 amd_sev_snp:
958 description: Indicates whether the instance is enabled for AMD SEV-SNP.
959 type: int
960 returned: if applicable
961 security_group_ids:
962 description: The security group IDs.
963 type: list
964 elements: str
965 returned: if applicable
966 security_groups:
967 description: The security group names.
968 type: list
969 elements: str
970 returned: if applicable
971 sample: {
972 "block_device_mappings": [
973 {
974 "device_name": "/dev/sdb",
975 "ebs": {
976 "delete_on_termination": true,
977 "encrypted": true,
978 "volumeSize": 5
979 }
980 }
981 ],
982 "ebs_optimized": false,
983 "image_id": "ami-0231217be14a6f3ba",
984 "instance_type": "t2.micro",
985 "network_interfaces": [
986 {
987 "associate_public_ip_address": false,
988 "device_index": 0,
989 "ipv6_addresses": [
990 {
991 "ipv6_address": "2001:0:130F:0:0:9C0:876A:130B"
992 }
993 ]
994 }
995 ]
996 }
997 latest_template:
998 description: The latest available version of the launch template.
999 returned: when O(state=present)
1000 type: complex
1001 contains:
1002 launch_template_id:
1003 description: The ID of the launch template.
1004 type: str
1005 returned: always
1006 launch_template_name:
1007 description: The name of the launch template.
1008 type: str
1009 returned: always
1010 create_time:
1011 description: The time launch template was created.
1012 type: str
1013 returned: always
1014 created_by:
1015 description: The principal that created the launch template.
1016 type: str
1017 returned: always
1018 default_version_number:
1019 description: The version number of the default version of the launch template.
1020 type: int
1021 returned: always
1022 latest_version_number:
1023 description: The version number of the latest version of the launch template.
1024 type: int
1025 returned: always
1026 tags:
1027 description: A dictionary of tags assigned to image.
1028 returned: when AMI is created or already exists
1029 type: dict
1030 sample: {
1031 "Env": "devel",
1032 "Name": "nat-server"
1033 }
1034 default_template:
1035 description:
1036 - The launch template version that will be used if only the template name is specified.
1037 - Often this is the same as the latest version, but not always.
1038 returned: when O(state=present)
1039 type: complex
1040 contains:
1041 launch_template_id:
1042 description: The ID of the launch template.
1043 type: str
1044 returned: always
1045 launch_template_name:
1046 description: The name of the launch template.
1047 type: str
1048 returned: always
1049 create_time:
1050 description: The time launch template was created.
1051 type: str
1052 returned: always
1053 created_by:
1054 description: The principal that created the launch template.
1055 type: str
1056 returned: always
1057 default_version_number:
1058 description: The version number of the default version of the launch template.
1059 type: int
1060 returned: always
1061 latest_version_number:
1062 description: The version number of the latest version of the launch template.
1063 type: int
1064 returned: always
1065 tags:
1066 description: A dictionary of tags assigned to image.
1067 returned: when AMI is created or already exists
1068 type: dict
1069 sample: {
1070 "Env": "devel",
1071 "Name": "nat-server"
1072 }
1073 deleted_template:
1074 description: information about a launch template deleted.
1075 returned: when O(state=absent)
1076 type: complex
1077 contains:
1078 launch_template_id:
1079 description: The ID of the launch template.
1080 type: str
1081 returned: always
1082 launch_template_name:
1083 description: The name of the launch template.
1084 type: str
1085 returned: always
1086 create_time:
1087 description: The time launch template was created.
1088 type: str
1089 returned: always
1090 created_by:
1091 description: The principal that created the launch template.
1092 type: str
1093 returned: always
1094 default_version_number:
1095 description: The version number of the default version of the launch template.
1096 type: int
1097 returned: always
1098 latest_version_number:
1099 description: The version number of the latest version of the launch template.
1100 type: int
1101 returned: always
1102 tags:
1103 description: A dictionary of tags assigned to image.
1104 returned: when AMI is created or already exists
1105 type: dict
1106 sample: {
1107 "Env": "devel",
1108 "Name": "nat-server"
1109 }
1110 deleted_versions:
1111 description: Information about deleted launch template versions.
1112 returned: when O(state=absent)
1113 type: list
1114 elements: dict
1115 contains:
1116 launch_template_id:
1117 description: The ID of the launch template.
1118 type: str
1119 returned: always
1120 launch_template_name:
1121 description: The name of the launch template.
1122 type: str
1123 returned: always
1124 version_number:
1125 description: The version number of the launch template.
1126 type: int
1127 returned: always
1128 """
1129
1130 from typing import Any
1131 from typing import Dict
1132 from typing import List
1133 from typing import Optional
1134 from typing import Tuple
1135 from uuid import uuid4
1136
1137 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
1138 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
1139 from ansible.module_utils.common.text.converters import to_text
1140
1141 from ansible_collections.amazon.aws.plugins.module_utils.botocore import normalize_boto3_result
1142 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
1143 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_launch_template
1144 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_launch_template_version
1145 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_launch_template
1146 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_launch_template_versions
1147 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_launch_template_versions
1148 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_launch_templates
1149 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import determine_iam_arn_from_name
1150 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
1151 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import modify_launch_template
1152 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
1153 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
1154 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
1155 from ansible_collections.amazon.aws.plugins.module_utils.transformation import scrub_none_parameters
1156
1157
1158 def find_existing(client, module: AnsibleAWSModule) -> Tuple[Optional[Dict[str, Any]], Optional[List[Dict[str, Any]]]]:
1159 launch_template = None
1160 launch_template_versions = []
1161 params = {}
1162 template_id = module.params.get("template_id")
1163 template_name = module.params.get("template_name")
1164 if template_id:
1165 params["launch_template_ids"] = [template_id]
1166 else:
1167 params["launch_template_names"] = [template_name]
1168 launch_templates = describe_launch_templates(client, **params)
1169 if launch_templates:
1170 launch_template = launch_templates[0]
1171 launch_template_versions = describe_launch_template_versions(
1172 client, LaunchTemplateId=launch_template["LaunchTemplateId"]
1173 )
1174 return normalize_boto3_result(launch_template), normalize_boto3_result(launch_template_versions)
1175
1176
1177 def params_to_launch_data(
1178 template_params: Dict[str, Any], iam_instance_profile_arn: Optional[str] = None
1179 ) -> Dict[str, Any]:
1180 if iam_instance_profile_arn:
1181 template_params["iam_instance_profile"] = {"arn": iam_instance_profile_arn}
1182 for interface in template_params.get("network_interfaces") or []:
1183 if interface.get("ipv6_addresses"):
1184 interface["ipv6_addresses"] = [{"ipv6_address": x} for x in interface["ipv6_addresses"]]
1185 params = snake_dict_to_camel_dict(
1186 dict((k, v) for k, v in template_params.items() if v is not None),
1187 capitalize_first=True,
1188 )
1189 return params
1190
1191
1192 def validate_string_as_int(module: AnsibleAWSModule, version: str, param_name: str) -> int:
1193 try:
1194 return int(version)
1195 except ValueError:
1196 module.fail_json(msg=f'{param_name} param was not a valid integer, got "{version}"')
1197
1198
1199 def validate_version_deletion(
1200 module: AnsibleAWSModule, launch_template_id: str, existing_versions: List[Dict[str, Any]]
1201 ) -> Tuple[List[str], Optional[int]]:
1202 versions_to_delete = module.params.get("versions_to_delete")
1203 launch_template_versions_to_delete = []
1204 default_version_to_set = None
1205 if versions_to_delete:
1206 unique_versions_to_delete = list(set(versions_to_delete))
1207 launch_template_versions_to_delete = [
1208 t["VersionNumber"] for t in existing_versions if t["VersionNumber"] in unique_versions_to_delete
1209 ]
1210 if len(launch_template_versions_to_delete) != len(unique_versions_to_delete):
1211 missing = [m for m in unique_versions_to_delete if m not in launch_template_versions_to_delete]
1212 module.fail_json(
1213 msg=f"The following versions {missing} do not exist for launch template id '{launch_template_id}'."
1214 )
1215
1216 remaining_versions = [
1217 t["VersionNumber"]
1218 for t in existing_versions
1219 if t["VersionNumber"] not in launch_template_versions_to_delete
1220 ]
1221
1222 # Find the default version
1223 default_version = module.params.get("default_version")
1224 if default_version in (None, ""):
1225 default_version_int = [t["VersionNumber"] for t in existing_versions if t["DefaultVersion"]][0]
1226 elif default_version == "latest":
1227 default_version_int = max(remaining_versions, default=None)
1228 default_version_to_set = default_version_int
1229 else:
1230 default_version_int = validate_string_as_int(module, default_version, "default_version")
1231 default_version_to_set = default_version_int
1232
1233 # Ensure we are not deleting the default version
1234 if default_version_int in launch_template_versions_to_delete or not remaining_versions:
1235 module.fail_json(msg="Cannot delete the launch template default version.")
1236
1237 if default_version_to_set and default_version_to_set not in remaining_versions:
1238 module.fail_json(
1239 msg=f"Could not set version '{default_version_to_set}' as default, "
1240 "the launch template version was not found for the specified launch template id '{launch_template_id}'."
1241 )
1242 else:
1243 # By default delete all non default version before the launch template deletion
1244 launch_template_versions_to_delete = [t["VersionNumber"] for t in existing_versions if not t["DefaultVersion"]]
1245
1246 return [to_text(v) for v in launch_template_versions_to_delete], default_version_to_set
1247
1248
1249 def ensure_absent(
1250 client, module: AnsibleAWSModule, existing: Optional[Dict[str, Any]], existing_versions: List[Dict[str, Any]]
1251 ) -> None:
1252 deleted_versions = []
1253 deleted_template = {}
1254 changed = False
1255
1256 if existing:
1257 launch_template_id = existing["LaunchTemplateId"]
1258 v_to_delete, v_default = validate_version_deletion(module, launch_template_id, existing_versions)
1259
1260 # Update default version
1261 if v_default:
1262 changed = True
1263 if not module.check_mode:
1264 modify_launch_template(
1265 client,
1266 LaunchTemplateId=launch_template_id,
1267 ClientToken=uuid4().hex,
1268 DefaultVersion=to_text(v_default),
1269 )
1270 # Delete versions
1271 if v_to_delete:
1272 changed = True
1273 if not module.check_mode:
1274 response = delete_launch_template_versions(
1275 client, launch_template_id=launch_template_id, versions=v_to_delete
1276 )
1277 if response["UnsuccessfullyDeletedLaunchTemplateVersions"]:
1278 module.warn(
1279 f"Failed to delete template versions {response['UnsuccessfullyDeletedLaunchTemplateVersions']} on"
1280 f" launch template {launch_template_id}"
1281 )
1282 deleted_versions = [
1283 camel_dict_to_snake_dict(v) for v in response["SuccessfullyDeletedLaunchTemplateVersions"]
1284 ]
1285
1286 # Delete the launch template when a list of versions was not specified
1287 if not module.params.get("versions_to_delete"):
1288 changed = True
1289 if not module.check_mode:
1290 deleted_template = delete_launch_template(client, launch_template_id=launch_template_id)
1291 deleted_template = camel_dict_to_snake_dict(deleted_template, ignore_list=["Tags"])
1292 if "tags" in deleted_template:
1293 deleted_template["tags"] = boto3_tag_list_to_ansible_dict(deleted_template.get("tags"))
1294
1295 module.exit_json(changed=changed, deleted_versions=deleted_versions, deleted_template=deleted_template)
1296
1297
1298 def add_launch_template_version(
1299 client,
1300 module: AnsibleAWSModule,
1301 launch_template_id: str,
1302 launch_template_data: Dict[str, Any],
1303 existing_versions: List[Dict[str, Any]],
1304 most_recent_version_number: str,
1305 ) -> int:
1306 source_version = module.params.get("source_version")
1307 version_description = module.params.get("version_description")
1308
1309 params = {
1310 "LaunchTemplateId": launch_template_id,
1311 "ClientToken": uuid4().hex,
1312 "VersionDescription": version_description,
1313 }
1314
1315 if source_version == "latest":
1316 params.update({"SourceVersion": most_recent_version_number})
1317 elif source_version not in (None, ""):
1318 # Source version passed as int
1319 source_version_int = validate_string_as_int(module, source_version, "source_version")
1320 # get source template version
1321 next_source_version = next(
1322 (v for v in existing_versions if v["VersionNumber"] == source_version_int),
1323 None,
1324 )
1325 if next_source_version is None:
1326 module.fail_json(msg=f'source_version does not exist, got "{source_version}"')
1327 params.update({"SourceVersion": str(next_source_version["VersionNumber"])})
1328
1329 if module.check_mode:
1330 module.exit_json(changed=True, msg="Would have created launch template version if not in check mode.")
1331
1332 # Create Launch template version
1333 launch_template_version = create_launch_template_version(
1334 client, launch_template_data=launch_template_data, **params
1335 )
1336 return launch_template_version["VersionNumber"]
1337
1338
1339 def ensure_default_version(
1340 client,
1341 module: AnsibleAWSModule,
1342 launch_template_id: str,
1343 current_default_version_number: int,
1344 most_recent_version_number: int,
1345 ) -> bool:
1346 # Modify default version
1347 default_version = module.params.get("default_version")
1348 changed = False
1349 if default_version not in (None, ""):
1350 if default_version == "latest":
1351 default_version = to_text(most_recent_version_number)
1352 else:
1353 default_version = to_text(validate_string_as_int(module, default_version, "default_version"))
1354 if to_text(current_default_version_number) != default_version:
1355 changed = True
1356 if not module.check_mode:
1357 modify_launch_template(
1358 client,
1359 LaunchTemplateId=launch_template_id,
1360 ClientToken=uuid4().hex,
1361 DefaultVersion=default_version,
1362 )
1363 return changed
1364
1365
1366 def format_module_output(client, module: AnsibleAWSModule) -> Dict[str, Any]:
1367 # Describe launch template
1368 template, template_versions = find_existing(client, module)
1369 template = camel_dict_to_snake_dict(template, ignore_list=["Tags"])
1370 if "tags" in template:
1371 template["tags"] = boto3_tag_list_to_ansible_dict(template.get("tags"))
1372 template_versions = [camel_dict_to_snake_dict(v) for v in template_versions]
1373 result = {
1374 "template": template,
1375 "versions": template_versions,
1376 "default_template": [v for v in template_versions if v.get("default_version")][0],
1377 "latest_template": [
1378 v
1379 for v in template_versions
1380 if (v.get("version_number") and int(v["version_number"]) == int(template["latest_version_number"]))
1381 ][0],
1382 }
1383 if "version_number" in result["default_template"]:
1384 result["default_version"] = result["default_template"]["version_number"]
1385 if "version_number" in result["latest_template"]:
1386 result["latest_version"] = result["latest_template"]["version_number"]
1387 return result
1388
1389
1390 def ensure_present(
1391 client,
1392 module: AnsibleAWSModule,
1393 template_options: Dict[str, Any],
1394 existing: Optional[Dict[str, Any]],
1395 existing_versions: List[Dict[str, Any]],
1396 ) -> None:
1397 template_name = module.params["template_name"]
1398 tags = module.params["tags"]
1399 tag_specifications = module.params.get("tag_specifications")
1400 version_description = module.params.get("version_description")
1401 iam_instance_profile = module.params.get("iam_instance_profile")
1402 # IAM instance profile
1403 if iam_instance_profile:
1404 iam_instance_profile = determine_iam_arn_from_name(module.client("iam"), iam_instance_profile)
1405 # Convert Launch template data
1406 launch_template_data = params_to_launch_data(
1407 dict((k, v) for k, v in module.params.items() if k in template_options), iam_instance_profile
1408 )
1409 # Tag specifications
1410 if tag_specifications:
1411 boto3_tag_specs = []
1412 for tag_spec in tag_specifications:
1413 boto3_tag_specs.extend(boto3_tag_specifications(tag_spec["tags"], types=tag_spec["resource_type"]))
1414 launch_template_data["TagSpecifications"] = boto3_tag_specs
1415 launch_template_data = scrub_none_parameters(launch_template_data, descend_into_lists=True)
1416 changed = False
1417
1418 if not (existing or existing_versions):
1419 # Create Launch template
1420 if module.check_mode:
1421 module.exit_json(changed=True, msg="Would have created launch template if not in check mode.")
1422 create_launch_template(
1423 client,
1424 launch_template_name=template_name,
1425 launch_template_data=launch_template_data,
1426 tags=tags,
1427 ClientToken=uuid4().hex,
1428 VersionDescription=version_description,
1429 )
1430 changed = True
1431 else:
1432 launch_template_id = existing["LaunchTemplateId"]
1433 default_version_number = existing["DefaultVersionNumber"]
1434 most_recent = sorted(existing_versions, key=lambda x: x["VersionNumber"])[-1]
1435 most_recent_version_number = most_recent["VersionNumber"]
1436 if not (
1437 launch_template_data == most_recent["LaunchTemplateData"]
1438 and version_description == most_recent.get("VersionDescription", "")
1439 ):
1440 changed = True
1441 most_recent_version_number = add_launch_template_version(
1442 client,
1443 module,
1444 launch_template_id,
1445 launch_template_data,
1446 existing_versions,
1447 str(most_recent["VersionNumber"]),
1448 )
1449
1450 # Ensure default version
1451 changed |= ensure_default_version(
1452 client, module, launch_template_id, default_version_number, most_recent_version_number
1453 )
1454 # Ensure tags
1455 changed |= ensure_ec2_tags(
1456 client,
1457 module,
1458 launch_template_id,
1459 resource_type="launch-template",
1460 tags=tags,
1461 purge_tags=module.params["purge_tags"],
1462 )
1463
1464 module.exit_json(changed=changed, **format_module_output(client, module))
1465
1466
1467 def main():
1468 template_options = dict(
1469 block_device_mappings=dict(
1470 type="list",
1471 elements="dict",
1472 options=dict(
1473 device_name=dict(),
1474 ebs=dict(
1475 type="dict",
1476 options=dict(
1477 delete_on_termination=dict(type="bool"),
1478 encrypted=dict(type="bool"),
1479 iops=dict(type="int"),
1480 kms_key_id=dict(),
1481 snapshot_id=dict(),
1482 volume_size=dict(type="int"),
1483 volume_type=dict(),
1484 throughput=dict(type="int"),
1485 ),
1486 ),
1487 no_device=dict(),
1488 virtual_name=dict(),
1489 ),
1490 ),
1491 cpu_options=dict(
1492 type="dict",
1493 options=dict(
1494 core_count=dict(type="int"),
1495 threads_per_core=dict(type="int"),
1496 ),
1497 ),
1498 credit_specification=dict(
1499 dict(type="dict"),
1500 options=dict(
1501 cpu_credits=dict(),
1502 ),
1503 ),
1504 disable_api_termination=dict(type="bool"),
1505 ebs_optimized=dict(type="bool"),
1506 elastic_gpu_specifications=dict(
1507 options=dict(type=dict()),
1508 type="list",
1509 elements="dict",
1510 ),
1511 image_id=dict(),
1512 instance_initiated_shutdown_behavior=dict(choices=["stop", "terminate"]),
1513 instance_market_options=dict(
1514 type="dict",
1515 options=dict(
1516 market_type=dict(),
1517 spot_options=dict(
1518 type="dict",
1519 options=dict(
1520 block_duration_minutes=dict(type="int"),
1521 instance_interruption_behavior=dict(choices=["hibernate", "stop", "terminate"]),
1522 max_price=dict(),
1523 spot_instance_type=dict(choices=["one-time", "persistent"]),
1524 ),
1525 ),
1526 ),
1527 ),
1528 instance_type=dict(),
1529 kernel_id=dict(),
1530 key_name=dict(),
1531 monitoring=dict(
1532 type="dict",
1533 options=dict(enabled=dict(type="bool")),
1534 ),
1535 metadata_options=dict(
1536 type="dict",
1537 options=dict(
1538 http_endpoint=dict(choices=["enabled", "disabled"], default="enabled"),
1539 http_put_response_hop_limit=dict(type="int", default=1),
1540 http_tokens=dict(choices=["optional", "required"], default="optional"),
1541 http_protocol_ipv6=dict(choices=["disabled", "enabled"], default="disabled"),
1542 instance_metadata_tags=dict(choices=["disabled", "enabled"], default="disabled"),
1543 ),
1544 ),
1545 network_interfaces=dict(
1546 type="list",
1547 elements="dict",
1548 options=dict(
1549 associate_public_ip_address=dict(type="bool"),
1550 delete_on_termination=dict(type="bool"),
1551 description=dict(),
1552 device_index=dict(type="int"),
1553 groups=dict(type="list", elements="str"),
1554 ipv6_address_count=dict(type="int"),
1555 ipv6_addresses=dict(type="list", elements="str"),
1556 network_interface_id=dict(),
1557 private_ip_address=dict(),
1558 subnet_id=dict(),
1559 ),
1560 ),
1561 placement=dict(
1562 options=dict(
1563 affinity=dict(),
1564 availability_zone=dict(),
1565 group_name=dict(),
1566 host_id=dict(),
1567 tenancy=dict(),
1568 ),
1569 type="dict",
1570 ),
1571 ram_disk_id=dict(),
1572 security_group_ids=dict(type="list", elements="str"),
1573 security_groups=dict(type="list", elements="str"),
1574 user_data=dict(),
1575 )
1576
1577 argument_spec = dict(
1578 state=dict(choices=["present", "absent"], default="present"),
1579 template_name=dict(aliases=["name"]),
1580 template_id=dict(aliases=["id"]),
1581 default_version=dict(default="latest"),
1582 source_version=dict(default="latest"),
1583 version_description=dict(default=""),
1584 iam_instance_profile=dict(),
1585 tags=dict(type="dict", aliases=["resource_tags"]),
1586 purge_tags=dict(type="bool", default=True),
1587 versions_to_delete=dict(type="list", elements="int"),
1588 tag_specifications=dict(
1589 type="list",
1590 elements="dict",
1591 options=dict(
1592 resource_type=dict(
1593 type="str",
1594 default="instance",
1595 choices=["instance", "volume", "network-interface", "spot-instances-request"],
1596 ),
1597 tags=dict(type="dict"),
1598 ),
1599 ),
1600 )
1601
1602 argument_spec.update(template_options)
1603
1604 module = AnsibleAWSModule(
1605 argument_spec=argument_spec,
1606 required_one_of=[
1607 ("template_name", "template_id"),
1608 ],
1609 supports_check_mode=True,
1610 )
1611
1612 state = module.params.get("state")
1613 client = module.client("ec2")
1614 launch_template, launch_template_versions = find_existing(client, module)
1615
1616 try:
1617 if state == "present":
1618 ensure_present(client, module, template_options, launch_template, launch_template_versions)
1619 else:
1620 ensure_absent(client, module, launch_template, launch_template_versions)
1621 except AnsibleEC2Error as e:
1622 module.fail_json_aws_error(e)
1623
1624
1625 if __name__ == "__main__":
1626 main()