Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: ec2_instance_info
10 version_added: 1.0.0
11 short_description: Gather information about ec2 instances in AWS
12 description:
13 - Gather information about EC2 instances in AWS.
14 author:
15 - Michael Schuett (@michaeljs1990)
16 - Rob White (@wimnat)
17 options:
18 instance_ids:
19 description:
20 - If you specify one or more instance IDs, only instances that have the specified IDs are returned.
21 required: false
22 type: list
23 elements: str
24 default: []
25 filters:
26 description:
27 - A dict of filters to apply. Each dict item consists of a filter key and a filter value. See
28 U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) for possible filters. Filter
29 names and values are case sensitive.
30 required: false
31 default: {}
32 type: dict
33 minimum_uptime:
34 description:
35 - Minimum running uptime in minutes of instances. For example if O(uptime) is V(60) return all instances that have run more than 60 minutes.
36 required: false
37 aliases: ['uptime']
38 type: int
39 include_attributes:
40 description:
41 - Describes the specified attributes of the returned instances.
42 required: false
43 type: list
44 elements: str
45 choices:
46 - instanceType
47 - kernel
48 - ramdisk
49 - userData
50 - disableApiTermination
51 - instanceInitiatedShutdownBehavior
52 - rootDeviceName
53 - blockDeviceMapping
54 - productCodes
55 - sourceDestCheck
56 - groupSet
57 - ebsOptimized
58 - sriovNetSupport
59 - enclaveOptions
60 - disableApiStop
61 aliases: ['attributes']
62 version_added: 6.3.0
63
64 extends_documentation_fragment:
65 - amazon.aws.common.modules
66 - amazon.aws.region.modules
67 - amazon.aws.boto3
68 """
69
70 EXAMPLES = r"""
71 # Note: These examples do not set authentication details, see the AWS Guide for details.
72
73 - name: Gather information about all instances
74 amazon.aws.ec2_instance_info:
75
76 - name: Gather information about all instances in AZ ap-southeast-2a
77 amazon.aws.ec2_instance_info:
78 filters:
79 availability-zone: ap-southeast-2a
80
81 - name: Gather information about a particular instance using ID
82 amazon.aws.ec2_instance_info:
83 instance_ids:
84 - i-12345678
85
86 - name: Gather information about any instance with a tag key Name and value Example
87 amazon.aws.ec2_instance_info:
88 filters:
89 "tag:Name": Example
90
91 - name: Gather information about any instance in states "shutting-down", "stopping", "stopped"
92 amazon.aws.ec2_instance_info:
93 filters:
94 instance-state-name: ["shutting-down", "stopping", "stopped"]
95
96 - name: Gather information about any instance with Name beginning with RHEL and an uptime of at least 60 minutes
97 amazon.aws.ec2_instance_info:
98 region: "{{ ec2_region }}"
99 uptime: 60
100 filters:
101 "tag:Name": "RHEL-*"
102 instance-state-name: ["running"]
103 register: ec2_node_info
104
105 - name: Gather information about a particular instance using ID and include kernel attribute
106 amazon.aws.ec2_instance_info:
107 instance_ids:
108 - i-12345678
109 include_attributes:
110 - kernel
111 """
112
113 RETURN = r"""
114 instances:
115 description: A list of ec2 instances.
116 returned: always
117 type: complex
118 contains:
119 ami_launch_index:
120 description: The AMI launch index, which can be used to find this instance in the launch group.
121 returned: always
122 type: int
123 sample: 0
124 architecture:
125 description: The architecture of the image.
126 returned: always
127 type: str
128 sample: x86_64
129 block_device_mappings:
130 description: Any block device mapping entries for the instance.
131 returned: always
132 type: complex
133 contains:
134 device_name:
135 description: The device name exposed to the instance (for example, /dev/sdh or xvdh).
136 returned: always
137 type: str
138 sample: /dev/sdh
139 ebs:
140 description: Parameters used to automatically set up EBS volumes when the instance is launched.
141 returned: always
142 type: complex
143 contains:
144 attach_time:
145 description: The time stamp when the attachment initiated.
146 returned: always
147 type: str
148 sample: "2017-03-23T22:51:24+00:00"
149 delete_on_termination:
150 description: Indicates whether the volume is deleted on instance termination.
151 returned: always
152 type: bool
153 sample: true
154 status:
155 description: The attachment state.
156 returned: always
157 type: str
158 sample: attached
159 volume_id:
160 description: The ID of the EBS volume.
161 returned: always
162 type: str
163 sample: vol-12345678
164 capacity_reservation_specification:
165 description: Information about the Capacity Reservation targeting option.
166 type: complex
167 contains:
168 capacity_reservation_preference:
169 description: Describes the Capacity Reservation preferences.
170 type: str
171 sample: open
172 cpu_options:
173 description: The CPU options set for the instance.
174 returned: always
175 type: complex
176 contains:
177 core_count:
178 description: The number of CPU cores for the instance.
179 returned: always
180 type: int
181 sample: 1
182 threads_per_core:
183 description: The number of threads per CPU core. On supported instance, a value of 1 means Intel Hyper-Threading Technology is disabled.
184 returned: always
185 type: int
186 sample: 1
187 client_token:
188 description: The idempotency token you provided when you launched the instance, if applicable.
189 returned: always
190 type: str
191 sample: mytoken
192 current_instance_boot_mode:
193 description: The boot mode that is used to boot the instance at launch or start.
194 type: str
195 sample: legacy-bios
196 ebs_optimized:
197 description: Indicates whether the instance is optimized for EBS I/O.
198 returned: always
199 type: bool
200 sample: false
201 ena_support:
202 description: Specifies whether enhanced networking with ENA is enabled.
203 returned: always
204 type: bool
205 sample: true
206 enclave_options:
207 description: Indicates whether the instance is enabled for Amazon Web Services Nitro Enclaves.
208 type: dict
209 contains:
210 enabled:
211 description: If this parameter is set to true, the instance is enabled for Amazon Web Services Nitro Enclaves.
212 returned: always
213 type: bool
214 sample: false
215 hibernation_options:
216 description: Indicates whether the instance is enabled for hibernation.
217 type: dict
218 contains:
219 configured:
220 description: If true, your instance is enabled for hibernation; otherwise, it is not enabled for hibernation.
221 returned: always
222 type: bool
223 sample: false
224 hypervisor:
225 description: The hypervisor type of the instance.
226 returned: always
227 type: str
228 sample: xen
229 iam_instance_profile:
230 description: The IAM instance profile associated with the instance, if applicable.
231 type: complex
232 contains:
233 arn:
234 description: The Amazon Resource Name (ARN) of the instance profile.
235 returned: always
236 type: str
237 sample: "arn:aws:iam::123456789012:instance-profile/myprofile"
238 id:
239 description: The ID of the instance profile.
240 returned: always
241 type: str
242 sample: JFJ397FDG400FG9FD1N
243 image_id:
244 description: The ID of the AMI used to launch the instance.
245 returned: always
246 type: str
247 sample: ami-0011223344
248 instance_id:
249 description: The ID of the instance.
250 returned: always
251 type: str
252 sample: i-012345678
253 instance_type:
254 description: The instance type size of the running instance.
255 returned: always
256 type: str
257 sample: t2.micro
258 key_name:
259 description: The name of the key pair, if this instance was launched with an associated key pair.
260 returned: always
261 type: str
262 sample: my-key
263 launch_time:
264 description: The time the instance was launched.
265 returned: always
266 type: str
267 sample: "2017-03-23T22:51:24+00:00"
268 maintenance_options:
269 description: Provides information on the recovery and maintenance options of your instance.
270 returned: always
271 type: dict
272 contains:
273 auto_recovery:
274 description: Provides information on the current automatic recovery behavior of your instance.
275 type: str
276 sample: default
277 metadata_options:
278 description: The metadata options for the instance.
279 returned: always
280 type: complex
281 contains:
282 http_endpoint:
283 description: Indicates whether the HTTP metadata endpoint on your instances is enabled or disabled.
284 type: str
285 sample: enabled
286 http_protocol_ipv6:
287 description: Indicates whether the IPv6 endpoint for the instance metadata service is enabled or disabled.
288 type: str
289 sample: disabled
290 http_put_response_hop_limit:
291 description: The maximum number of hops that the metadata token can travel.
292 type: int
293 sample: 1
294 http_tokens:
295 description: Indicates whether IMDSv2 is required.
296 type: str
297 sample: optional
298 instance_metadata_tags:
299 description: Indicates whether access to instance tags from the instance metadata is enabled or disabled.
300 type: str
301 sample: disabled
302 state:
303 description: The state of the metadata option changes.
304 type: str
305 sample: applied
306 monitoring:
307 description: The monitoring for the instance.
308 returned: always
309 type: complex
310 contains:
311 state:
312 description: Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled.
313 returned: always
314 type: str
315 sample: disabled
316 network_interfaces:
317 description: One or more network interfaces for the instance.
318 returned: always
319 type: complex
320 contains:
321 association:
322 description: The association information for an Elastic IPv4 associated with the network interface.
323 returned: always
324 type: complex
325 contains:
326 ip_owner_id:
327 description: The ID of the owner of the Elastic IP address.
328 returned: always
329 type: str
330 sample: amazon
331 public_dns_name:
332 description: The public DNS name.
333 returned: always
334 type: str
335 sample: ""
336 public_ip:
337 description: The public IP address or Elastic IP address bound to the network interface.
338 returned: always
339 type: str
340 sample: 1.2.3.4
341 attachment:
342 description: The network interface attachment.
343 returned: always
344 type: complex
345 contains:
346 attach_time:
347 description: The time stamp when the attachment initiated.
348 returned: always
349 type: str
350 sample: "2017-03-23T22:51:24+00:00"
351 attachment_id:
352 description: The ID of the network interface attachment.
353 returned: always
354 type: str
355 sample: eni-attach-3aff3f
356 delete_on_termination:
357 description: Indicates whether the network interface is deleted when the instance is terminated.
358 returned: always
359 type: bool
360 sample: true
361 device_index:
362 description: The index of the device on the instance for the network interface attachment.
363 returned: always
364 type: int
365 sample: 0
366 network_card_index:
367 description: The index of the network card.
368 returned: always
369 type: int
370 sample: 0
371 status:
372 description: The attachment state.
373 returned: always
374 type: str
375 sample: attached
376 description:
377 description: The description.
378 returned: always
379 type: str
380 sample: My interface
381 groups:
382 description: One or more security groups.
383 returned: always
384 type: list
385 elements: dict
386 contains:
387 group_id:
388 description: The ID of the security group.
389 returned: always
390 type: str
391 sample: sg-abcdef12
392 group_name:
393 description: The name of the security group.
394 returned: always
395 type: str
396 sample: mygroup
397 interface_type:
398 description: The type of network interface.
399 returned: always
400 type: str
401 sample: interface
402 ipv6_addresses:
403 description: One or more IPv6 addresses associated with the network interface.
404 returned: always
405 type: list
406 elements: dict
407 contains:
408 ipv6_address:
409 description: The IPv6 address.
410 returned: always
411 type: str
412 sample: "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
413 mac_address:
414 description: The MAC address.
415 returned: always
416 type: str
417 sample: "00:11:22:33:44:55"
418 network_interface_id:
419 description: The ID of the network interface.
420 returned: always
421 type: str
422 sample: eni-01234567
423 owner_id:
424 description: The AWS account ID of the owner of the network interface.
425 returned: always
426 type: str
427 sample: 01234567890
428 private_dns_name:
429 description: The private DNS hostname name assigned to the instance.
430 type: str
431 returned: always
432 sample: ip-10-1-0-156.ec2.internal
433 private_ip_address:
434 description: The IPv4 address of the network interface within the subnet.
435 returned: always
436 type: str
437 sample: 10.0.0.1
438 private_ip_addresses:
439 description: The private IPv4 addresses associated with the network interface.
440 returned: always
441 type: list
442 elements: dict
443 contains:
444 association:
445 description: The association information for an Elastic IP address (IPv4) associated with the network interface.
446 type: complex
447 contains:
448 ip_owner_id:
449 description: The ID of the owner of the Elastic IP address.
450 returned: always
451 type: str
452 sample: amazon
453 public_dns_name:
454 description: The public DNS name.
455 returned: always
456 type: str
457 sample: ""
458 public_ip:
459 description: The public IP address or Elastic IP address bound to the network interface.
460 returned: always
461 type: str
462 sample: 1.2.3.4
463 primary:
464 description: Indicates whether this IPv4 address is the primary private IP address of the network interface.
465 returned: always
466 type: bool
467 sample: true
468 private_dns_name:
469 description: The private DNS hostname name assigned to the instance.
470 type: str
471 returned: always
472 sample: ip-10-1-0-156.ec2.internal
473 private_ip_address:
474 description: The private IPv4 address of the network interface.
475 returned: always
476 type: str
477 sample: 10.0.0.1
478 source_dest_check:
479 description: Indicates whether source/destination checking is enabled.
480 returned: always
481 type: bool
482 sample: true
483 status:
484 description: The status of the network interface.
485 returned: always
486 type: str
487 sample: in-use
488 subnet_id:
489 description: The ID of the subnet for the network interface.
490 returned: always
491 type: str
492 sample: subnet-0123456
493 vpc_id:
494 description: The ID of the VPC for the network interface.
495 returned: always
496 type: str
497 sample: vpc-0123456
498 placement:
499 description: The location where the instance launched, if applicable.
500 returned: always
501 type: complex
502 contains:
503 availability_zone:
504 description: The Availability Zone of the instance.
505 returned: always
506 type: str
507 sample: ap-southeast-2a
508 group_name:
509 description: The name of the placement group the instance is in (for cluster compute instances).
510 returned: always
511 type: str
512 sample: ""
513 tenancy:
514 description: The tenancy of the instance (if the instance is running in a VPC).
515 returned: always
516 type: str
517 sample: default
518 platform_details:
519 description: The platform details value for the instance.
520 returned: always
521 type: str
522 sample: Linux/UNIX
523 private_dns_name:
524 description: The private DNS name.
525 returned: always
526 type: str
527 sample: ip-10-0-0-1.ap-southeast-2.compute.internal
528 private_dns_name_options:
529 description: The options for the instance hostname.
530 type: dict
531 contains:
532 enable_resource_name_dns_a_record:
533 description: Indicates whether to respond to DNS queries for instance hostnames with DNS A records.
534 type: bool
535 sample: false
536 enable_resource_name_dns_aaaa_record:
537 description: Indicates whether to respond to DNS queries for instance hostnames with DNS AAAA records.
538 type: bool
539 sample: false
540 hostname_type:
541 description: The type of hostname to assign to an instance.
542 type: str
543 sample: ip-name
544 private_ip_address:
545 description: The IPv4 address of the network interface within the subnet.
546 returned: always
547 type: str
548 sample: 10.0.0.1
549 product_codes:
550 description: One or more product codes.
551 returned: always
552 type: list
553 elements: dict
554 contains:
555 product_code_id:
556 description: The product code.
557 returned: always
558 type: str
559 sample: aw0evgkw8ef3n2498gndfgasdfsd5cce
560 product_code_type:
561 description: The type of product code.
562 returned: always
563 type: str
564 sample: marketplace
565 public_dns_name:
566 description: The public DNS name assigned to the instance.
567 returned: always
568 type: str
569 sample:
570 public_ip_address:
571 description: The public IPv4 address assigned to the instance.
572 returned: always
573 type: str
574 sample: 52.0.0.1
575 root_device_name:
576 description: The device name of the root device.
577 returned: always
578 type: str
579 sample: /dev/sda1
580 root_device_type:
581 description: The type of root device used by the AMI.
582 returned: always
583 type: str
584 sample: ebs
585 security_groups:
586 description: One or more security groups for the instance.
587 returned: always
588 type: list
589 elements: dict
590 contains:
591 group_id:
592 description: The ID of the security group.
593 returned: always
594 type: str
595 sample: sg-0123456
596 group_name:
597 description: The name of the security group.
598 returned: always
599 type: str
600 sample: my-security-group
601 source_dest_check:
602 description: Indicates whether source/destination checking is enabled.
603 returned: always
604 type: bool
605 sample: true
606 state:
607 description: The current state of the instance.
608 returned: always
609 type: complex
610 contains:
611 code:
612 description: The low byte represents the state.
613 returned: always
614 type: int
615 sample: 16
616 name:
617 description: The name of the state.
618 returned: always
619 type: str
620 sample: running
621 state_transition_reason:
622 description: The reason for the most recent state transition.
623 returned: always
624 type: str
625 sample:
626 subnet_id:
627 description: The ID of the subnet in which the instance is running.
628 returned: always
629 type: str
630 sample: subnet-00abcdef
631 tags:
632 description: Any tags assigned to the instance.
633 returned: always
634 type: dict
635 sample:
636 virtualization_type:
637 description: The type of virtualization of the AMI.
638 returned: always
639 type: str
640 sample: hvm
641 vpc_id:
642 description: The ID of the VPC the instance is in.
643 returned: always
644 type: dict
645 sample: vpc-0011223344
646 attributes:
647 description: The details of the instance attribute specified on input.
648 returned: when O(include_attributes) is specified
649 type: dict
650 sample:
651 {
652 'disable_api_termination': {
653 'value': True
654 },
655 'ebs_optimized': {
656 'value': True
657 }
658 }
659 version_added: 6.3.0
660 """
661
662 import datetime
663 from typing import Any
664 from typing import Dict
665 from typing import List
666
667 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
668
669 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
670 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_instance_attribute
671 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_instances
672 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
673 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
674 from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
675
676
677 def list_ec2_instances(connection, module: AnsibleAWSModule) -> None:
678 instance_ids = module.params.get("instance_ids")
679 uptime = module.params.get("minimum_uptime")
680 filters = ansible_dict_to_boto3_filter_list(module.params.get("filters"))
681
682 reservations = describe_instances(connection, InstanceIds=instance_ids, Filters=filters)
683 instances = []
684 oldest_launch_time = None
685
686 if uptime:
687 timedelta = int(uptime) if uptime else 0
688 oldest_launch_time = datetime.datetime.now() - datetime.timedelta(minutes=timedelta)
689
690 # Get instances from reservations
691 for reservation in reservations:
692 instances.extend(
693 [
694 instance
695 for instance in reservation["Instances"]
696 if oldest_launch_time is None or instance["LaunchTime"].replace(tzinfo=None) < oldest_launch_time
697 ]
698 )
699
700 # include instances attributes
701 attributes = module.params.get("include_attributes")
702 if attributes:
703 for instance in instances:
704 instance["attributes"] = describe_instance_attributes(connection, instance["InstanceId"], attributes)
705
706 # Turn the boto3 result in to ansible_friendly_snaked_names
707 snaked_instances = [camel_dict_to_snake_dict(instance) for instance in instances]
708
709 # Turn the boto3 result in to ansible friendly tag dictionary
710 for instance in snaked_instances:
711 instance["tags"] = boto3_tag_list_to_ansible_dict(instance.get("tags", []), "key", "value")
712
713 module.exit_json(instances=snaked_instances)
714
715
716 def describe_instance_attributes(connection, instance_id: str, attributes: List[str]) -> Dict[str, Any]:
717 result = {}
718 for attr in attributes:
719 response = describe_instance_attribute(connection, instance_id=instance_id, attribute=attr)
720 for key in response:
721 if key not in ("InstanceId", "ResponseMetadata"):
722 result[key] = response[key]
723 return result
724
725
726 def main():
727 instance_attributes = [
728 "instanceType",
729 "kernel",
730 "ramdisk",
731 "userData",
732 "disableApiTermination",
733 "instanceInitiatedShutdownBehavior",
734 "rootDeviceName",
735 "blockDeviceMapping",
736 "productCodes",
737 "sourceDestCheck",
738 "groupSet",
739 "ebsOptimized",
740 "sriovNetSupport",
741 "enclaveOptions",
742 "disableApiStop",
743 ]
744 argument_spec = dict(
745 minimum_uptime=dict(required=False, type="int", default=None, aliases=["uptime"]),
746 instance_ids=dict(default=[], type="list", elements="str"),
747 filters=dict(default={}, type="dict"),
748 include_attributes=dict(type="list", elements="str", aliases=["attributes"], choices=instance_attributes),
749 )
750
751 module = AnsibleAWSModule(
752 argument_spec=argument_spec,
753 mutually_exclusive=[["instance_ids", "filters"]],
754 supports_check_mode=True,
755 )
756
757 connection = module.client("ec2")
758 try:
759 list_ec2_instances(connection, module)
760 except AnsibleEC2Error as e:
761 module.fail_json_aws_error(e)
762
763
764 if __name__ == "__main__":
765 main()