| 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_metadata_facts |
| 10 |
version_added: 1.0.0 |
| 11 |
short_description: Gathers facts (instance metadata) about remote hosts within EC2 |
| 12 |
author: |
| 13 |
- Silviu Dicu (@silviud) |
| 14 |
- Vinay Dandekar (@roadmapper) |
| 15 |
description: |
| 16 |
- This module fetches data from the instance metadata endpoint in EC2 as per |
| 17 |
U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html). |
| 18 |
- The module must be called from within the EC2 instance itself. |
| 19 |
- The module is configured to utilize the session oriented Instance Metadata Service v2 (IMDSv2) |
| 20 |
U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html). |
| 21 |
- If the HttpEndpoint parameter |
| 22 |
U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceMetadataOptions.html#API_ModifyInstanceMetadataOptions_RequestParameters) |
| 23 |
is set to disabled for the EC2 instance, the module will return an error while retrieving a session token. |
| 24 |
notes: |
| 25 |
- Parameters to filter on ec2_metadata_facts may be added later. |
| 26 |
options: |
| 27 |
metadata_token_ttl_seconds: |
| 28 |
description: |
| 29 |
- Specify a value for the C(X-aws-ec2-metadata-token-ttl-seconds) header. |
| 30 |
- Value must be between V(1) and V(21600). |
| 31 |
type: int |
| 32 |
default: 60 |
| 33 |
version_added: 8.2.0 |
| 34 |
""" |
| 35 |
|
| 36 |
EXAMPLES = r""" |
| 37 |
# Gather EC2 metadata facts |
| 38 |
- amazon.aws.ec2_metadata_facts: |
| 39 |
|
| 40 |
# Set a bigger value for X-aws-ec2-metadata-token-ttl-seconds header |
| 41 |
- amazon.aws.ec2_metadata_facts: |
| 42 |
metadata_token_ttl_seconds: 240 |
| 43 |
|
| 44 |
- debug: |
| 45 |
msg: "This instance is a t1.micro" |
| 46 |
when: ansible_ec2_instance_type == "t1.micro" |
| 47 |
""" |
| 48 |
|
| 49 |
RETURN = r""" |
| 50 |
ansible_facts: |
| 51 |
description: Dictionary of new facts representing discovered properties of the EC2 instance. |
| 52 |
returned: changed |
| 53 |
type: complex |
| 54 |
contains: |
| 55 |
ansible_ec2_ami_id: |
| 56 |
description: The AMI ID used to launch the instance. |
| 57 |
type: str |
| 58 |
sample: "ami-XXXXXXXX" |
| 59 |
ansible_ec2_ami_launch_index: |
| 60 |
description: |
| 61 |
- If you started more than one instance at the same time, this value indicates the order in which the instance was launched. |
| 62 |
- The value of the first instance launched is 0. |
| 63 |
type: str |
| 64 |
sample: "0" |
| 65 |
ansible_ec2_ami_manifest_path: |
| 66 |
description: |
| 67 |
- The path to the AMI manifest file in Amazon S3. |
| 68 |
- If you used an Amazon EBS-backed AMI to launch the instance, the returned result is unknown. |
| 69 |
type: str |
| 70 |
sample: "(unknown)" |
| 71 |
ansible_ec2_ancestor_ami_ids: |
| 72 |
description: |
| 73 |
- The AMI IDs of any instances that were rebundled to create this AMI. |
| 74 |
- This value will only exist if the AMI manifest file contained an ancestor-amis key. |
| 75 |
type: str |
| 76 |
sample: "(unknown)" |
| 77 |
ansible_ec2_block_device_mapping_ami: |
| 78 |
description: The virtual device that contains the root/boot file system. |
| 79 |
type: str |
| 80 |
sample: "/dev/sda1" |
| 81 |
ansible_ec2_block_device_mapping_ebsN: |
| 82 |
description: |
| 83 |
- The virtual devices associated with Amazon EBS volumes, if any are present. |
| 84 |
- Amazon EBS volumes are only available in metadata if they were present at launch time or when the instance was last started. |
| 85 |
- The N indicates the index of the Amazon EBS volume (such as ebs1 or ebs2). |
| 86 |
type: str |
| 87 |
sample: "/dev/xvdb" |
| 88 |
ansible_ec2_block_device_mapping_ephemeralN: |
| 89 |
description: The virtual devices associated with ephemeral devices, if any are present. The N indicates the index of the ephemeral volume. |
| 90 |
type: str |
| 91 |
sample: "/dev/xvdc" |
| 92 |
ansible_ec2_block_device_mapping_root: |
| 93 |
description: |
| 94 |
- The virtual devices or partitions associated with the root devices, or partitions on the virtual device, |
| 95 |
where the root (/ or C) file system is associated with the given instance. |
| 96 |
type: str |
| 97 |
sample: "/dev/sda1" |
| 98 |
ansible_ec2_block_device_mapping_swap: |
| 99 |
description: The virtual devices associated with swap. Not always present. |
| 100 |
type: str |
| 101 |
sample: "/dev/sda2" |
| 102 |
ansible_ec2_fws_instance_monitoring: |
| 103 |
description: "Value showing whether the customer has enabled detailed one-minute monitoring in CloudWatch." |
| 104 |
type: str |
| 105 |
sample: "enabled" |
| 106 |
ansible_ec2_hostname: |
| 107 |
description: |
| 108 |
- The private IPv4 DNS hostname of the instance. |
| 109 |
- In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0). |
| 110 |
type: str |
| 111 |
sample: "ip-10-0-0-1.ec2.internal" |
| 112 |
ansible_ec2_iam_info: |
| 113 |
description: |
| 114 |
- If there is an IAM role associated with the instance, contains information about the last time the instance profile was updated, |
| 115 |
including the instance's LastUpdated date, InstanceProfileArn, and InstanceProfileId. Otherwise, not present. |
| 116 |
type: complex |
| 117 |
sample: "" |
| 118 |
contains: |
| 119 |
LastUpdated: |
| 120 |
description: The last time which InstanceProfile is associated with the Instance changed. |
| 121 |
type: str |
| 122 |
InstanceProfileArn: |
| 123 |
description: The ARN of the InstanceProfile associated with the Instance. |
| 124 |
type: str |
| 125 |
InstanceProfileId: |
| 126 |
description: The Id of the InstanceProfile associated with the Instance. |
| 127 |
type: str |
| 128 |
ansible_ec2_iam_info_instanceprofilearn: |
| 129 |
description: The IAM instance profile ARN. |
| 130 |
type: str |
| 131 |
sample: "arn:aws:iam::123456789012:instance-profile/role_name" |
| 132 |
ansible_ec2_iam_info_instanceprofileid: |
| 133 |
description: IAM instance profile ID. |
| 134 |
type: str |
| 135 |
sample: "" |
| 136 |
ansible_ec2_iam_info_lastupdated: |
| 137 |
description: IAM info last updated time. |
| 138 |
type: str |
| 139 |
sample: "2017-05-12T02:42:27Z" |
| 140 |
ansible_ec2_iam_instance_profile_role: |
| 141 |
description: IAM instance role. |
| 142 |
type: str |
| 143 |
sample: "role_name" |
| 144 |
ansible_ec2_iam_security_credentials_role_name: |
| 145 |
description: |
| 146 |
- If there is an IAM role associated with the instance, role-name is the name of the role, |
| 147 |
and role-name contains the temporary security credentials associated with the role. Otherwise, not present. |
| 148 |
type: str |
| 149 |
sample: "" |
| 150 |
ansible_ec2_iam_security_credentials_role_name_accesskeyid: |
| 151 |
description: IAM role access key ID. |
| 152 |
type: str |
| 153 |
sample: "" |
| 154 |
ansible_ec2_iam_security_credentials_role_name_code: |
| 155 |
description: IAM code. |
| 156 |
type: str |
| 157 |
sample: "Success" |
| 158 |
ansible_ec2_iam_security_credentials_role_name_expiration: |
| 159 |
description: IAM role credentials expiration time. |
| 160 |
type: str |
| 161 |
sample: "2017-05-12T09:11:41Z" |
| 162 |
ansible_ec2_iam_security_credentials_role_name_lastupdated: |
| 163 |
description: IAM role last updated time. |
| 164 |
type: str |
| 165 |
sample: "2017-05-12T02:40:44Z" |
| 166 |
ansible_ec2_iam_security_credentials_role_name_secretaccesskey: |
| 167 |
description: IAM role secret access key. |
| 168 |
type: str |
| 169 |
sample: "" |
| 170 |
ansible_ec2_iam_security_credentials_role_name_token: |
| 171 |
description: IAM role token. |
| 172 |
type: str |
| 173 |
sample: "" |
| 174 |
ansible_ec2_iam_security_credentials_role_name_type: |
| 175 |
description: IAM role type. |
| 176 |
type: str |
| 177 |
sample: "AWS-HMAC" |
| 178 |
ansible_ec2_instance_action: |
| 179 |
description: Notifies the instance that it should reboot in preparation for bundling. |
| 180 |
type: str |
| 181 |
sample: "none" |
| 182 |
ansible_ec2_instance_id: |
| 183 |
description: The ID of this instance. |
| 184 |
type: str |
| 185 |
sample: "i-XXXXXXXXXXXXXXXXX" |
| 186 |
ansible_ec2_instance_identity_document: |
| 187 |
description: JSON containing instance attributes, such as instance-id, private IP address, etc. |
| 188 |
type: str |
| 189 |
sample: "" |
| 190 |
ansible_ec2_instance_identity_document_accountid: |
| 191 |
description: "" |
| 192 |
type: str |
| 193 |
sample: "123456789012" |
| 194 |
ansible_ec2_instance_identity_document_architecture: |
| 195 |
description: Instance system architecture. |
| 196 |
type: str |
| 197 |
sample: "x86_64" |
| 198 |
ansible_ec2_instance_identity_document_availabilityzone: |
| 199 |
description: The Availability Zone in which the instance launched. |
| 200 |
type: str |
| 201 |
sample: "us-east-1a" |
| 202 |
ansible_ec2_instance_identity_document_billingproducts: |
| 203 |
description: Billing products for this instance. |
| 204 |
type: str |
| 205 |
sample: "" |
| 206 |
ansible_ec2_instance_identity_document_devpayproductcodes: |
| 207 |
description: Product codes for the launched AMI. |
| 208 |
type: str |
| 209 |
sample: "" |
| 210 |
ansible_ec2_instance_identity_document_imageid: |
| 211 |
description: The AMI ID used to launch the instance. |
| 212 |
type: str |
| 213 |
sample: "ami-01234567" |
| 214 |
ansible_ec2_instance_identity_document_instanceid: |
| 215 |
description: The ID of this instance. |
| 216 |
type: str |
| 217 |
sample: "i-0123456789abcdef0" |
| 218 |
ansible_ec2_instance_identity_document_instancetype: |
| 219 |
description: The type of instance. |
| 220 |
type: str |
| 221 |
sample: "m4.large" |
| 222 |
ansible_ec2_instance_identity_document_kernelid: |
| 223 |
description: The ID of the kernel launched with this instance, if applicable. |
| 224 |
type: str |
| 225 |
sample: "" |
| 226 |
ansible_ec2_instance_identity_document_pendingtime: |
| 227 |
description: The instance pending time. |
| 228 |
type: str |
| 229 |
sample: "2017-05-11T20:51:20Z" |
| 230 |
ansible_ec2_instance_identity_document_privateip: |
| 231 |
description: |
| 232 |
- The private IPv4 address of the instance. |
| 233 |
- In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0). |
| 234 |
type: str |
| 235 |
sample: "10.0.0.1" |
| 236 |
ansible_ec2_instance_identity_document_ramdiskid: |
| 237 |
description: The ID of the RAM disk specified at launch time, if applicable. |
| 238 |
type: str |
| 239 |
sample: "" |
| 240 |
ansible_ec2_instance_identity_document_region: |
| 241 |
description: The Region in which the instance launched. |
| 242 |
type: str |
| 243 |
sample: "us-east-1" |
| 244 |
ansible_ec2_instance_identity_document_version: |
| 245 |
description: Identity document version. |
| 246 |
type: str |
| 247 |
sample: "2010-08-31" |
| 248 |
ansible_ec2_instance_identity_pkcs7: |
| 249 |
description: Used to verify the document's authenticity and content against the signature. |
| 250 |
type: str |
| 251 |
sample: "" |
| 252 |
ansible_ec2_instance_identity_rsa2048: |
| 253 |
description: Used to verify the document's authenticity and content against the signature. |
| 254 |
type: str |
| 255 |
sample: "" |
| 256 |
ansible_ec2_instance_identity_signature: |
| 257 |
description: Data that can be used by other parties to verify its origin and authenticity. |
| 258 |
type: str |
| 259 |
sample: "" |
| 260 |
ansible_ec2_instance_life_cycle: |
| 261 |
description: The purchasing option of the instance. |
| 262 |
type: str |
| 263 |
sample: "on-demand" |
| 264 |
ansible_ec2_instance_tags: |
| 265 |
description: |
| 266 |
- The dict of tags for the instance. |
| 267 |
- Returns empty dict if access to tags (InstanceMetadataTags) in instance metadata is not enabled. |
| 268 |
type: dict |
| 269 |
sample: {"tagKey1": "tag value 1", "tag_key2": "tag value 2"} |
| 270 |
version_added: 9.1.0 |
| 271 |
ansible_ec2_instance_tags_keys: |
| 272 |
description: |
| 273 |
- The list of tags keys of the instance. |
| 274 |
- Returns empty list if access to tags (InstanceMetadataTags) in instance metadata is not enabled. |
| 275 |
type: list |
| 276 |
elements: str |
| 277 |
sample: ["tagKey1", "tag_key2"] |
| 278 |
version_added: 5.5.0 |
| 279 |
ansible_ec2_instance_type: |
| 280 |
description: The type of the instance. |
| 281 |
type: str |
| 282 |
sample: "m4.large" |
| 283 |
ansible_ec2_local_hostname: |
| 284 |
description: |
| 285 |
- The private IPv4 DNS hostname of the instance. |
| 286 |
- In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0). |
| 287 |
type: str |
| 288 |
sample: "ip-10-0-0-1.ec2.internal" |
| 289 |
ansible_ec2_local_ipv4: |
| 290 |
description: |
| 291 |
- The private IPv4 address of the instance. |
| 292 |
- In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0). |
| 293 |
type: str |
| 294 |
sample: "10.0.0.1" |
| 295 |
ansible_ec2_mac: |
| 296 |
description: |
| 297 |
- The instance's media access control (MAC) address. |
| 298 |
- In cases where multiple network interfaces are present, this refers to the eth0 device (the device for which the device number is 0). |
| 299 |
type: str |
| 300 |
sample: "00:11:22:33:44:55" |
| 301 |
ansible_ec2_metrics_vhostmd: |
| 302 |
description: Metrics; no longer available. |
| 303 |
type: str |
| 304 |
sample: "" |
| 305 |
ansible_ec2_network_interfaces_macs_mac_address_device_number: |
| 306 |
description: |
| 307 |
- The unique device number associated with that interface. The device number corresponds to the device name; |
| 308 |
for example, a device-number of 2 is for the eth2 device. |
| 309 |
- This category corresponds to the DeviceIndex and device-index fields that are used by the Amazon EC2 API and the EC2 commands for the AWS CLI. |
| 310 |
type: str |
| 311 |
sample: "0" |
| 312 |
ansible_ec2_network_interfaces_macs_mac_address_interface_id: |
| 313 |
description: The elastic network interface ID. |
| 314 |
type: str |
| 315 |
sample: "eni-12345678" |
| 316 |
ansible_ec2_network_interfaces_macs_mac_address_ipv4_associations_ip_address: |
| 317 |
description: The private IPv4 addresses that are associated with each public-ip address and assigned to that interface. |
| 318 |
type: str |
| 319 |
sample: "" |
| 320 |
ansible_ec2_network_interfaces_macs_mac_address_ipv6s: |
| 321 |
description: The IPv6 addresses associated with the interface. Returned only for instances launched into a VPC. |
| 322 |
type: str |
| 323 |
sample: "" |
| 324 |
ansible_ec2_network_interfaces_macs_mac_address_local_hostname: |
| 325 |
description: The interface's local hostname. |
| 326 |
type: str |
| 327 |
sample: "" |
| 328 |
ansible_ec2_network_interfaces_macs_mac_address_local_ipv4s: |
| 329 |
description: The private IPv4 addresses associated with the interface. |
| 330 |
type: str |
| 331 |
sample: "" |
| 332 |
ansible_ec2_network_interfaces_macs_mac_address_mac: |
| 333 |
description: The instance's MAC address. |
| 334 |
type: str |
| 335 |
sample: "00:11:22:33:44:55" |
| 336 |
ansible_ec2_network_interfaces_macs_mac_address_owner_id: |
| 337 |
description: |
| 338 |
- The ID of the owner of the network interface. |
| 339 |
- In multiple-interface environments, an interface can be attached by a third party, such as Elastic Load Balancing. |
| 340 |
- Traffic on an interface is always billed to the interface owner. |
| 341 |
type: str |
| 342 |
sample: "123456789012" |
| 343 |
ansible_ec2_network_interfaces_macs_mac_address_public_hostname: |
| 344 |
description: |
| 345 |
- The interface's public DNS (IPv4). If the instance is in a VPC, |
| 346 |
this category is only returned if the enableDnsHostnames attribute is set to true. |
| 347 |
type: str |
| 348 |
sample: "ec2-1-2-3-4.compute-1.amazonaws.com" |
| 349 |
ansible_ec2_network_interfaces_macs_mac_address_public_ipv4s: |
| 350 |
description: The Elastic IP addresses associated with the interface. There may be multiple IPv4 addresses on an instance. |
| 351 |
type: str |
| 352 |
sample: "1.2.3.4" |
| 353 |
ansible_ec2_network_interfaces_macs_mac_address_security_group_ids: |
| 354 |
description: The IDs of the security groups to which the network interface belongs. Returned only for instances launched into a VPC. |
| 355 |
type: str |
| 356 |
sample: "sg-01234567,sg-01234568" |
| 357 |
ansible_ec2_network_interfaces_macs_mac_address_security_groups: |
| 358 |
description: Security groups to which the network interface belongs. Returned only for instances launched into a VPC. |
| 359 |
type: str |
| 360 |
sample: "secgroup1,secgroup2" |
| 361 |
ansible_ec2_network_interfaces_macs_mac_address_subnet_id: |
| 362 |
description: The ID of the subnet in which the interface resides. Returned only for instances launched into a VPC. |
| 363 |
type: str |
| 364 |
sample: "subnet-01234567" |
| 365 |
ansible_ec2_network_interfaces_macs_mac_address_subnet_ipv4_cidr_block: |
| 366 |
description: The IPv4 CIDR block of the subnet in which the interface resides. Returned only for instances launched into a VPC. |
| 367 |
type: str |
| 368 |
sample: "10.0.1.0/24" |
| 369 |
ansible_ec2_network_interfaces_macs_mac_address_subnet_ipv6_cidr_blocks: |
| 370 |
description: The IPv6 CIDR block of the subnet in which the interface resides. Returned only for instances launched into a VPC. |
| 371 |
type: str |
| 372 |
sample: "" |
| 373 |
ansible_ec2_network_interfaces_macs_mac_address_vpc_id: |
| 374 |
description: The ID of the VPC in which the interface resides. Returned only for instances launched into a VPC. |
| 375 |
type: str |
| 376 |
sample: "vpc-0123456" |
| 377 |
ansible_ec2_network_interfaces_macs_mac_address_vpc_ipv4_cidr_block: |
| 378 |
description: The IPv4 CIDR block of the VPC in which the interface resides. Returned only for instances launched into a VPC. |
| 379 |
type: str |
| 380 |
sample: "10.0.0.0/16" |
| 381 |
ansible_ec2_network_interfaces_macs_mac_address_vpc_ipv4_cidr_blocks: |
| 382 |
description: The IPv4 CIDR block of the VPC in which the interface resides. Returned only for instances launched into a VPC. |
| 383 |
type: str |
| 384 |
sample: "10.0.0.0/16" |
| 385 |
ansible_ec2_network_interfaces_macs_mac_address_vpc_ipv6_cidr_blocks: |
| 386 |
description: The IPv6 CIDR block of the VPC in which the interface resides. Returned only for instances launched into a VPC. |
| 387 |
type: str |
| 388 |
sample: "" |
| 389 |
ansible_ec2_placement_availability_zone: |
| 390 |
description: The Availability Zone in which the instance launched. |
| 391 |
type: str |
| 392 |
sample: "us-east-1a" |
| 393 |
ansible_ec2_placement_region: |
| 394 |
description: The Region in which the instance launched. |
| 395 |
type: str |
| 396 |
sample: "us-east-1" |
| 397 |
ansible_ec2_product_codes: |
| 398 |
description: Product codes associated with the instance, if any. |
| 399 |
type: str |
| 400 |
sample: "aw0evgkw8e5c1q413zgy5pjce" |
| 401 |
ansible_ec2_profile: |
| 402 |
description: EC2 instance hardware profile. |
| 403 |
type: str |
| 404 |
sample: "default-hvm" |
| 405 |
ansible_ec2_public_hostname: |
| 406 |
description: |
| 407 |
- The instance's public DNS. If the instance is in a VPC, this category is only returned if the enableDnsHostnames attribute is set to true. |
| 408 |
type: str |
| 409 |
sample: "ec2-1-2-3-4.compute-1.amazonaws.com" |
| 410 |
ansible_ec2_public_ipv4: |
| 411 |
description: The public IPv4 address. If an Elastic IP address is associated with the instance, the value returned is the Elastic IP address. |
| 412 |
type: str |
| 413 |
sample: "1.2.3.4" |
| 414 |
ansible_ec2_public_key: |
| 415 |
description: Public key. Only available if supplied at instance launch time. |
| 416 |
type: str |
| 417 |
sample: "" |
| 418 |
ansible_ec2_ramdisk_id: |
| 419 |
description: The ID of the RAM disk specified at launch time, if applicable. |
| 420 |
type: str |
| 421 |
sample: "" |
| 422 |
ansible_ec2_reservation_id: |
| 423 |
description: The ID of the reservation. |
| 424 |
type: str |
| 425 |
sample: "r-0123456789abcdef0" |
| 426 |
ansible_ec2_security_groups: |
| 427 |
description: |
| 428 |
- The names of the security groups applied to the instance. After launch, you can only change the security groups of instances running in a VPC. |
| 429 |
- Such changes are reflected here and in network/interfaces/macs/mac/security-groups. |
| 430 |
type: str |
| 431 |
sample: "securitygroup1,securitygroup2" |
| 432 |
ansible_ec2_services_domain: |
| 433 |
description: The domain for AWS resources for the region; for example, amazonaws.com for us-east-1. |
| 434 |
type: str |
| 435 |
sample: "amazonaws.com" |
| 436 |
ansible_ec2_services_partition: |
| 437 |
description: |
| 438 |
- The partition that the resource is in. For standard AWS regions, the partition is aws. |
| 439 |
- If you have resources in other partitions, the partition is aws-partitionname. |
| 440 |
- For example, the partition for resources in the China (Beijing) region is aws-cn. |
| 441 |
type: str |
| 442 |
sample: "aws" |
| 443 |
ansible_ec2_spot_termination_time: |
| 444 |
description: |
| 445 |
- The approximate time, in UTC, that the operating system for your Spot instance will receive the shutdown signal. |
| 446 |
- This item is present and contains a time value only if the Spot instance has been marked for termination by Amazon EC2. |
| 447 |
- The termination-time item is not set to a time if you terminated the Spot instance yourself. |
| 448 |
type: str |
| 449 |
sample: "2015-01-05T18:02:00Z" |
| 450 |
ansible_ec2_user_data: |
| 451 |
description: The instance user data. |
| 452 |
type: str |
| 453 |
sample: "#!/bin/bash" |
| 454 |
""" |
| 455 |
|
| 456 |
import json |
| 457 |
import re |
| 458 |
import socket |
| 459 |
import time |
| 460 |
import zlib |
| 461 |
|
| 462 |
from ansible.module_utils.basic import AnsibleModule |
| 463 |
from ansible.module_utils.common.text.converters import to_text |
| 464 |
from ansible.module_utils.six.moves.urllib.parse import quote |
| 465 |
from ansible.module_utils.urls import fetch_url |
| 466 |
|
| 467 |
socket.setdefaulttimeout(5) |
| 468 |
|
| 469 |
# The ec2_metadata_facts module is a special case, while we generally dropped support for Python < 3.6 |
| 470 |
# this module doesn't depend on the SDK and still has valid use cases for folks working with older |
| 471 |
# OSes. |
| 472 |
|
| 473 |
# pylint: disable=consider-using-f-string |
| 474 |
try: |
| 475 |
json_decode_error = json.JSONDecodeError |
| 476 |
except AttributeError: |
| 477 |
json_decode_error = ValueError |
| 478 |
|
| 479 |
|
| 480 |
class Ec2Metadata: |
| 481 |
ec2_metadata_token_uri = "http://169.254.169.254/latest/api/token" |
| 482 |
ec2_metadata_uri = "http://169.254.169.254/latest/meta-data/" |
| 483 |
ec2_metadata_instance_tags_uri = "http://169.254.169.254/latest/meta-data/tags/instance" |
| 484 |
ec2_sshdata_uri = "http://169.254.169.254/latest/meta-data/public-keys/0/openssh-key" |
| 485 |
ec2_userdata_uri = "http://169.254.169.254/latest/user-data/" |
| 486 |
ec2_dynamicdata_uri = "http://169.254.169.254/latest/dynamic/" |
| 487 |
|
| 488 |
def __init__( |
| 489 |
self, |
| 490 |
module, |
| 491 |
ec2_metadata_token_uri=None, |
| 492 |
ec2_metadata_uri=None, |
| 493 |
ec2_metadata_instance_tags_uri=None, |
| 494 |
ec2_sshdata_uri=None, |
| 495 |
ec2_userdata_uri=None, |
| 496 |
ec2_dynamicdata_uri=None, |
| 497 |
): |
| 498 |
self.module = module |
| 499 |
self.uri_token = ec2_metadata_token_uri or self.ec2_metadata_token_uri |
| 500 |
self.uri_meta = ec2_metadata_uri or self.ec2_metadata_uri |
| 501 |
self.uri_instance_tags = ec2_metadata_instance_tags_uri or self.ec2_metadata_instance_tags_uri |
| 502 |
self.uri_user = ec2_userdata_uri or self.ec2_userdata_uri |
| 503 |
self.uri_ssh = ec2_sshdata_uri or self.ec2_sshdata_uri |
| 504 |
self.uri_dynamic = ec2_dynamicdata_uri or self.ec2_dynamicdata_uri |
| 505 |
self._data = {} |
| 506 |
self._token = None |
| 507 |
self._prefix = "ansible_ec2_%s" |
| 508 |
|
| 509 |
def _decode(self, data): |
| 510 |
try: |
| 511 |
return data.decode("utf-8") |
| 512 |
except UnicodeDecodeError: |
| 513 |
# Decoding as UTF-8 failed, return data without raising an error |
| 514 |
self.module.warn("Decoding user-data as UTF-8 failed, return data as is ignoring any error") |
| 515 |
return data.decode("utf-8", errors="ignore") |
| 516 |
|
| 517 |
def decode_user_data(self, data): |
| 518 |
is_compressed = False |
| 519 |
|
| 520 |
# Check if data is compressed using zlib header |
| 521 |
if data.startswith(b"\x78\x9c") or data.startswith(b"\x1f\x8b"): |
| 522 |
is_compressed = True |
| 523 |
|
| 524 |
if is_compressed: |
| 525 |
# Data is compressed, attempt decompression and decode using UTF-8 |
| 526 |
try: |
| 527 |
decompressed = zlib.decompress(data, zlib.MAX_WBITS | 32) |
| 528 |
return self._decode(decompressed) |
| 529 |
except zlib.error: |
| 530 |
# Unable to decompress, return original data |
| 531 |
self.module.warn( |
| 532 |
"Unable to decompress user-data using zlib, attempt to decode original user-data as UTF-8" |
| 533 |
) |
| 534 |
return self._decode(data) |
| 535 |
else: |
| 536 |
# Data is not compressed, decode using UTF-8 |
| 537 |
return self._decode(data) |
| 538 |
|
| 539 |
def _fetch(self, url): |
| 540 |
encoded_url = quote(url, safe="%/:=&?~#+!$,;'@()*[]") |
| 541 |
headers = {} |
| 542 |
if self._token: |
| 543 |
headers = {"X-aws-ec2-metadata-token": self._token} |
| 544 |
|
| 545 |
response, info = fetch_url(self.module, encoded_url, headers=headers, force=True) |
| 546 |
|
| 547 |
if info.get("status") in (401, 403): |
| 548 |
self.module.fail_json(msg="Failed to retrieve metadata from AWS: {0}".format(info["msg"]), response=info) |
| 549 |
elif info.get("status") not in (200, 404): |
| 550 |
time.sleep(3) |
| 551 |
# request went bad, retry once then raise |
| 552 |
self.module.warn("Retrying query to metadata service. First attempt failed: {0}".format(info["msg"])) |
| 553 |
response, info = fetch_url(self.module, encoded_url, headers=headers, force=True) |
| 554 |
if info.get("status") not in (200, 404): |
| 555 |
# fail out now |
| 556 |
self.module.fail_json( |
| 557 |
msg="Failed to retrieve metadata from AWS: {0}".format(info["msg"]), response=info |
| 558 |
) |
| 559 |
if response and info["status"] < 400: |
| 560 |
data = response.read() |
| 561 |
if "user-data" in encoded_url: |
| 562 |
return to_text(self.decode_user_data(data)) |
| 563 |
else: |
| 564 |
data = None |
| 565 |
return to_text(data) |
| 566 |
|
| 567 |
def _mangle_fields(self, fields, uri, filter_patterns=None): |
| 568 |
filter_patterns = ["public-keys-0"] if filter_patterns is None else filter_patterns |
| 569 |
|
| 570 |
new_fields = {} |
| 571 |
for key, value in fields.items(): |
| 572 |
split_fields = key[len(uri):].split("/") # fmt: skip |
| 573 |
# Parse out the IAM role name (which is _not_ the same as the instance profile name) |
| 574 |
if ( |
| 575 |
len(split_fields) == 3 |
| 576 |
and split_fields[0:2] == ["iam", "security-credentials"] |
| 577 |
and ":" not in split_fields[2] |
| 578 |
): |
| 579 |
new_fields[self._prefix % "iam-instance-profile-role"] = split_fields[2] |
| 580 |
if len(split_fields) > 1 and split_fields[1]: |
| 581 |
new_key = "-".join(split_fields) |
| 582 |
new_fields[self._prefix % new_key] = value |
| 583 |
else: |
| 584 |
new_key = "".join(split_fields) |
| 585 |
new_fields[self._prefix % new_key] = value |
| 586 |
for pattern in filter_patterns: |
| 587 |
for key in dict(new_fields): |
| 588 |
match = re.search(pattern, key) |
| 589 |
if match: |
| 590 |
new_fields.pop(key) |
| 591 |
return new_fields |
| 592 |
|
| 593 |
def fetch(self, uri, recurse=True): |
| 594 |
raw_subfields = self._fetch(uri) |
| 595 |
if not raw_subfields: |
| 596 |
return |
| 597 |
subfields = raw_subfields.split("\n") |
| 598 |
for field in subfields: |
| 599 |
if field.endswith("/") and recurse: |
| 600 |
self.fetch(uri + field) |
| 601 |
if uri.endswith("/"): |
| 602 |
new_uri = uri + field |
| 603 |
else: |
| 604 |
new_uri = uri + "/" + field |
| 605 |
if new_uri not in self._data and not new_uri.endswith("/"): |
| 606 |
content = self._fetch(new_uri) |
| 607 |
if field == "security-groups" or field == "security-group-ids": |
| 608 |
sg_fields = ",".join(content.split("\n")) |
| 609 |
self._data["%s" % (new_uri)] = sg_fields |
| 610 |
else: |
| 611 |
try: |
| 612 |
json_dict = json.loads(content) |
| 613 |
self._data["%s" % (new_uri)] = content |
| 614 |
for key, value in json_dict.items(): |
| 615 |
self._data["%s:%s" % (new_uri, key.lower())] = value |
| 616 |
except (json_decode_error, AttributeError): |
| 617 |
self._data["%s" % (new_uri)] = content # not a stringified JSON string |
| 618 |
|
| 619 |
def fix_invalid_varnames(self, data): |
| 620 |
"""Change ':'' and '-' to '_' to ensure valid template variable names""" |
| 621 |
new_data = data.copy() |
| 622 |
for key, value in data.items(): |
| 623 |
if ":" in key or "-" in key: |
| 624 |
newkey = re.sub(":|-", "_", key) |
| 625 |
new_data[newkey] = value |
| 626 |
del new_data[key] |
| 627 |
|
| 628 |
return new_data |
| 629 |
|
| 630 |
def fetch_session_token(self, uri_token): |
| 631 |
"""Used to get a session token for IMDSv2""" |
| 632 |
metadata_token_ttl_seconds = self.module.params.get("metadata_token_ttl_seconds") |
| 633 |
headers = {"X-aws-ec2-metadata-token-ttl-seconds": metadata_token_ttl_seconds} |
| 634 |
response, info = fetch_url(self.module, uri_token, method="PUT", headers=headers, force=True) |
| 635 |
|
| 636 |
if info.get("status") == 403: |
| 637 |
self.module.fail_json( |
| 638 |
msg="Failed to retrieve metadata token from AWS: {0}".format(info["msg"]), response=info |
| 639 |
) |
| 640 |
elif info.get("status") not in (200, 404): |
| 641 |
time.sleep(3) |
| 642 |
# request went bad, retry once then raise |
| 643 |
self.module.warn("Retrying query to metadata service. First attempt failed: {0}".format(info["msg"])) |
| 644 |
response, info = fetch_url(self.module, uri_token, method="PUT", headers=headers, force=True) |
| 645 |
if info.get("status") not in (200, 404): |
| 646 |
# fail out now |
| 647 |
self.module.fail_json( |
| 648 |
msg="Failed to retrieve metadata token from AWS: {0}".format(info["msg"]), response=info |
| 649 |
) |
| 650 |
if response: |
| 651 |
token_data = response.read() |
| 652 |
else: |
| 653 |
token_data = None |
| 654 |
return to_text(token_data) |
| 655 |
|
| 656 |
def get_instance_tags(self, tag_keys, data): |
| 657 |
tags = {} |
| 658 |
for key in tag_keys: |
| 659 |
value = data.get("ansible_ec2_tags_instance_{}".format(key)) |
| 660 |
if value is not None: |
| 661 |
tags[key] = value |
| 662 |
return tags |
| 663 |
|
| 664 |
def run(self): |
| 665 |
self._token = self.fetch_session_token(self.uri_token) # create session token for IMDS |
| 666 |
self.fetch(self.uri_meta) # populate _data with metadata |
| 667 |
data = self._mangle_fields(self._data, self.uri_meta) |
| 668 |
data[self._prefix % "user-data"] = self._fetch(self.uri_user) |
| 669 |
data[self._prefix % "public-key"] = self._fetch(self.uri_ssh) |
| 670 |
|
| 671 |
self._data = {} # clear out metadata in _data |
| 672 |
self.fetch(self.uri_dynamic) # populate _data with dynamic data |
| 673 |
dyndata = self._mangle_fields(self._data, self.uri_dynamic) |
| 674 |
data.update(dyndata) |
| 675 |
data = self.fix_invalid_varnames(data) |
| 676 |
|
| 677 |
instance_tags_keys = self._fetch(self.uri_instance_tags) |
| 678 |
instance_tags_keys = instance_tags_keys.split("\n") if instance_tags_keys != "None" else [] |
| 679 |
data[self._prefix % "instance_tags_keys"] = instance_tags_keys |
| 680 |
|
| 681 |
instance_tags = self.get_instance_tags(instance_tags_keys, data) |
| 682 |
data[self._prefix % "instance_tags"] = instance_tags |
| 683 |
|
| 684 |
# Maintain old key for backwards compatibility |
| 685 |
if "ansible_ec2_instance_identity_document_region" in data: |
| 686 |
data["ansible_ec2_placement_region"] = data["ansible_ec2_instance_identity_document_region"] |
| 687 |
return data |
| 688 |
|
| 689 |
|
| 690 |
def main(): |
| 691 |
argument_spec = dict( |
| 692 |
metadata_token_ttl_seconds=dict(required=False, default=60, type="int", no_log=False), |
| 693 |
) |
| 694 |
|
| 695 |
module = AnsibleModule( |
| 696 |
argument_spec=argument_spec, |
| 697 |
supports_check_mode=True, |
| 698 |
) |
| 699 |
|
| 700 |
metadata_token_ttl_seconds = module.params.get("metadata_token_ttl_seconds") |
| 701 |
|
| 702 |
if metadata_token_ttl_seconds <= 0 or metadata_token_ttl_seconds > 21600: |
| 703 |
module.fail_json(msg="The option 'metadata_token_ttl_seconds' must be set to a value between 1 and 21600.") |
| 704 |
|
| 705 |
ec2_metadata_facts = Ec2Metadata(module).run() |
| 706 |
ec2_metadata_facts_result = dict(changed=False, ansible_facts=ec2_metadata_facts) |
| 707 |
|
| 708 |
module.exit_json(**ec2_metadata_facts_result) |
| 709 |
|
| 710 |
|
| 711 |
if __name__ == "__main__": |
| 712 |
main() |