Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_spot_instance.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: ec2_spot_instance
10 version_added: 2.0.0
11 short_description: Request, stop, reboot or cancel spot instance
12 description:
13 - Creates or cancels spot instance requests.
14 author:
15 - Sri Rachana Achyuthuni (@srirachanaachyuthuni)
16 options:
17 zone_group:
18 description:
19 - Name for logical grouping of spot requests.
20 - All spot instances in the request are launched in the same availability zone.
21 type: str
22 client_token:
23 description: The idempotency token you provided when you launched the instance, if applicable.
24 type: str
25 count:
26 description:
27 - Number of instances to launch.
28 default: 1
29 type: int
30 interruption:
31 description:
32 - The behavior when a Spot Instance is interrupted.
33 choices: [ "hibernate", "stop", "terminate" ]
34 type: str
35 default: terminate
36 launch_group:
37 description:
38 - Launch group for spot requests, see U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/how-spot-instances-work.html#spot-launch-group).
39 type: str
40 launch_specification:
41 description:
42 - The launch specification.
43 type: dict
44 suboptions:
45 security_group_ids:
46 description:
47 - Security group id (or list of ids) to use with the instance.
48 type: list
49 elements: str
50 security_groups:
51 description:
52 - Security group name (or list of group names) to use with the instance.
53 - Only supported with EC2 Classic. To launch in a VPC, use O(launch_specification.security_group_ids).
54 type: list
55 elements: str
56 key_name:
57 description:
58 - Key to use on the instance.
59 - The SSH key must already exist in AWS in order to use this argument.
60 - Keys can be created / deleted using the M(amazon.aws.ec2_key) module.
61 type: str
62 subnet_id:
63 description:
64 - The ID of the subnet in which to launch the instance.
65 type: str
66 user_data:
67 description:
68 - The base64-encoded user data for the instance. User data is limited to 16 KB.
69 type: str
70 block_device_mappings:
71 description:
72 - A list of hash/dictionaries of volumes to add to the new instance.
73 type: list
74 elements: dict
75 suboptions:
76 device_name:
77 description:
78 - The device name (for example, /dev/sdh or xvdh).
79 type: str
80 virtual_name:
81 description:
82 - The virtual device name
83 type: str
84 ebs:
85 description:
86 - Parameters used to automatically set up EBS volumes when the instance is launched,
87 see U(https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.request_spot_instances).
88 type: dict
89 no_device:
90 description:
91 - To omit the device from the block device mapping, specify an empty string.
92 type: str
93 ebs_optimized:
94 description:
95 - Whether instance is using optimized EBS volumes, see U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html).
96 default: false
97 type: bool
98 iam_instance_profile:
99 description:
100 - The IAM instance profile.
101 type: dict
102 suboptions:
103 arn:
104 description:
105 - The Amazon Resource Name (ARN) of the instance profile.
106 - Only one of O(launch_specification.iam_instance_profile.arn) or I(launch_specification.iam_instance_profile.name) may be specified.
107 type: str
108 name:
109 description:
110 - The name of the instance profile.
111 - Only one of O(launch_specification.iam_instance_profile.arn) or I(launch_specification.iam_instance_profile.name) may be specified.
112 type: str
113 image_id:
114 description:
115 - The ID of the AMI.
116 type: str
117 instance_type:
118 description:
119 - Instance type to use for the instance, see U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html).
120 - Required when creating a new instance.
121 type: str
122 kernel_id:
123 description:
124 - The ID of the kernel.
125 type: str
126 network_interfaces:
127 description:
128 - One or more network interfaces. If you specify a network interface, you must specify subnet IDs and security group IDs using the network interface.
129 type: list
130 elements: dict
131 default: []
132 suboptions:
133 associate_public_ip_address:
134 description:
135 - Indicates whether to assign a public IPv4 address to an instance you launch in a VPC.
136 type: bool
137 delete_on_termination:
138 description:
139 - If set to true , the interface is deleted when the instance is terminated.
140 You can specify true only if creating a new network interface when launching an instance.
141 type: bool
142 description:
143 description:
144 - The description of the network interface. Applies only if creating a network interface when launching an instance.
145 type: str
146 device_index:
147 description:
148 - The position of the network interface in the attachment order. A primary network interface has a device index of 0.
149 - If you specify a network interface when launching an instance, you must specify the device index.
150 type: int
151 groups:
152 description:
153 - The IDs of the security groups for the network interface. Applies only if creating a network interface when launching an instance.
154 type: list
155 elements: str
156 ipv6_address_count:
157 description:
158 - A number of IPv6 addresses to assign to the network interface
159 type: int
160 ipv6_addresses:
161 description:
162 - One or more IPv6 addresses to assign to the network interface.
163 type: list
164 elements: dict
165 suboptions:
166 ipv6address:
167 description: The IPv6 address.
168 type: str
169 network_interface_id:
170 description:
171 - The ID of the network interface.
172 type: str
173 private_ip_address:
174 description:
175 - The private IPv4 address of the network interface
176 type: str
177 private_ip_addresses:
178 description:
179 - One or more private IPv4 addresses to assign to the network interface
180 type: list
181 elements: dict
182 secondary_private_ip_address_count:
183 description:
184 - The number of secondary private IPv4 addresses.
185 type: int
186 subnet_id:
187 description:
188 - The ID of the subnet associated with the network interface
189 type: str
190 associate_carrier_ip_address:
191 description:
192 - Indicates whether to assign a carrier IP address to the network interface.
193 type: bool
194 interface_type:
195 description:
196 - The type of network interface.
197 type: str
198 choices: ['interface', 'efa']
199 network_card_index:
200 description:
201 - The index of the network card.
202 type: int
203 ipv4_prefixes:
204 description:
205 - One or more IPv4 delegated prefixes to be assigned to the network interface.
206 type: list
207 elements: dict
208 ipv4_prefix_count:
209 description:
210 - The number of IPv4 delegated prefixes to be automatically assigned to the network interface
211 type: int
212 ipv6_prefixes:
213 description:
214 - One or more IPv6 delegated prefixes to be assigned to the network interface
215 type: list
216 elements: dict
217 ipv6_prefix_count:
218 description:
219 - The number of IPv6 delegated prefixes to be automatically assigned to the network interface
220 type: int
221 placement:
222 description:
223 - The placement information for the instance.
224 type: dict
225 suboptions:
226 availability_zone:
227 description:
228 - The Availability Zone.
229 type: str
230 group_name:
231 description:
232 - The name of the placement group.
233 type: str
234 tenancy:
235 description:
236 - the tenancy of the host
237 type: str
238 choices: ['default', 'dedicated', 'host']
239 default: default
240 ramdisk_id:
241 description:
242 - The ID of the RAM disk.
243 type: str
244 monitoring:
245 description:
246 - Indicates whether basic or detailed monitoring is enabled for the instance.
247 type: dict
248 suboptions:
249 enabled:
250 description:
251 - Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled.
252 type: bool
253 default: false
254 state:
255 description:
256 - Whether the spot request should be created or removed.
257 - When O(state=present), O(launch_specification) is required.
258 - When O(state=absent), O(spot_instance_request_ids) is required.
259 default: 'present'
260 choices: [ 'absent', 'present' ]
261 type: str
262 spot_price:
263 description:
264 - Maximum spot price to bid. If not set, a regular on-demand instance is requested.
265 - A spot request is made with this maximum bid. When it is filled, the instance is started.
266 type: str
267 spot_type:
268 description:
269 - The type of spot request.
270 - After being interrupted a V(persistent) spot instance will be started once there is capacity to fill the request again.
271 default: 'one-time'
272 choices: [ "one-time", "persistent" ]
273 type: str
274 tags:
275 description:
276 - A dictionary of key-value pairs for tagging the Spot Instance request on creation.
277 type: dict
278 spot_instance_request_ids:
279 description:
280 - List of strings with IDs of spot requests to be cancelled
281 type: list
282 elements: str
283 terminate_instances:
284 description:
285 - Boolean value to set whether or not to terminate instances associated to spot request.
286 - Can be used only when O(state=absent).
287 default: False
288 type: bool
289 version_added: 5.4.0
290 extends_documentation_fragment:
291 - amazon.aws.common.modules
292 - amazon.aws.region.modules
293 - amazon.aws.boto3
294 """
295
296 EXAMPLES = r"""
297 # Note: These examples do not set authentication details, see the AWS Guide for details.
298
299 - name: Simple Spot Request Creation
300 amazon.aws.ec2_spot_instance:
301 launch_specification:
302 image_id: ami-123456789
303 key_name: my-keypair
304 instance_type: t2.medium
305
306 - name: Spot Request Creation with more options
307 amazon.aws.ec2_spot_instance:
308 launch_specification:
309 image_id: ami-123456789
310 key_name: my-keypair
311 instance_type: t2.medium
312 subnet_id: subnet-12345678
313 block_device_mappings:
314 - device_name: /dev/sdb
315 ebs:
316 delete_on_termination: true
317 volume_type: gp3
318 volume_size: 5
319 - device_name: /dev/sdc
320 ebs:
321 delete_on_termination: true
322 volume_type: io2
323 volume_size: 30
324 network_interfaces:
325 - associate_public_ip_address: false
326 delete_on_termination: true
327 device_index: 0
328 placement:
329 availability_zone: us-west-2a
330 monitoring:
331 enabled: false
332 spot_price: 0.002
333 tags:
334 Environment: Testing
335
336 - name: Spot Request Termination
337 amazon.aws.ec2_spot_instance:
338 spot_instance_request_ids: ['sir-12345678', 'sir-abcdefgh']
339 state: absent
340 """
341
342 RETURN = r"""
343 spot_request:
344 description: The spot instance request details after creation.
345 returned: when success
346 type: dict
347 sample: {
348 "create_time": "2021-08-23T22:59:12+00:00",
349 "instance_interruption_behavior": "terminate",
350 "launch_specification": {
351 "block_device_mappings": [
352 {
353 "device_name": "/dev/sdb",
354 "ebs": {
355 "delete_on_termination": true,
356 "volume_size": 5,
357 "volume_type": "gp3"
358 }
359 }
360 ],
361 "ebs_optimized": false,
362 "iam_instance_profile": {
363 "arn": "arn:aws:iam::EXAMPLE:instance-profile/myinstanceprofile"
364 },
365 "image_id": "ami-083ac7c7ecf9bb9b0",
366 "instance_type": "t2.small",
367 "key_name": "mykey",
368 "monitoring": {
369 "enabled": false
370 },
371 "network_interfaces": [
372 {
373 "associate_public_ip_address": false,
374 "delete_on_termination": true,
375 "device_index": 0
376 }
377 ],
378 "placement": {
379 "availability_zone": "us-west-2a",
380 "tenancy": "default"
381 },
382 "security_groups": [
383 {
384 "group_name": "default"
385 }
386 ]
387 },
388 "product_description": "Linux/UNIX",
389 "spot_instance_request_id": "sir-1234abcd",
390 "spot_price": "0.00600",
391 "state": "open",
392 "status": {
393 "code": "pending-evaluation",
394 "message": "Your Spot request has been submitted for review, and is pending evaluation.",
395 "update_time": "2021-08-23T22:59:12+00:00"
396 },
397 "tags": {},
398 "type": "one-time"
399 }
400
401 cancelled_spot_request:
402 description: Details of the cancelled spot instance request.
403 type: str
404 returned: when cancellation is successful
405 sample: 'Spot requests with IDs: sir-1234abcd have been cancelled'
406 """
407
408 # TODO: add support for datetime-based parameters
409 # import datetime
410 # import time
411
412 from typing import Any
413 from typing import Dict
414
415 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
416 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
417
418 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
419 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import cancel_spot_instance_requests
420 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_spot_instance_requests
421 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import request_spot_instances
422 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import terminate_instances
423 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
424 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
425 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
426
427
428 def build_launch_specification(launch_spec: Dict[str, Any]) -> Dict[str, Any]:
429 """
430 Remove keys that have a value of None from Launch Specification
431 Descend into these subkeys:
432 network_interfaces
433 block_device_mappings
434 monitoring
435 placement
436 iam_instance_profile
437 """
438 assigned_keys = dict((k, v) for k, v in launch_spec.items() if v is not None)
439
440 sub_key_to_build = ["placement", "iam_instance_profile", "monitoring"]
441 for subkey in sub_key_to_build:
442 if launch_spec[subkey] is not None:
443 assigned_keys[subkey] = dict((k, v) for k, v in launch_spec[subkey].items() if v is not None)
444
445 if launch_spec["network_interfaces"] is not None:
446 interfaces = []
447 for iface in launch_spec["network_interfaces"]:
448 interfaces.append(dict((k, v) for k, v in iface.items() if v is not None))
449 assigned_keys["network_interfaces"] = interfaces
450
451 if launch_spec["block_device_mappings"] is not None:
452 block_devs = []
453 for dev in launch_spec["block_device_mappings"]:
454 block_devs.append(dict((k, v) for k, v in dev.items() if v is not None))
455 assigned_keys["block_device_mappings"] = block_devs
456
457 return snake_dict_to_camel_dict(assigned_keys, capitalize_first=True)
458
459
460 def _request(module: AnsibleAWSModule, connection) -> None:
461 # request_spot_instances() always creates a new spot request
462 changed = True
463
464 if module.check_mode:
465 module.exit_json(changed=changed)
466
467 params = {}
468
469 if module.params.get("launch_specification"):
470 params["LaunchSpecification"] = build_launch_specification(module.params.get("launch_specification"))
471
472 if module.params.get("zone_group"):
473 params["AvailabilityZoneGroup"] = module.params.get("zone_group")
474
475 if module.params.get("count"):
476 params["InstanceCount"] = module.params.get("count")
477
478 if module.params.get("launch_group"):
479 params["LaunchGroup"] = module.params.get("launch_group")
480
481 if module.params.get("spot_price"):
482 params["SpotPrice"] = module.params.get("spot_price")
483
484 if module.params.get("spot_type"):
485 params["Type"] = module.params.get("spot_type")
486
487 if module.params.get("client_token"):
488 params["ClientToken"] = module.params.get("client_token")
489
490 if module.params.get("interruption"):
491 params["InstanceInterruptionBehavior"] = module.params.get("interruption")
492
493 if module.params.get("tags"):
494 params["TagSpecifications"] = [
495 {
496 "ResourceType": "spot-instances-request",
497 "Tags": ansible_dict_to_boto3_tag_list(module.params.get("tags")),
498 }
499 ]
500
501 # TODO: add support for datetime-based parameters
502 # params['ValidFrom'] = module.params.get('valid_from')
503 # params['ValidUntil'] = module.params.get('valid_until')
504
505 try:
506 request_spot_instance_response = request_spot_instances(connection, **params)[0]
507 except AnsibleEC2Error as e:
508 module.fail_json_aws(e, msg="Error while creating the spot instance request")
509
510 request_spot_instance_response["Tags"] = boto3_tag_list_to_ansible_dict(
511 request_spot_instance_response.get("Tags", [])
512 )
513 spot_request = camel_dict_to_snake_dict(request_spot_instance_response, ignore_list=["Tags"])
514 module.exit_json(spot_request=spot_request, changed=changed)
515
516
517 def _cancel(module: AnsibleAWSModule, connection) -> None:
518 changed = False
519 spot_instance_request_ids = module.params.get("spot_instance_request_ids")
520 try:
521 requests_exist = describe_spot_instance_requests(
522 connection,
523 SpotInstanceRequestIds=spot_instance_request_ids,
524 Filters=[{"Name": "state", "Values": ["open", "active"]}],
525 )
526 except AnsibleEC2Error as e:
527 module.fail_json_aws(e, msg="Failure when describing spot requests")
528
529 if len(requests_exist) > 0:
530 changed = True
531 if module.check_mode:
532 module.exit_json(changed=changed, msg=f"Would have cancelled Spot request {spot_instance_request_ids}")
533
534 try:
535 cancel_spot_instance_requests(connection, spot_instance_request_ids)
536 except AnsibleEC2Error as e:
537 module.fail_json_aws(e, msg="Error while cancelling the spot instance request")
538
539 if module.params.get("terminate_instances") is True:
540 instance_ids = [request["InstanceId"] for request in requests_exist]
541 try:
542 terminate_instances(connection, instance_ids=instance_ids)
543 except AnsibleEC2Error as e:
544 module.fail_json_aws(e, msg=f"Failed to terminate instances with Ids={instance_ids}")
545
546 module.exit_json(changed=changed, msg=f"Cancelled Spot request {spot_instance_request_ids}")
547 else:
548 module.exit_json(changed=changed, msg="Spot request not found or already cancelled")
549
550
551 def main() -> None:
552 network_interface_options = dict(
553 associate_public_ip_address=dict(type="bool"),
554 delete_on_termination=dict(type="bool"),
555 description=dict(type="str"),
556 device_index=dict(type="int"),
557 groups=dict(type="list", elements="str"),
558 ipv6_address_count=dict(type="int"),
559 ipv6_addresses=dict(type="list", elements="dict", options=dict(ipv6address=dict(type="str"))),
560 network_interface_id=dict(type="str"),
561 private_ip_address=dict(type="str"),
562 private_ip_addresses=dict(type="list", elements="dict"),
563 secondary_private_ip_address_count=dict(type="int"),
564 subnet_id=dict(type="str"),
565 associate_carrier_ip_address=dict(type="bool"),
566 interface_type=dict(type="str", choices=["interface", "efa"]),
567 network_card_index=dict(type="int"),
568 ipv4_prefixes=dict(type="list", elements="dict"),
569 ipv4_prefix_count=dict(type="int"),
570 ipv6_prefixes=dict(type="list", elements="dict"),
571 ipv6_prefix_count=dict(type="int"),
572 )
573 block_device_mappings_options = dict(
574 device_name=dict(type="str"),
575 virtual_name=dict(type="str"),
576 ebs=dict(type="dict"),
577 no_device=dict(type="str"),
578 )
579 monitoring_options = dict(enabled=dict(type="bool", default=False))
580 placement_options = dict(
581 availability_zone=dict(type="str"),
582 group_name=dict(type="str"),
583 tenancy=dict(type="str", choices=["default", "dedicated", "host"], default="default"),
584 )
585 iam_instance_profile_options = dict(arn=dict(type="str"), name=dict(type="str"))
586 launch_specification_options = dict(
587 security_group_ids=dict(type="list", elements="str"),
588 security_groups=dict(type="list", elements="str"),
589 block_device_mappings=dict(type="list", elements="dict", options=block_device_mappings_options),
590 ebs_optimized=dict(type="bool", default=False),
591 iam_instance_profile=dict(type="dict", options=iam_instance_profile_options),
592 image_id=dict(type="str"),
593 instance_type=dict(type="str"),
594 kernel_id=dict(type="str"),
595 key_name=dict(type="str"),
596 monitoring=dict(type="dict", options=monitoring_options),
597 network_interfaces=dict(type="list", elements="dict", options=network_interface_options, default=[]),
598 placement=dict(type="dict", options=placement_options),
599 ramdisk_id=dict(type="str"),
600 user_data=dict(type="str"),
601 subnet_id=dict(type="str"),
602 )
603
604 argument_spec = dict(
605 zone_group=dict(type="str"),
606 client_token=dict(type="str", no_log=False),
607 count=dict(type="int", default=1),
608 interruption=dict(type="str", default="terminate", choices=["hibernate", "stop", "terminate"]),
609 launch_group=dict(type="str"),
610 launch_specification=dict(type="dict", options=launch_specification_options),
611 state=dict(default="present", choices=["present", "absent"]),
612 spot_price=dict(type="str"),
613 spot_type=dict(default="one-time", choices=["one-time", "persistent"]),
614 tags=dict(type="dict"),
615 # valid_from=dict(type='datetime', default=datetime.datetime.now()),
616 # valid_until=dict(type='datetime', default=(datetime.datetime.now() + datetime.timedelta(minutes=60))
617 spot_instance_request_ids=dict(type="list", elements="str"),
618 terminate_instances=dict(type="bool", default="False"),
619 )
620
621 module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)
622
623 state = module.params["state"]
624
625 if module.params.get("terminate_instances") and state != "absent":
626 module.fail_json("terminate_instances can only be used when state is absent.")
627
628 connection = module.client("ec2")
629
630 if state == "present":
631 _request(module, connection)
632
633 if state == "absent":
634 _cancel(module, connection)
635
636
637 if __name__ == "__main__":
638 main()