Debian Codegraph @

ansible_collections/amazon/aws/plugins/inventory/aws_ec2.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2017 Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 DOCUMENTATION = r"""
7 name: aws_ec2
8 short_description: EC2 inventory source
9 extends_documentation_fragment:
10 - inventory_cache
11 - constructed
12 - amazon.aws.boto3
13 - amazon.aws.common.plugins
14 - amazon.aws.region.plugins
15 - amazon.aws.assume_role.plugins
16 description:
17 - Get inventory hosts from Amazon Web Services EC2.
18 - The inventory file is a YAML configuration file and must end with C(aws_ec2.{yml|yaml}). For example - C(my_inventory.aws_ec2.yml).
19 notes:
20 - If no credentials are provided and the control node has an associated IAM instance profile then the
21 role will be used for authentication.
22 - The C(tags) host variable is deprecated and will be removed in a release after 2026-12-01.
23 Use C(ec2_tags) instead to avoid conflicts with Ansible reserved variable names.
24 - The C(ec2_tags) host variable was added in version 11.2.0.
25 - The C(use_contrib_script_compatible_ec2_tag_keys) option is deprecated and will be removed in a release after 2026-12-01.
26 Use the C(ec2_tags) structure instead (e.g. use C(ec2_tags.TAGNAME) rather than C(ec2_tag_TAGNAME)).
27 - The C(use_contrib_script_compatible_sanitization) option is deprecated and will be removed in a release after 2026-12-01.
28 Use Ansible's default group name sanitization instead.
29 author:
30 - Sloane Hertel (@s-hertel)
31 options:
32 regions:
33 description:
34 - A list of regions in which to describe EC2 instances.
35 - If empty (the default) default this will include all regions, except possibly restricted ones like V(us-gov-west-1) and V(cn-north-1).
36 type: list
37 elements: str
38 default: []
39 hostnames:
40 description:
41 - A list in order of precedence for hostname variables.
42 - The elements of the list can be a dict with the keys mentioned below or a string.
43 - Can be one of the options specified in U(http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options).
44 - If value provided does not exist in the above options, it will be used as a literal string.
45 - To use tags as hostnames use the syntax tag:Name=Value to use the hostname Name_Value, or tag:Name to use the value of the Name tag.
46 - Jinja2 filters can be added to the hostnames string. Added in version 9.2.0.
47 type: list
48 elements: raw
49 default: []
50 suboptions:
51 name:
52 description:
53 - Name of the host.
54 type: str
55 required: true
56 prefix:
57 description:
58 - Prefix to prepend to O(hostnames.name). Same options as O(hostnames.name).
59 - If O(hostnames.prefix) is specified, final hostname will be O(hostnames.prefix) + O(hostnames.separator) + O(hostnames.name).
60 type: str
61 default: ''
62 required: false
63 separator:
64 description:
65 - Value to separate O(hostnames.prefix) and O(hostnames.name) when O(hostnames.prefix) is specified.
66 type: str
67 default: '_'
68 required: false
69 allow_duplicated_hosts:
70 description:
71 - By default, the first name that matches an entry of the O(hostnames) list is returned.
72 - Turn this flag on if you don't mind having duplicated entries in the inventory
73 and you want to get all the hostnames that match.
74 type: bool
75 default: false
76 version_added: 5.0.0
77 filters:
78 description:
79 - A dictionary of filter value pairs.
80 - Available filters are listed here U(http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options).
81 type: dict
82 default: {}
83 include_filters:
84 description:
85 - A list of filters. Any instances matching at least one of the filters are included in the result.
86 - Available filters are listed here U(http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options).
87 - Every entry in this list triggers a search query. As such, from a performance point of view, it's better to
88 keep the list as short as possible.
89 type: list
90 elements: dict
91 default: []
92 version_added: 1.5.0
93 exclude_filters:
94 description:
95 - A list of filters. Any instances matching one of the filters are excluded from the result.
96 - The filters from O(exclude_filters) take priority over the O(include_filters) and O(filters) keys.
97 - Available filters are listed here U(http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options).
98 - Every entry in this list triggers a search query. As such, from a performance point of view, it's better to
99 keep the list as short as possible.
100 type: list
101 elements: dict
102 default: []
103 version_added: 1.5.0
104 strict_permissions:
105 description:
106 - By default if a 403 (Forbidden) error code is encountered this plugin will fail.
107 - You can set this option to False in the inventory config file which will allow 403 errors to be gracefully skipped.
108 type: bool
109 default: true
110 use_contrib_script_compatible_sanitization:
111 description:
112 - By default this plugin is using a general group name sanitization to create safe and usable group names for use in Ansible.
113 This option allows you to override that, in efforts to allow migration from the old C(ec2.py) inventory script and
114 matches the sanitization of groups when the script's ``replace_dash_in_groups`` option is set to ``False``.
115 To replicate behavior of ``replace_dash_in_groups = True`` with constructed groups,
116 you will need to replace hyphens with underscores via the regex_replace filter for those entries.
117 - For this to work you should also turn off the TRANSFORM_INVALID_GROUP_CHARS setting,
118 otherwise the core engine will just use the standard sanitization on top.
119 - This is not the default as such names break certain functionality as not all characters are valid Python identifiers
120 which group names end up being used as.
121 - The use of this feature is deprecated and will be removed in a release after 2026-12-01.
122 Use Ansible's default group name sanitization instead.
123 type: bool
124 default: false
125 use_contrib_script_compatible_ec2_tag_keys:
126 description:
127 - Expose the host tags with C(ec2_tag_TAGNAME) keys like the old C(ec2.py) inventory script.
128 - The use of this feature is deprecated and will be removed in a release after 2026-12-01.
129 Use the C(ec2_tags) structure instead (e.g. use C(ec2_tags.TAGNAME) rather than C(ec2_tag_TAGNAME)).
130 type: bool
131 default: false
132 version_added: 1.5.0
133 hostvars_prefix:
134 description:
135 - The prefix for host variables names coming from AWS.
136 type: str
137 version_added: 3.1.0
138 hostvars_suffix:
139 description:
140 - The suffix for host variables names coming from AWS.
141 type: str
142 version_added: 3.1.0
143 use_ssm_inventory:
144 description:
145 - Enables fetching additional EC2 instance information from the AWS Systems Manager (SSM) inventory service into hostvars.
146 - By leveraging the SSM inventory data, the O(use_ssm_inventory) option provides additional details and attributes
147 about the EC2 instances in your inventory. These details can include operating system information, installed software,
148 network configurations, and custom inventory attributes defined in SSM.
149 type: bool
150 default: false
151 version_added: 6.0.0
152 route53_enabled:
153 description:
154 - Whether or not to use the Route53 DNS as host name.
155 - When set to V(true), Route53 hostnames will be included.
156 type: bool
157 default: false
158 version_added: 10.1.0
159 route53_hostnames:
160 description:
161 - Specifies the Route53 DNS name suffix to consider.
162 - Consider only Route53 zone with name ending with the value specified here.
163 type: list
164 elements: str
165 default: []
166 version_added: 10.1.0
167 route53_excluded_zones:
168 description:
169 - A list of Route53 zones to exclude.
170 type: list
171 elements: str
172 default: []
173 version_added: 10.1.0
174 """
175
176 EXAMPLES = r"""
177 # Minimal example using environment vars or instance role credentials
178 # Fetch all hosts in us-east-1, the hostname is the public DNS if it exists, otherwise the private IP address
179 plugin: amazon.aws.aws_ec2
180 regions:
181 - us-east-1
182
183 ---
184
185 # Example using filters, ignoring permission errors, and specifying the hostname precedence
186 plugin: amazon.aws.aws_ec2
187 # The values for profile, access key, secret key and token can be hardcoded like:
188 profile: aws_profile
189 # or you could use Jinja as:
190 # profile: "{{ lookup('env', 'AWS_PROFILE') | default('aws_profile', true) }}"
191 # Populate inventory with instances in these regions
192 regions:
193 - us-east-1
194 - us-east-2
195 filters:
196 ## All instances with their `Environment` tag set to `dev`
197 # tag:Environment: dev
198
199 # All dev and QA hosts
200 tag:Environment:
201 - dev
202 - qa
203 instance.group-id: sg-xxxxxxxx
204 # Ignores 403 errors rather than failing
205 strict_permissions: false
206 # Note: I(hostnames) sets the inventory_hostname. To modify ansible_host without modifying
207 # inventory_hostname use compose (see example below).
208 hostnames:
209 - tag:Name=Tag1,Name=Tag2 # Return specific hosts only
210 - tag:CustomDNSName
211 - dns-name
212 - name: 'tag:Name=Tag1,Name=Tag2'
213 - name: 'private-ip-address'
214 separator: '_'
215 prefix: 'tag:Name'
216 - name: 'test_literal' # Using literal values for hostname
217 separator: '-' # Hostname will be aws-test_literal
218 prefix: 'aws'
219
220 # Returns all the hostnames for a given instance
221 allow_duplicated_hosts: false
222
223 ---
224
225 # Example using constructed features to create groups and set ansible_host
226 plugin: amazon.aws.aws_ec2
227 regions:
228 - us-east-1
229 - us-west-1
230 # keyed_groups may be used to create custom groups
231 strict: false
232 keyed_groups:
233 # Add e.g. x86_64 hosts to an arch_x86_64 group
234 - prefix: arch
235 key: 'architecture'
236 # Add hosts to tag_Name_Value groups for each Name/Value tag pair
237 - prefix: tag
238 key: ec2_tags
239 # Add hosts to e.g. instance_type_z3_tiny
240 - prefix: instance_type
241 key: instance_type
242 # Create security_groups_sg_abcd1234 group for each SG
243 - key: 'security_groups|json_query("[].group_id")'
244 prefix: 'security_groups'
245 # Create a group for each value of the Application tag
246 - key: ec2_tags.Application
247 separator: ''
248 # Create a group per region e.g. aws_region_us_east_2
249 - key: placement.region
250 prefix: aws_region
251 # Create a group (or groups) based on the value of a custom tag "Role" and add them to a metagroup called "project"
252 - key: ec2_tags['Role']
253 prefix: foo
254 parent_group: "project"
255 # Set individual variables with compose
256 compose:
257 # Use the private IP address to connect to the host
258 # (note: this does not modify inventory_hostname, which is set via I(hostnames))
259 ansible_host: private_ip_address
260
261 ---
262
263 # Example using include_filters and exclude_filters to compose the inventory.
264 plugin: amazon.aws.aws_ec2
265 regions:
266 - us-east-1
267 - us-west-1
268 include_filters:
269 - tag:Name:
270 - 'my_second_tag'
271 - tag:Name:
272 - 'my_third_tag'
273 exclude_filters:
274 - tag:Name:
275 - 'my_first_tag'
276
277 ---
278
279 # Example using groups to assign the running hosts to a group based on vpc_id
280 plugin: amazon.aws.aws_ec2
281 profile: aws_profile
282 # Populate inventory with instances in these regions
283 regions:
284 - us-east-2
285 filters:
286 # All instances with their state as `running`
287 instance-state-name: running
288 keyed_groups:
289 - prefix: tag
290 key: ec2_tags
291 compose:
292 ansible_host: public_dns_name
293 groups:
294 libvpc: vpc_id == 'vpc-####'
295
296 ---
297
298 # Define prefix and suffix for host variables coming from AWS.
299 plugin: amazon.aws.aws_ec2
300 regions:
301 - us-east-1
302 hostvars_prefix: 'aws_'
303 hostvars_suffix: '_ec2'
304
305 ---
306
307 # Define hostnames variables with jinja2 filters.
308 plugin: amazon.aws.aws_ec2
309 regions:
310 - us-east-1
311 hostnames:
312 - "tag:Name | replace('test', 'prod')"
313
314 ---
315
316 # Define inventory with Route53 enabled and filtering specific route53 host names suffix.
317 plugin: amazon.aws.aws_ec2
318 regions:
319 - us-east-1
320 route53_enabled: true
321 route53_hostnames:
322 - .example.com
323 - .another_example.org
324
325 ---
326
327 # Define inventory with Route53 enabled and excluded zones.
328 plugin: amazon.aws.aws_ec2
329 regions:
330 - us-east-1
331 route53_enabled: true
332 route53_excluded_zones:
333 - ansible.bar.net
334 - ansible.foo.net
335 """
336
337 import re
338
339 try:
340 import botocore
341 except ImportError:
342 pass # will be captured by imported HAS_BOTO3
343
344 from collections import defaultdict
345 from typing import Any
346 from typing import Dict
347 from typing import List
348 from typing import Set
349
350 from ansible.module_utils.common.text.converters import to_text
351
352 try:
353 from ansible.template import trust_as_template
354 except ImportError:
355 trust_as_template = None
356 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
357
358 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
359 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
360 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
361 from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list
362 from ansible_collections.amazon.aws.plugins.plugin_utils.inventory import AWSInventoryBase
363
364 # The mappings give an array of keys to get from the filter name to the value
365 # returned by boto3's EC2 describe_instances method.
366
367 instance_meta_filter_to_boto_attr = {
368 "group-id": ("Groups", "GroupId"),
369 "group-name": ("Groups", "GroupName"),
370 "network-interface.attachment.instance-owner-id": ("OwnerId",),
371 "owner-id": ("OwnerId",),
372 "requester-id": ("RequesterId",),
373 "reservation-id": ("ReservationId",),
374 }
375
376 instance_data_filter_to_boto_attr = {
377 "affinity": ("Placement", "Affinity"),
378 "architecture": ("Architecture",),
379 "availability-zone": ("Placement", "AvailabilityZone"),
380 "block-device-mapping.attach-time": ("BlockDeviceMappings", "Ebs", "AttachTime"),
381 "block-device-mapping.delete-on-termination": ("BlockDeviceMappings", "Ebs", "DeleteOnTermination"),
382 "block-device-mapping.device-name": ("BlockDeviceMappings", "DeviceName"),
383 "block-device-mapping.status": ("BlockDeviceMappings", "Ebs", "Status"),
384 "block-device-mapping.volume-id": ("BlockDeviceMappings", "Ebs", "VolumeId"),
385 "client-token": ("ClientToken",),
386 "dns-name": ("PublicDnsName",),
387 "host-id": ("Placement", "HostId"),
388 "hypervisor": ("Hypervisor",),
389 "iam-instance-profile.arn": ("IamInstanceProfile", "Arn"),
390 "image-id": ("ImageId",),
391 "instance-id": ("InstanceId",),
392 "instance-lifecycle": ("InstanceLifecycle",),
393 "instance-state-code": ("State", "Code"),
394 "instance-state-name": ("State", "Name"),
395 "instance-type": ("InstanceType",),
396 "instance.group-id": ("SecurityGroups", "GroupId"),
397 "instance.group-name": ("SecurityGroups", "GroupName"),
398 "ip-address": ("PublicIpAddress",),
399 "kernel-id": ("KernelId",),
400 "key-name": ("KeyName",),
401 "launch-index": ("AmiLaunchIndex",),
402 "launch-time": ("LaunchTime",),
403 "monitoring-state": ("Monitoring", "State"),
404 "network-interface.addresses.private-ip-address": ("NetworkInterfaces", "PrivateIpAddress"),
405 "network-interface.addresses.primary": ("NetworkInterfaces", "PrivateIpAddresses", "Primary"),
406 "network-interface.addresses.association.public-ip": (
407 "NetworkInterfaces",
408 "PrivateIpAddresses",
409 "Association",
410 "PublicIp",
411 ),
412 "network-interface.addresses.association.ip-owner-id": (
413 "NetworkInterfaces",
414 "PrivateIpAddresses",
415 "Association",
416 "IpOwnerId",
417 ),
418 "network-interface.association.public-ip": ("NetworkInterfaces", "Association", "PublicIp"),
419 "network-interface.association.ip-owner-id": ("NetworkInterfaces", "Association", "IpOwnerId"),
420 "network-interface.association.allocation-id": ("ElasticGpuAssociations", "ElasticGpuId"),
421 "network-interface.association.association-id": ("ElasticGpuAssociations", "ElasticGpuAssociationId"),
422 "network-interface.attachment.attachment-id": ("NetworkInterfaces", "Attachment", "AttachmentId"),
423 "network-interface.attachment.instance-id": ("InstanceId",),
424 "network-interface.attachment.device-index": ("NetworkInterfaces", "Attachment", "DeviceIndex"),
425 "network-interface.attachment.status": ("NetworkInterfaces", "Attachment", "Status"),
426 "network-interface.attachment.attach-time": ("NetworkInterfaces", "Attachment", "AttachTime"),
427 "network-interface.attachment.delete-on-termination": ("NetworkInterfaces", "Attachment", "DeleteOnTermination"),
428 "network-interface.availability-zone": ("Placement", "AvailabilityZone"),
429 "network-interface.description": ("NetworkInterfaces", "Description"),
430 "network-interface.group-id": ("NetworkInterfaces", "Groups", "GroupId"),
431 "network-interface.group-name": ("NetworkInterfaces", "Groups", "GroupName"),
432 "network-interface.ipv6-addresses.ipv6-address": ("NetworkInterfaces", "Ipv6Addresses", "Ipv6Address"),
433 "network-interface.mac-address": ("NetworkInterfaces", "MacAddress"),
434 "network-interface.network-interface-id": ("NetworkInterfaces", "NetworkInterfaceId"),
435 "network-interface.owner-id": ("NetworkInterfaces", "OwnerId"),
436 "network-interface.private-dns-name": ("NetworkInterfaces", "PrivateDnsName"),
437 # 'network-interface.requester-id': (),
438 "network-interface.requester-managed": ("NetworkInterfaces", "Association", "IpOwnerId"),
439 "network-interface.status": ("NetworkInterfaces", "Status"),
440 "network-interface.source-dest-check": ("NetworkInterfaces", "SourceDestCheck"),
441 "network-interface.subnet-id": ("NetworkInterfaces", "SubnetId"),
442 "network-interface.vpc-id": ("NetworkInterfaces", "VpcId"),
443 "placement-group-name": ("Placement", "GroupName"),
444 "platform": ("Platform",),
445 "private-dns-name": ("PrivateDnsName",),
446 "private-ip-address": ("PrivateIpAddress",),
447 "product-code": ("ProductCodes", "ProductCodeId"),
448 "product-code.type": ("ProductCodes", "ProductCodeType"),
449 "ramdisk-id": ("RamdiskId",),
450 "reason": ("StateTransitionReason",),
451 "root-device-name": ("RootDeviceName",),
452 "root-device-type": ("RootDeviceType",),
453 "source-dest-check": ("SourceDestCheck",),
454 "spot-instance-request-id": ("SpotInstanceRequestId",),
455 "state-reason-code": ("StateReason", "Code"),
456 "state-reason-message": ("StateReason", "Message"),
457 "subnet-id": ("SubnetId",),
458 "tag": ("Tags",),
459 "tag-key": ("Tags",),
460 "tag-value": ("Tags",),
461 "tenancy": ("Placement", "Tenancy"),
462 "virtualization-type": ("VirtualizationType",),
463 "vpc-id": ("VpcId",),
464 }
465
466
467 def _get_tag_hostname(preference, instance):
468 tag_hostnames = preference.split("tag:", 1)[1]
469 expected_single_value = False
470 if "," in tag_hostnames:
471 tag_hostnames = tag_hostnames.split(",")
472 else:
473 expected_single_value = True
474 tag_hostnames = [tag_hostnames]
475
476 tags = boto3_tag_list_to_ansible_dict(instance.get("Tags", []))
477 tag_values = []
478 for v in tag_hostnames:
479 if "=" in v:
480 tag_name, tag_value = v.split("=")
481 if tags.get(tag_name) == tag_value:
482 tag_values.append(to_text(tag_name) + "_" + to_text(tag_value))
483 else:
484 tag_value = tags.get(v)
485 if tag_value:
486 tag_values.append(to_text(tag_value))
487 if expected_single_value and len(tag_values) > 0:
488 tag_values = tag_values[0]
489 return tag_values
490
491
492 def _prepare_host_vars(
493 original_host_vars,
494 hostvars_prefix=None,
495 hostvars_suffix=None,
496 use_contrib_script_compatible_ec2_tag_keys=False,
497 ):
498 host_vars = camel_dict_to_snake_dict(original_host_vars, ignore_list=["Tags"])
499 host_vars["ec2_tags"] = boto3_tag_list_to_ansible_dict(original_host_vars.get("Tags", []))
500 # ec2_tags is the new key, tags is deprecated but kept for backward compatibility
501 host_vars["tags"] = host_vars["ec2_tags"]
502
503 # Allow easier grouping by region
504 host_vars["placement"]["region"] = host_vars["placement"]["availability_zone"][:-1]
505
506 if use_contrib_script_compatible_ec2_tag_keys:
507 for k, v in host_vars["ec2_tags"].items():
508 host_vars[f"ec2_tag_{k}"] = v
509
510 if hostvars_prefix or hostvars_suffix:
511 for hostvar, hostval in host_vars.copy().items():
512 del host_vars[hostvar]
513 if hostvars_prefix:
514 hostvar = hostvars_prefix + hostvar
515 if hostvars_suffix:
516 hostvar = hostvar + hostvars_suffix
517 host_vars[hostvar] = hostval
518
519 return host_vars
520
521
522 def _compile_values(obj, attr):
523 """
524 :param obj: A list or dict of instance attributes
525 :param attr: A key
526 :return The value(s) found via the attr
527 """
528 if obj is None:
529 return
530
531 temp_obj = []
532
533 if isinstance(obj, list) or isinstance(obj, tuple):
534 for each in obj:
535 value = _compile_values(each, attr)
536 if value:
537 temp_obj.append(value)
538 else:
539 temp_obj = obj.get(attr)
540
541 has_indexes = any([isinstance(temp_obj, list), isinstance(temp_obj, tuple)])
542 if has_indexes and len(temp_obj) == 1:
543 return temp_obj[0]
544
545 return temp_obj
546
547
548 def _get_boto_attr_chain(filter_name, instance):
549 """
550 :param filter_name: The filter
551 :param instance: instance dict returned by boto3 ec2 describe_instances()
552 """
553 allowed_filters = sorted(
554 list(instance_data_filter_to_boto_attr.keys()) + list(instance_meta_filter_to_boto_attr.keys())
555 )
556
557 # If filter not in allow_filters -> use it as a literal string
558 if filter_name not in allowed_filters:
559 return filter_name
560
561 if filter_name in instance_data_filter_to_boto_attr:
562 boto_attr_list = instance_data_filter_to_boto_attr[filter_name]
563 else:
564 boto_attr_list = instance_meta_filter_to_boto_attr[filter_name]
565
566 instance_value = instance
567 for attribute in boto_attr_list:
568 instance_value = _compile_values(instance_value, attribute)
569 return instance_value
570
571
572 def _describe_ec2_instances(connection, filters):
573 paginator = connection.get_paginator("describe_instances")
574 return paginator.paginate(Filters=filters).build_full_result()
575
576
577 def _get_ssm_information(client, filters):
578 paginator = client.get_paginator("get_inventory")
579 return paginator.paginate(Filters=filters).build_full_result()
580
581
582 @AWSRetry.jittered_backoff()
583 def _list_hosted_zones(client: Any, **kwargs: Dict[str, Any]) -> List[Dict[str, Any]]:
584 """
585 List all hosted zones using the given boto3 Route53 client.
586
587 :param client: boto3 client for Route53
588 :param kwargs: Additional parameters for the paginator
589 :return: List of hosted zones
590 """
591 paginator = client.get_paginator("list_hosted_zones")
592 return paginator.paginate(**kwargs).build_full_result()["HostedZones"]
593
594
595 @AWSRetry.jittered_backoff()
596 def _list_resource_record_sets(client: Any, hosted_zone_id: str, **kwargs: Dict[str, Any]) -> List[Dict[str, Any]]:
597 """
598 Retrieve all resource record sets for a specific hosted zone in Route53.
599
600 :param client: A boto3 Route53 client.
601 :param hosted_zone_id: The ID of the hosted zone whose records should be listed.
602 :param kwargs: Optional keyword arguments to pass to the paginator.
603 :return: A list of dictionaries representing resource record sets.
604 """
605 paginator = client.get_paginator("list_resource_record_sets")
606 return paginator.paginate(HostedZoneId=hosted_zone_id, **kwargs).build_full_result()["ResourceRecordSets"]
607
608
609 def _remove_trailing_dot(data: str) -> str:
610 """Remove the trailing dot from a string"""
611 if data.endswith("."):
612 return data[:-1]
613 return data
614
615
616 class InventoryModule(AWSInventoryBase):
617 NAME = "amazon.aws.aws_ec2"
618 INVENTORY_FILE_SUFFIXES = ("aws_ec2.yml", "aws_ec2.yaml")
619
620 def __init__(self):
621 super().__init__()
622
623 self.group_prefix = "aws_ec2_"
624
625 def _get_instances_by_region(self, regions, filters, strict_permissions):
626 """
627 :param regions: a list of regions in which to describe instances
628 :param filters: a list of boto3 filter dictionaries
629 :param strict_permissions: a boolean determining whether to fail or ignore 403 error codes
630 :return A list of instance dictionaries
631 """
632 all_instances = []
633 # By default find non-terminated/terminating instances
634 if not any(f["Name"] == "instance-state-name" for f in filters):
635 filters.append({"Name": "instance-state-name", "Values": ["running", "pending", "stopping", "stopped"]})
636
637 for connection, _region in self.all_clients("ec2"):
638 try:
639 reservations = _describe_ec2_instances(connection, filters).get("Reservations")
640 instances = []
641 for r in reservations:
642 new_instances = r["Instances"]
643 reservation_details = {
644 "OwnerId": r["OwnerId"],
645 "RequesterId": r.get("RequesterId", ""),
646 "ReservationId": r["ReservationId"],
647 }
648 for instance in new_instances:
649 instance.update(reservation_details)
650 instances.extend(new_instances)
651 except is_boto3_error_code("UnauthorizedOperation") as e:
652 if not strict_permissions:
653 continue
654 self.fail_aws("Failed to describe instances", exception=e)
655 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
656 self.fail_aws("Failed to describe instances", exception=e)
657
658 all_instances.extend(instances)
659
660 return all_instances
661
662 def _sanitize_hostname(self, hostname):
663 if ":" in to_text(hostname):
664 return self._sanitize_group_name(to_text(hostname))
665 else:
666 return to_text(hostname)
667
668 def _get_hostname_with_jinja2_filter(self, instance, preference, return_single_hostname=False):
669 jinja2_filter = None
670 is_template = False
671 if "|" in preference:
672 preference, jinja2_filter = preference.split("|", maxsplit=1)
673 preference = preference.rstrip()
674 is_template = True
675 if preference.startswith("tag:"):
676 hostname = _get_tag_hostname(preference, instance)
677 else:
678 hostname = _get_boto_attr_chain(preference, instance)
679 if is_template:
680 template_var = "{{'%s'|%s}}" % (hostname, jinja2_filter)
681 if isinstance(hostname, list):
682 template_var = "{{%s|%s}}" % (hostname, jinja2_filter)
683 if trust_as_template:
684 template_var = trust_as_template(template_var)
685 hostname = self.templar.template(variable=template_var)
686 if isinstance(hostname, list) and return_single_hostname:
687 hostname = hostname[0] if hostname else None
688 return hostname
689
690 @property
691 def route53_enabled(self) -> bool:
692 return self.get_option("route53_enabled")
693
694 def _get_preferred_hostname(self, instance, hostnames):
695 """
696 :param instance: an instance dict returned by boto3 ec2 describe_instances()
697 :param hostnames: a list of hostname destination variables in order of preference
698 :return the preferred identifer for the host
699 """
700 if self.route53_enabled:
701 route53_hostnames = self._get_instance_route53_hostnames(instance)
702 if route53_hostnames:
703 # This method returns only one hostname
704 return self._sanitize_hostname(sorted(route53_hostnames)[0])
705
706 if not hostnames:
707 hostnames = ["dns-name", "private-dns-name"]
708
709 hostname = None
710 for preference in hostnames:
711 if isinstance(preference, dict):
712 if "name" not in preference:
713 self.fail_aws("A 'name' key must be defined in a hostnames dictionary.")
714 hostname = self._get_preferred_hostname(instance, [preference["name"]])
715 hostname_from_prefix = None
716 if "prefix" in preference:
717 hostname_from_prefix = self._get_preferred_hostname(instance, [preference["prefix"]])
718 separator = preference.get("separator", "_")
719 if hostname and hostname_from_prefix and "prefix" in preference:
720 hostname = hostname_from_prefix + separator + hostname
721 else:
722 hostname = self._get_hostname_with_jinja2_filter(instance, preference, return_single_hostname=True)
723 if hostname:
724 break
725 if hostname:
726 return self._sanitize_hostname(hostname)
727
728 def _get_all_hostnames(self, instance, hostnames):
729 """
730 :param instance: an instance dict returned by boto3 ec2 describe_instances()
731 :param hostnames: a list of hostname destination variables
732 :return all the candidats matching the expectation
733 """
734 hostname_list = []
735 if self.route53_enabled:
736 hostname_list = [self._sanitize_hostname(name) for name in self._get_instance_route53_hostnames(instance)]
737
738 if not hostnames:
739 hostnames = ["dns-name", "private-dns-name"]
740
741 hostname = None
742 for preference in hostnames:
743 if isinstance(preference, dict):
744 if "name" not in preference:
745 self.fail_aws("A 'name' key must be defined in a hostnames dictionary.")
746 hostname = self._get_all_hostnames(instance, [preference["name"]])
747 hostname_from_prefix = None
748 if "prefix" in preference:
749 hostname_from_prefix = self._get_all_hostnames(instance, [preference["prefix"]])
750 separator = preference.get("separator", "_")
751 if hostname and hostname_from_prefix and "prefix" in preference:
752 hostname = hostname_from_prefix[0] + separator + hostname[0]
753 else:
754 hostname = self._get_hostname_with_jinja2_filter(instance, preference)
755
756 if hostname:
757 if isinstance(hostname, list):
758 for host in hostname:
759 hostname_list.append(self._sanitize_hostname(host))
760 elif isinstance(hostname, str):
761 hostname_list.append(self._sanitize_hostname(hostname))
762
763 return hostname_list
764
765 def _query(self, regions, include_filters, exclude_filters, strict_permissions, use_ssm_inventory):
766 """
767 :param regions: a list of regions to query
768 :param include_filters: a list of boto3 filter dictionaries
769 :param exclude_filters: a list of boto3 filter dictionaries
770 :param strict_permissions: a boolean determining whether to fail or ignore 403 error codes
771
772 """
773 instances = []
774 ids_to_ignore = []
775 for filter_dict in exclude_filters:
776 for i in self._get_instances_by_region(
777 regions,
778 ansible_dict_to_boto3_filter_list(filter_dict),
779 strict_permissions,
780 ):
781 ids_to_ignore.append(i["InstanceId"])
782 for filter_dict in include_filters:
783 for i in self._get_instances_by_region(
784 regions,
785 ansible_dict_to_boto3_filter_list(filter_dict),
786 strict_permissions,
787 ):
788 if i["InstanceId"] not in ids_to_ignore:
789 instances.append(i)
790 ids_to_ignore.append(i["InstanceId"])
791
792 instances = sorted(instances, key=lambda x: x["InstanceId"])
793
794 if use_ssm_inventory and instances:
795 for connection, _region in self.all_clients("ssm"):
796 self._add_ssm_information(connection, instances)
797
798 return {"aws_ec2": instances}
799
800 def _add_ssm_information(self, connection, instances):
801 instance_ids = [x["InstanceId"] for x in instances]
802 result = self._get_multiple_ssm_inventories(connection, instance_ids)
803 for entity in result.get("Entities", []):
804 for x in instances:
805 if x["InstanceId"] == entity["Id"]:
806 content = entity.get("Data", {}).get("AWS:InstanceInformation", {}).get("Content", [])
807 if content:
808 x["SsmInventory"] = content[0]
809 break
810
811 def _map_route53_records(self) -> Dict[str, Set[str]]:
812 """Get and store the map of resource records to domain names that point to them."""
813 route53_excluded_zones = [_remove_trailing_dot(zone) for zone in self.get_option("route53_excluded_zones")]
814 route53_map = defaultdict(set)
815 for connection, _region in self.all_clients("route53"):
816 for zone in _list_hosted_zones(connection):
817 if _remove_trailing_dot(zone["Name"]) in route53_excluded_zones:
818 continue
819 for record in _list_resource_record_sets(client=connection, hosted_zone_id=zone["Id"]):
820 for resource in record.get("ResourceRecords", []):
821 route53_map[_remove_trailing_dot(resource["Value"])].add(_remove_trailing_dot(record["Name"]))
822 return route53_map
823
824 def _is_matching_route53_hostname(self, hostname: str) -> bool:
825 route53_hostnames = self.get_option("route53_hostnames")
826 result = True
827 if route53_hostnames:
828 result = any((hostname.endswith(name) for name in route53_hostnames))
829 return result
830
831 def _get_instance_route53_hostnames(self, instance: Dict[str, Any]) -> List[str]:
832 """Check if an instance is referenced in the records we have from
833 Route53. If it is, return the list of domain names pointing to that
834 instance. If nothing points to it, return an empty list."""
835
836 hostnames = set()
837 for attr in ("PublicDnsName", "PrivateDnsName", "PublicIpAddress", "PrivateIpAddress"):
838 if (attr_value := instance.get(attr)) and attr_value in self.route53_resource_record_mapping:
839 hostnames.update(self.route53_resource_record_mapping[attr_value])
840 return [name for name in hostnames if self._is_matching_route53_hostname(name)]
841
842 def _get_multiple_ssm_inventories(self, connection, instance_ids):
843 result = []
844 # SSM inventory filters Values list can contain a maximum of 40 items so we need to retrieve 40 at a time
845 # https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_InventoryFilter.html
846 while len(instance_ids) > 40:
847 filters = [{"Key": "AWS:InstanceInformation.InstanceId", "Values": instance_ids[:40]}]
848 result.extend(_get_ssm_information(connection, filters).get("Entities", []))
849 instance_ids = instance_ids[40:]
850 if instance_ids:
851 filters = [{"Key": "AWS:InstanceInformation.InstanceId", "Values": instance_ids}]
852 result.extend(_get_ssm_information(connection, filters).get("Entities", []))
853 return {"Entities": result}
854
855 def _populate(
856 self,
857 groups,
858 hostnames,
859 allow_duplicated_hosts=False,
860 hostvars_prefix=None,
861 hostvars_suffix=None,
862 use_contrib_script_compatible_ec2_tag_keys=False,
863 ):
864 for group in groups:
865 group = self.inventory.add_group(group)
866 self._add_hosts(
867 hosts=groups[group],
868 group=group,
869 hostnames=hostnames,
870 allow_duplicated_hosts=allow_duplicated_hosts,
871 hostvars_prefix=hostvars_prefix,
872 hostvars_suffix=hostvars_suffix,
873 use_contrib_script_compatible_ec2_tag_keys=use_contrib_script_compatible_ec2_tag_keys,
874 )
875 self.inventory.add_child("all", group)
876
877 def iter_entry(
878 self,
879 hosts,
880 hostnames,
881 allow_duplicated_hosts=False,
882 hostvars_prefix=None,
883 hostvars_suffix=None,
884 use_contrib_script_compatible_ec2_tag_keys=False,
885 ):
886 for host in hosts:
887 if allow_duplicated_hosts:
888 hostname_list = self._get_all_hostnames(host, hostnames)
889 else:
890 hostname_list = [self._get_preferred_hostname(host, hostnames)]
891 if not hostname_list or hostname_list[0] is None:
892 continue
893
894 host_vars = _prepare_host_vars(
895 host,
896 hostvars_prefix,
897 hostvars_suffix,
898 use_contrib_script_compatible_ec2_tag_keys,
899 )
900 for name in hostname_list:
901 yield to_text(name), host_vars
902
903 def _add_hosts(
904 self,
905 hosts,
906 group,
907 hostnames,
908 allow_duplicated_hosts=False,
909 hostvars_prefix=None,
910 hostvars_suffix=None,
911 use_contrib_script_compatible_ec2_tag_keys=False,
912 ):
913 """
914 :param hosts: a list of hosts to be added to a group
915 :param group: the name of the group to which the hosts belong
916 :param hostnames: a list of hostname destination variables in order of preference
917 :param bool allow_duplicated_hosts: if true, accept same host with different names
918 :param str hostvars_prefix: starts the hostvars variable name with this prefix
919 :param str hostvars_suffix: ends the hostvars variable name with this suffix
920 :param bool use_contrib_script_compatible_ec2_tag_keys: transform the host name with the legacy naming system
921 """
922
923 for name, host_vars in self.iter_entry(
924 hosts,
925 hostnames,
926 allow_duplicated_hosts=allow_duplicated_hosts,
927 hostvars_prefix=hostvars_prefix,
928 hostvars_suffix=hostvars_suffix,
929 use_contrib_script_compatible_ec2_tag_keys=use_contrib_script_compatible_ec2_tag_keys,
930 ):
931 self.inventory.add_host(name, group=group)
932 for k, v in host_vars.items():
933 self.inventory.set_variable(name, k, v)
934
935 # Use constructed if applicable
936
937 strict = self.get_option("strict")
938
939 # Composed variables
940 self._set_composite_vars(self.get_option("compose"), host_vars, name, strict=strict)
941
942 # Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group
943 self._add_host_to_composed_groups(self.get_option("groups"), host_vars, name, strict=strict)
944
945 # Create groups based on variable values and add the corresponding hosts to it
946 self._add_host_to_keyed_groups(self.get_option("keyed_groups"), host_vars, name, strict=strict)
947
948 def build_include_filters(self):
949 result = self.get_option("include_filters")
950 if self.get_option("filters"):
951 result = [self.get_option("filters")] + result
952 return result or [{}]
953
954 def parse(self, inventory, loader, path, cache=True):
955 super().parse(inventory, loader, path, cache=cache)
956
957 self.display.deprecated(
958 "The 'tags' host variable is deprecated. Use 'ec2_tags' instead.",
959 date="2026-12-01",
960 collection_name="amazon.aws",
961 )
962
963 # get user specifications
964 regions = self.get_option("regions")
965 include_filters = self.build_include_filters()
966 exclude_filters = self.get_option("exclude_filters")
967 hostnames = self.get_option("hostnames")
968 strict_permissions = self.get_option("strict_permissions")
969 allow_duplicated_hosts = self.get_option("allow_duplicated_hosts")
970
971 hostvars_prefix = self.get_option("hostvars_prefix")
972 hostvars_suffix = self.get_option("hostvars_suffix")
973 use_contrib_script_compatible_sanitization = self.get_option("use_contrib_script_compatible_sanitization")
974 use_contrib_script_compatible_ec2_tag_keys = self.get_option("use_contrib_script_compatible_ec2_tag_keys")
975 use_ssm_inventory = self.get_option("use_ssm_inventory")
976
977 if use_contrib_script_compatible_sanitization:
978 self.display.deprecated(
979 "The 'use_contrib_script_compatible_sanitization' option is deprecated. "
980 "Use Ansible's default group name sanitization instead.",
981 date="2026-12-01",
982 collection_name="amazon.aws",
983 )
984
985 self._sanitize_group_name = self._legacy_script_compatible_group_sanitization
986
987 if use_contrib_script_compatible_ec2_tag_keys:
988 self.display.deprecated(
989 "The 'use_contrib_script_compatible_ec2_tag_keys' option is deprecated. "
990 "Use the 'ec2_tags' structure instead.",
991 date="2026-12-01",
992 collection_name="amazon.aws",
993 )
994
995 if not all(isinstance(element, (dict, str)) for element in hostnames):
996 self.fail_aws("Hostnames should be a list of dict and str.")
997
998 result_was_cached, results = self.get_cached_result(path, cache)
999
1000 if not result_was_cached:
1001 results = self._query(regions, include_filters, exclude_filters, strict_permissions, use_ssm_inventory)
1002
1003 if self.route53_enabled:
1004 self.route53_resource_record_mapping = self._map_route53_records()
1005
1006 self._populate(
1007 results,
1008 hostnames,
1009 allow_duplicated_hosts=allow_duplicated_hosts,
1010 hostvars_prefix=hostvars_prefix,
1011 hostvars_suffix=hostvars_suffix,
1012 use_contrib_script_compatible_ec2_tag_keys=use_contrib_script_compatible_ec2_tag_keys,
1013 )
1014
1015 self.update_cached_result(path, cache, results)
1016
1017 @staticmethod
1018 def _legacy_script_compatible_group_sanitization(name):
1019 # note that while this mirrors what the script used to do, it has many issues with unicode and usability in python
1020 regex = re.compile(r"[^A-Za-z0-9\_\-]")
1021
1022 return regex.sub("_", name)