| 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 |
| 10 |
version_added: 1.0.0 |
| 11 |
short_description: Create & manage EC2 instances |
| 12 |
description: |
| 13 |
- Create and manage AWS EC2 instances. |
| 14 |
- This module does not support creating |
| 15 |
L(EC2 Spot instances,https://aws.amazon.com/ec2/spot/). |
| 16 |
- The M(amazon.aws.ec2_spot_instance) module can create and manage spot instances. |
| 17 |
author: |
| 18 |
- Ryan Scott Brown (@ryansb) |
| 19 |
options: |
| 20 |
instance_ids: |
| 21 |
description: |
| 22 |
- If you specify one or more instance IDs, only instances that have the specified IDs are returned. |
| 23 |
- Mutually exclusive with O(exact_count). |
| 24 |
type: list |
| 25 |
elements: str |
| 26 |
default: [] |
| 27 |
state: |
| 28 |
description: |
| 29 |
- Goal state for the instances. |
| 30 |
- "O(state=present): ensures instances exist, but does not guarantee any state (e.g. running). Newly-launched instances will be run by EC2." |
| 31 |
- "O(state=running): O(state=present) + ensures the instances are running." |
| 32 |
- "O(state=started): O(state=running) + waits for EC2 status checks to report OK if O(wait=true)." |
| 33 |
- "O(state=stopped): ensures an existing instance is stopped." |
| 34 |
- "O(state=rebooted): convenience alias for O(state=stopped) immediately followed by O(state=running)." |
| 35 |
- "O(state=restarted): convenience alias for O(state=stopped) immediately followed by O(state=started)." |
| 36 |
- "O(state=terminated): ensures an existing instance is terminated." |
| 37 |
- "O(state=absent): alias for O(state=terminated)." |
| 38 |
choices: [present, terminated, running, started, stopped, restarted, rebooted, absent] |
| 39 |
default: present |
| 40 |
type: str |
| 41 |
wait: |
| 42 |
description: |
| 43 |
- Whether or not to wait for the desired O(state) (use O(wait_timeout) to customize this). |
| 44 |
default: true |
| 45 |
type: bool |
| 46 |
wait_timeout: |
| 47 |
description: |
| 48 |
- How long to wait (in seconds) for the instance to finish booting/terminating. |
| 49 |
default: 600 |
| 50 |
type: int |
| 51 |
instance_type: |
| 52 |
description: |
| 53 |
- Instance type to use for the instance, see |
| 54 |
U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html). |
| 55 |
- At least one of O(instance_type) or O(launch_template) must be specificed when launching an |
| 56 |
instance. |
| 57 |
- When the instance is present and the O(instance_type) specified value is different from the current value, |
| 58 |
the instance will be stopped and the instance type will be updated. |
| 59 |
type: str |
| 60 |
count: |
| 61 |
description: |
| 62 |
- Number of instances to launch. |
| 63 |
- Setting this value will result in always launching new instances. |
| 64 |
- Mutually exclusive with O(exact_count). |
| 65 |
type: int |
| 66 |
version_added: 2.2.0 |
| 67 |
exact_count: |
| 68 |
description: |
| 69 |
- An integer value which indicates how many instances that match the O(filters) parameter should be running. |
| 70 |
- Instances are either created or terminated based on this value. |
| 71 |
- If termination takes place, least recently created instances will be terminated based on Launch Time. |
| 72 |
- Mutually exclusive with O(count), O(instance_ids). |
| 73 |
type: int |
| 74 |
version_added: 2.2.0 |
| 75 |
user_data: |
| 76 |
description: |
| 77 |
- Opaque blob of data which is made available to the EC2 instance. |
| 78 |
type: str |
| 79 |
aap_callback: |
| 80 |
description: |
| 81 |
- Preconfigured user-data to enable an instance to perform an Ansible Automation Platform |
| 82 |
callback (Linux only). |
| 83 |
- For Windows instances, to enable remote access via Ansible set O(aap_callback.windows) to V(true), and |
| 84 |
optionally set an admin password. |
| 85 |
- If using O(aap_callback.windows) and O(aap_callback.set_password), callback to Ansible Automation Platform will not |
| 86 |
be performed but the instance will be ready to receive winrm connections from Ansible. |
| 87 |
- Mutually exclusive with O(user_data). |
| 88 |
type: dict |
| 89 |
aliases: ['tower_callback'] |
| 90 |
suboptions: |
| 91 |
windows: |
| 92 |
description: |
| 93 |
- Set O(aap_callback.windows=True) to use powershell instead of bash for the callback script. |
| 94 |
type: bool |
| 95 |
default: False |
| 96 |
set_password: |
| 97 |
description: |
| 98 |
- Optional admin password to use if O(aap_callback.windows=True). |
| 99 |
type: str |
| 100 |
tower_address: |
| 101 |
description: |
| 102 |
- IP address or DNS name of Tower server. Must be accessible via this address from the |
| 103 |
VPC that this instance will be launched in. |
| 104 |
- Required if O(aap_callback.windows=False). |
| 105 |
type: str |
| 106 |
job_template_id: |
| 107 |
description: |
| 108 |
- Either the integer ID of the Tower Job Template, or the name. |
| 109 |
Using a name for the job template is not supported by Ansible Tower prior to version |
| 110 |
3.2. |
| 111 |
- Required if O(aap_callback.windows=False). |
| 112 |
type: str |
| 113 |
host_config_key: |
| 114 |
description: |
| 115 |
- Host configuration secret key generated by the Tower job template. |
| 116 |
- Required if O(aap_callback.windows=False). |
| 117 |
type: str |
| 118 |
image: |
| 119 |
description: |
| 120 |
- An image to use for the instance. The M(amazon.aws.ec2_ami_info) module may be used to retrieve images. |
| 121 |
One of O(image) or O(image_id) are required when instance is not already present. |
| 122 |
type: dict |
| 123 |
suboptions: |
| 124 |
id: |
| 125 |
description: |
| 126 |
- The AMI ID. |
| 127 |
type: str |
| 128 |
ramdisk: |
| 129 |
description: |
| 130 |
- Overrides the AMI's default ramdisk ID. |
| 131 |
type: str |
| 132 |
kernel: |
| 133 |
description: |
| 134 |
- a string AKI to override the AMI kernel. |
| 135 |
type: str |
| 136 |
image_id: |
| 137 |
description: |
| 138 |
- I(ami) ID to use for the instance. One of O(image) or O(image_id) are required when instance is not already present. |
| 139 |
- This is an alias for O(image.id). |
| 140 |
type: str |
| 141 |
security_groups: |
| 142 |
description: |
| 143 |
- A list of security group IDs or names (strings). |
| 144 |
- Mutually exclusive with O(security_group). |
| 145 |
- Mutually exclusive with O(network_interfaces_ids). |
| 146 |
type: list |
| 147 |
elements: str |
| 148 |
default: [] |
| 149 |
security_group: |
| 150 |
description: |
| 151 |
- A security group ID or name. |
| 152 |
- Mutually exclusive with O(security_groups). |
| 153 |
- Mutually exclusive with O(network_interfaces_ids). |
| 154 |
type: str |
| 155 |
name: |
| 156 |
description: |
| 157 |
- The Name tag for the instance. |
| 158 |
type: str |
| 159 |
vpc_subnet_id: |
| 160 |
description: |
| 161 |
- The subnet ID in which to launch the instance (VPC). |
| 162 |
- If none is provided, M(amazon.aws.ec2_instance) will chose the default zone of the default VPC. |
| 163 |
- If used along with O(network), O(vpc_subnet_id) is used as a fallback to prevent errors when O(network.subnet_id) is not specified. |
| 164 |
aliases: ['subnet_id'] |
| 165 |
type: str |
| 166 |
network: |
| 167 |
description: |
| 168 |
- Either a dictionary containing the key C(interfaces) corresponding to a list of network interface IDs or |
| 169 |
containing specifications for a single network interface. |
| 170 |
- Use the M(amazon.aws.ec2_eni) module to create ENIs with special settings. |
| 171 |
- This field is deprecated and will be removed in a release after 2026-12-01, use O(network_interfaces) or O(network_interfaces_ids) instead. |
| 172 |
- Mutually exclusive with O(network_interfaces). |
| 173 |
- Mutually exclusive with O(network_interfaces_ids). |
| 174 |
- If used along with O(vpc_subnet_id), O(vpc_subnet_id) is used as a fallback to prevent errors when O(network.subnet_id) is not specified. |
| 175 |
type: dict |
| 176 |
suboptions: |
| 177 |
interfaces: |
| 178 |
description: |
| 179 |
- A list of ENI IDs (strings) or a list of objects containing the key id. |
| 180 |
type: list |
| 181 |
elements: str |
| 182 |
assign_public_ip: |
| 183 |
description: |
| 184 |
- When C(true) assigns a public IP address to the interface. |
| 185 |
type: bool |
| 186 |
private_ip_address: |
| 187 |
description: |
| 188 |
- An IPv4 address to assign to the interface. |
| 189 |
type: str |
| 190 |
ipv6_addresses: |
| 191 |
description: |
| 192 |
- A list of IPv6 addresses to assign to the network interface. |
| 193 |
type: list |
| 194 |
elements: str |
| 195 |
source_dest_check: |
| 196 |
description: |
| 197 |
- Controls whether source/destination checking is enabled on the interface. |
| 198 |
- This field with be ignored when O(source_dest_check) is provided. |
| 199 |
type: bool |
| 200 |
description: |
| 201 |
description: |
| 202 |
- A description for the network interface. |
| 203 |
type: str |
| 204 |
private_ip_addresses: |
| 205 |
description: |
| 206 |
- A list of IPv4 addresses to assign to the network interface. |
| 207 |
type: list |
| 208 |
elements: str |
| 209 |
subnet_id: |
| 210 |
description: |
| 211 |
- The subnet to connect the network interface to. |
| 212 |
type: str |
| 213 |
delete_on_termination: |
| 214 |
description: |
| 215 |
- Delete the interface when the instance it is attached to is |
| 216 |
terminated. |
| 217 |
type: bool |
| 218 |
device_index: |
| 219 |
description: |
| 220 |
- The index of the interface to modify. |
| 221 |
type: int |
| 222 |
groups: |
| 223 |
description: |
| 224 |
- A list of security group IDs to attach to the interface. |
| 225 |
type: list |
| 226 |
elements: str |
| 227 |
source_dest_check: |
| 228 |
description: |
| 229 |
- Controls whether source/destination checking is enabled on the interface. |
| 230 |
type: bool |
| 231 |
version_added: 8.2.0 |
| 232 |
network_interfaces: |
| 233 |
description: |
| 234 |
- A list of dictionaries containing specifications for network interfaces. |
| 235 |
- Use the M(amazon.aws.ec2_eni) module to create ENIs with special settings. |
| 236 |
- Mutually exclusive with O(network). |
| 237 |
type: list |
| 238 |
elements: dict |
| 239 |
version_added: 8.2.0 |
| 240 |
suboptions: |
| 241 |
assign_public_ip: |
| 242 |
description: |
| 243 |
- When V(true) assigns a public IP address to the interface. |
| 244 |
type: bool |
| 245 |
private_ip_address: |
| 246 |
description: |
| 247 |
- An IPv4 address to assign to the interface. |
| 248 |
type: str |
| 249 |
ipv6_addresses: |
| 250 |
description: |
| 251 |
- A list of IPv6 addresses to assign to the network interface. |
| 252 |
type: list |
| 253 |
elements: str |
| 254 |
description: |
| 255 |
description: |
| 256 |
- A description for the network interface. |
| 257 |
type: str |
| 258 |
subnet_id: |
| 259 |
description: |
| 260 |
- The subnet to connect the network interface to. |
| 261 |
type: str |
| 262 |
delete_on_termination: |
| 263 |
description: |
| 264 |
- Delete the interface when the instance it is attached to is terminated. |
| 265 |
type: bool |
| 266 |
default: True |
| 267 |
device_index: |
| 268 |
description: |
| 269 |
- The position of the network interface in the attachment order. |
| 270 |
- Use device index V(0) for a primary network interface. |
| 271 |
type: int |
| 272 |
default: 0 |
| 273 |
groups: |
| 274 |
description: |
| 275 |
- A list of security group IDs or names to attach to the interface. |
| 276 |
type: list |
| 277 |
elements: str |
| 278 |
private_ip_addresses: |
| 279 |
description: |
| 280 |
- A list of private IPv4 addresses to assign to the network interface. |
| 281 |
- Only one private IPv4 address can be designated as primary. |
| 282 |
- You cannot specify this option if you're launching more than one instance. |
| 283 |
type: list |
| 284 |
elements: dict |
| 285 |
suboptions: |
| 286 |
private_ip_address: |
| 287 |
description: |
| 288 |
- The private IPv4 address. |
| 289 |
type: str |
| 290 |
required: true |
| 291 |
primary: |
| 292 |
description: |
| 293 |
- Indicates whether the private IPv4 address is the primary private IPv4 address. |
| 294 |
- Only one IPv4 address can be designated as primary. |
| 295 |
type: bool |
| 296 |
network_interfaces_ids: |
| 297 |
description: |
| 298 |
- A list of ENI ids to attach to the instance. |
| 299 |
- Mutually exclusive with O(network). |
| 300 |
- Mutually exclusive with O(security_group). |
| 301 |
- Mutually exclusive with O(security_groups). |
| 302 |
type: list |
| 303 |
elements: dict |
| 304 |
version_added: 8.2.0 |
| 305 |
suboptions: |
| 306 |
id: |
| 307 |
description: |
| 308 |
- The ID of the network interface. |
| 309 |
type: str |
| 310 |
required: True |
| 311 |
device_index: |
| 312 |
description: |
| 313 |
- The position of the network interface in the attachment order. |
| 314 |
type: int |
| 315 |
default: 0 |
| 316 |
volumes: |
| 317 |
description: |
| 318 |
- A list of block device mappings, by default this will always use the AMI root device so the volumes option is primarily for adding more storage. |
| 319 |
- A mapping contains the (optional) keys V(device_name), V(virtual_name), V(ebs.volume_type), V(ebs.volume_size), V(ebs.kms_key_id), |
| 320 |
V(ebs.snapshot_id), V(ebs.iops), and V(ebs.delete_on_termination). |
| 321 |
- For more information about each parameter, see U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_BlockDeviceMapping.html). |
| 322 |
type: list |
| 323 |
elements: dict |
| 324 |
launch_template: |
| 325 |
description: |
| 326 |
- The EC2 launch template to base instance configuration on. |
| 327 |
- At least one of O(instance_type) or O(launch_template) must be specificed when launching an |
| 328 |
instance. |
| 329 |
type: dict |
| 330 |
suboptions: |
| 331 |
id: |
| 332 |
description: |
| 333 |
- The ID of the launch template (optional if name is specified). |
| 334 |
type: str |
| 335 |
name: |
| 336 |
description: |
| 337 |
- The pretty name of the launch template (optional if id is specified). |
| 338 |
type: str |
| 339 |
version: |
| 340 |
description: |
| 341 |
- The specific version of the launch template to use. If unspecified, the template default is chosen. |
| 342 |
key_name: |
| 343 |
description: |
| 344 |
- Name of the SSH access key to assign to the instance - must exist in the region the instance is created. |
| 345 |
- Use M(amazon.aws.ec2_key) to manage SSH keys. |
| 346 |
type: str |
| 347 |
availability_zone: |
| 348 |
description: |
| 349 |
- Specify an availability zone to use the default subnet it. Useful if not specifying the O(vpc_subnet_id) parameter. |
| 350 |
- If no subnet, ENI, or availability zone is provided, the default subnet in the default VPC will be used in the first AZ (alphabetically sorted). |
| 351 |
type: str |
| 352 |
instance_initiated_shutdown_behavior: |
| 353 |
description: |
| 354 |
- Whether to stop or terminate an instance upon shutdown. |
| 355 |
choices: ['stop', 'terminate'] |
| 356 |
type: str |
| 357 |
tenancy: |
| 358 |
description: |
| 359 |
- What type of tenancy to allow an instance to use. Default is V(shared) tenancy. Dedicated tenancy will incur additional charges. |
| 360 |
- This field is deprecated and will be removed in a release after 2025-12-01, use O(placement) instead. |
| 361 |
choices: ['dedicated', 'default'] |
| 362 |
type: str |
| 363 |
termination_protection: |
| 364 |
description: |
| 365 |
- Whether to enable termination protection. |
| 366 |
- This module will not terminate an instance with termination protection active, it must be turned off first. |
| 367 |
type: bool |
| 368 |
hibernation_options: |
| 369 |
description: |
| 370 |
- Indicates whether an instance is enabled for hibernation. |
| 371 |
Refer U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/hibernating-prerequisites.html) |
| 372 |
for Hibernation prerequisits. |
| 373 |
type: bool |
| 374 |
default: False |
| 375 |
version_added: 5.0.0 |
| 376 |
cpu_credit_specification: |
| 377 |
description: |
| 378 |
- For T series instances, choose whether to allow increased charges to buy CPU credits if the default pool is depleted. |
| 379 |
- Choose V(unlimited) to enable buying additional CPU credits. |
| 380 |
choices: ['unlimited', 'standard'] |
| 381 |
type: str |
| 382 |
cpu_options: |
| 383 |
description: |
| 384 |
- Reduce the number of vCPU exposed to the instance. |
| 385 |
- Those parameters can only be set at instance launch. The two suboptions O(cpu_options.threads_per_core) and O(cpu_options.core_count) are mandatory. |
| 386 |
- See U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) for combinations available. |
| 387 |
type: dict |
| 388 |
suboptions: |
| 389 |
threads_per_core: |
| 390 |
description: |
| 391 |
- Select the number of threads per core to enable. Disable or Enable Intel HT. |
| 392 |
choices: [1, 2] |
| 393 |
required: true |
| 394 |
type: int |
| 395 |
core_count: |
| 396 |
description: |
| 397 |
- Set the number of core to enable. |
| 398 |
required: true |
| 399 |
type: int |
| 400 |
detailed_monitoring: |
| 401 |
description: |
| 402 |
- Whether to allow detailed CloudWatch metrics to be collected, enabling more detailed alerting. |
| 403 |
type: bool |
| 404 |
ebs_optimized: |
| 405 |
description: |
| 406 |
- Whether instance is should use optimized EBS volumes, see U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html). |
| 407 |
type: bool |
| 408 |
filters: |
| 409 |
description: |
| 410 |
- A dict of filters to apply when deciding whether existing instances match and should be altered. Each dict item |
| 411 |
consists of a filter key and a filter value. See |
| 412 |
U(https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html). |
| 413 |
for possible filters. Filter names and values are case sensitive. |
| 414 |
- By default, instances are filtered for counting by their "Name" tag, base AMI, state (running, by default), and |
| 415 |
subnet ID. Any queryable filter can be used. Good candidates are specific tags, SSH keys, or security groups. |
| 416 |
type: dict |
| 417 |
iam_instance_profile: |
| 418 |
description: |
| 419 |
- The ARN or name of an EC2-enabled IAM instance profile to be used. |
| 420 |
- If a name is not provided in ARN format then the ListInstanceProfiles permission must also be granted. |
| 421 |
U(https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListInstanceProfiles.html) |
| 422 |
- If no full ARN is provided, the role with a matching name will be used from the active AWS account. |
| 423 |
type: str |
| 424 |
aliases: ['instance_role'] |
| 425 |
placement_group: |
| 426 |
description: |
| 427 |
- The placement group that needs to be assigned to the instance. |
| 428 |
- This field is deprecated and will be removed in a release after 2025-12-01, use O(placement) instead. |
| 429 |
type: str |
| 430 |
placement: |
| 431 |
description: |
| 432 |
- The location where the instance launched, if applicable. |
| 433 |
type: dict |
| 434 |
version_added: 7.0.0 |
| 435 |
suboptions: |
| 436 |
affinity: |
| 437 |
description: The affinity setting for the instance on the Dedicated Host. |
| 438 |
type: str |
| 439 |
required: false |
| 440 |
availability_zone: |
| 441 |
description: The Availability Zone of the instance. |
| 442 |
type: str |
| 443 |
required: false |
| 444 |
group_name: |
| 445 |
description: The name of the placement group the instance is in. |
| 446 |
type: str |
| 447 |
required: false |
| 448 |
host_id: |
| 449 |
description: The ID of the Dedicated Host on which the instance resides. |
| 450 |
type: str |
| 451 |
required: false |
| 452 |
host_resource_group_arn: |
| 453 |
description: The ARN of the host resource group in which to launch the instances. |
| 454 |
type: str |
| 455 |
required: false |
| 456 |
partition_number: |
| 457 |
description: The number of the partition the instance is in. |
| 458 |
type: int |
| 459 |
required: false |
| 460 |
tenancy: |
| 461 |
description: |
| 462 |
- Type of tenancy to allow an instance to use. Default is shared tenancy. Dedicated tenancy will incur additional charges. |
| 463 |
- Support for O(tenancy=host) was added in amazon.aws 7.6.0. |
| 464 |
type: str |
| 465 |
required: false |
| 466 |
choices: ['dedicated', 'default', 'host'] |
| 467 |
license_specifications: |
| 468 |
description: |
| 469 |
- The license specifications to be used for the instance. |
| 470 |
type: list |
| 471 |
elements: dict |
| 472 |
suboptions: |
| 473 |
license_configuration_arn: |
| 474 |
description: The Amazon Resource Name (ARN) of the license configuration. |
| 475 |
type: str |
| 476 |
required: true |
| 477 |
additional_info: |
| 478 |
description: |
| 479 |
- Reserved for Amazon's internal use. |
| 480 |
type: str |
| 481 |
version_added: 7.1.0 |
| 482 |
metadata_options: |
| 483 |
description: |
| 484 |
- Modify the metadata options for the instance. |
| 485 |
- See U(https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) for more information. |
| 486 |
- The two suboptions O(metadata_options.http_endpoint) and O(metadata_options.http_tokens) are supported. |
| 487 |
type: dict |
| 488 |
version_added: 2.0.0 |
| 489 |
suboptions: |
| 490 |
http_endpoint: |
| 491 |
description: |
| 492 |
- Enables or disables the HTTP metadata endpoint on instances. |
| 493 |
- If specified a value of disabled, metadata of the instance will not be accessible. |
| 494 |
choices: [enabled, disabled] |
| 495 |
default: enabled |
| 496 |
type: str |
| 497 |
http_tokens: |
| 498 |
description: |
| 499 |
- Set the state of token usage for instance metadata requests. |
| 500 |
- If the state is optional (v1 and v2), instance metadata can be retrieved with or without a signed token header on request. |
| 501 |
- If the state is required (v2), a signed token header must be sent with any instance metadata retrieval requests. |
| 502 |
choices: [optional, required] |
| 503 |
default: optional |
| 504 |
type: str |
| 505 |
http_put_response_hop_limit: |
| 506 |
version_added: 4.0.0 |
| 507 |
type: int |
| 508 |
description: |
| 509 |
- The desired HTTP PUT response hop limit for instance metadata requests. |
| 510 |
- The larger the number, the further instance metadata requests can travel. |
| 511 |
default: 1 |
| 512 |
http_protocol_ipv6: |
| 513 |
version_added: 4.0.0 |
| 514 |
type: str |
| 515 |
description: |
| 516 |
- Whether the instance metadata endpoint is available via IPv6 (V(enabled)) or not (V(disabled)). |
| 517 |
choices: [enabled, disabled] |
| 518 |
default: 'disabled' |
| 519 |
instance_metadata_tags: |
| 520 |
version_added: 4.0.0 |
| 521 |
type: str |
| 522 |
description: |
| 523 |
- Whether the instance tags are availble (V(enabled)) via metadata endpoint or not (V(disabled)). |
| 524 |
choices: [enabled, disabled] |
| 525 |
default: 'disabled' |
| 526 |
|
| 527 |
extends_documentation_fragment: |
| 528 |
- amazon.aws.common.modules |
| 529 |
- amazon.aws.region.modules |
| 530 |
- amazon.aws.tags |
| 531 |
- amazon.aws.boto3 |
| 532 |
""" |
| 533 |
|
| 534 |
EXAMPLES = r""" |
| 535 |
# Note: These examples do not set authentication details, see the AWS Guide for details. |
| 536 |
|
| 537 |
- name: Terminate every running instance in a region. Use with EXTREME caution. |
| 538 |
amazon.aws.ec2_instance: |
| 539 |
state: absent |
| 540 |
filters: |
| 541 |
instance-state-name: running |
| 542 |
|
| 543 |
- name: restart a particular instance by its ID |
| 544 |
amazon.aws.ec2_instance: |
| 545 |
state: restarted |
| 546 |
instance_ids: |
| 547 |
- i-12345678 |
| 548 |
|
| 549 |
- name: start an instance with a public IP address |
| 550 |
amazon.aws.ec2_instance: |
| 551 |
name: "public-compute-instance" |
| 552 |
key_name: "prod-ssh-key" |
| 553 |
vpc_subnet_id: subnet-5ca1ab1e |
| 554 |
instance_type: c5.large |
| 555 |
security_group: default |
| 556 |
network_interfaces: |
| 557 |
- assign_public_ip: true |
| 558 |
image_id: ami-123456 |
| 559 |
tags: |
| 560 |
Environment: Testing |
| 561 |
|
| 562 |
- name: start an instance and Add EBS |
| 563 |
amazon.aws.ec2_instance: |
| 564 |
name: "public-withebs-instance" |
| 565 |
vpc_subnet_id: subnet-5ca1ab1e |
| 566 |
instance_type: t2.micro |
| 567 |
key_name: "prod-ssh-key" |
| 568 |
security_group: default |
| 569 |
volumes: |
| 570 |
- device_name: /dev/sda1 |
| 571 |
ebs: |
| 572 |
volume_size: 16 |
| 573 |
delete_on_termination: true |
| 574 |
|
| 575 |
- name: start an instance and Add EBS volume from a snapshot |
| 576 |
amazon.aws.ec2_instance: |
| 577 |
name: "public-withebs-instance" |
| 578 |
instance_type: t2.micro |
| 579 |
image_id: ami-1234567890 |
| 580 |
vpc_subnet_id: subnet-5ca1ab1e |
| 581 |
volumes: |
| 582 |
- device_name: /dev/sda2 |
| 583 |
ebs: |
| 584 |
snapshot_id: snap-1234567890 |
| 585 |
|
| 586 |
- name: Create EC2 instance with termination protection turned on |
| 587 |
amazon.aws.ec2_instance: |
| 588 |
name: "my-ec2-instance" |
| 589 |
vpc_subnet_id: subnet-5ca1ab1e |
| 590 |
instance_type: t3.small |
| 591 |
image_id: ami-123456 |
| 592 |
termination_protection: true |
| 593 |
wait: true |
| 594 |
|
| 595 |
- name: start an instance with a cpu_options |
| 596 |
amazon.aws.ec2_instance: |
| 597 |
name: "public-cpuoption-instance" |
| 598 |
vpc_subnet_id: subnet-5ca1ab1e |
| 599 |
tags: |
| 600 |
Environment: Testing |
| 601 |
instance_type: c4.large |
| 602 |
volumes: |
| 603 |
- device_name: /dev/sda1 |
| 604 |
ebs: |
| 605 |
delete_on_termination: true |
| 606 |
cpu_options: |
| 607 |
core_count: 1 |
| 608 |
threads_per_core: 1 |
| 609 |
|
| 610 |
- name: start an instance and have it begin a Tower callback on boot |
| 611 |
amazon.aws.ec2_instance: |
| 612 |
name: "tower-callback-test" |
| 613 |
key_name: "prod-ssh-key" |
| 614 |
vpc_subnet_id: subnet-5ca1ab1e |
| 615 |
security_group: default |
| 616 |
tower_callback: |
| 617 |
# IP or hostname of tower server |
| 618 |
tower_address: 1.2.3.4 |
| 619 |
job_template_id: 876 |
| 620 |
host_config_key: '[secret config key goes here]' |
| 621 |
network_interfaces: |
| 622 |
- assign_public_ip: true |
| 623 |
image_id: ami-123456 |
| 624 |
cpu_credit_specification: unlimited |
| 625 |
tags: |
| 626 |
SomeThing: "A value" |
| 627 |
|
| 628 |
- name: start an instance with ENI (An existing ENI ID is required) |
| 629 |
amazon.aws.ec2_instance: |
| 630 |
name: "public-eni-instance" |
| 631 |
key_name: "prod-ssh-key" |
| 632 |
vpc_subnet_id: subnet-5ca1ab1e |
| 633 |
network_interfaces_ids: |
| 634 |
- id: "eni-12345" |
| 635 |
device_index: 0 |
| 636 |
tags: |
| 637 |
Env: "eni_on" |
| 638 |
volumes: |
| 639 |
- device_name: /dev/sda1 |
| 640 |
ebs: |
| 641 |
delete_on_termination: true |
| 642 |
instance_type: t2.micro |
| 643 |
image_id: ami-123456 |
| 644 |
|
| 645 |
- name: add second ENI interface |
| 646 |
amazon.aws.ec2_instance: |
| 647 |
name: "public-eni-instance" |
| 648 |
network_interfaces_ids: |
| 649 |
- id: "eni-12345" |
| 650 |
device_index: 0 |
| 651 |
- id: "eni-67890" |
| 652 |
device_index: 1 |
| 653 |
image_id: ami-123456 |
| 654 |
tags: |
| 655 |
Env: "eni_on" |
| 656 |
instance_type: t2.micro |
| 657 |
|
| 658 |
- name: start an instance with metadata options |
| 659 |
amazon.aws.ec2_instance: |
| 660 |
name: "public-metadataoptions-instance" |
| 661 |
vpc_subnet_id: subnet-5calable |
| 662 |
instance_type: t3.small |
| 663 |
image_id: ami-123456 |
| 664 |
tags: |
| 665 |
Environment: Testing |
| 666 |
metadata_options: |
| 667 |
http_endpoint: enabled |
| 668 |
http_tokens: optional |
| 669 |
|
| 670 |
# ensure number of instances running with a tag matches exact_count |
| 671 |
- name: start multiple instances |
| 672 |
amazon.aws.ec2_instance: |
| 673 |
instance_type: t3.small |
| 674 |
image_id: ami-123456 |
| 675 |
exact_count: 5 |
| 676 |
region: us-east-2 |
| 677 |
vpc_subnet_id: subnet-0123456 |
| 678 |
network_interfaces: |
| 679 |
- assign_public_ip: true |
| 680 |
groups: |
| 681 |
- default |
| 682 |
tags: |
| 683 |
foo: bar |
| 684 |
|
| 685 |
# launches multiple instances - specific number of instances |
| 686 |
- name: start specific number of multiple instances |
| 687 |
amazon.aws.ec2_instance: |
| 688 |
instance_type: t3.small |
| 689 |
image_id: ami-123456 |
| 690 |
count: 3 |
| 691 |
region: us-east-2 |
| 692 |
network_interfaces: |
| 693 |
- assign_public_ip: true |
| 694 |
groups: |
| 695 |
- default |
| 696 |
subnet_id: subnet-0123456 |
| 697 |
state: present |
| 698 |
tags: |
| 699 |
foo: bar |
| 700 |
|
| 701 |
# launches an instance with a primary and a secondary network interfaces |
| 702 |
- name: start an instance with a primary and secondary network interfaces |
| 703 |
amazon.aws.ec2_instance: |
| 704 |
instance_type: t2.large |
| 705 |
image_id: ami-123456 |
| 706 |
region: us-east-2 |
| 707 |
network_interfaces: |
| 708 |
- assign_public_ip: true |
| 709 |
groups: |
| 710 |
- default |
| 711 |
subnet_id: subnet-0123456 |
| 712 |
private_ip_addresses: |
| 713 |
- primary: true |
| 714 |
private_ip_address: 168.50.4.239 |
| 715 |
- primary: false |
| 716 |
private_ip_address: 168.50.4.237 |
| 717 |
state: present |
| 718 |
tags: |
| 719 |
foo: bar |
| 720 |
|
| 721 |
# launches a mac instance with HostResourceGroupArn and LicenseSpecifications |
| 722 |
- name: start a mac instance with a host resource group and license specifications |
| 723 |
amazon.aws.ec2_instance: |
| 724 |
name: "mac-compute-instance" |
| 725 |
key_name: "prod-ssh-key" |
| 726 |
vpc_subnet_id: subnet-5ca1ab1e |
| 727 |
instance_type: mac1.metal |
| 728 |
security_group: default |
| 729 |
placement: |
| 730 |
host_resource_group_arn: arn:aws:resource-groups:us-east-1:123456789012:group/MyResourceGroup |
| 731 |
license_specifications: |
| 732 |
- license_configuration_arn: arn:aws:license-manager:us-east-1:123456789012:license-configuration:lic-0123456789 |
| 733 |
image_id: ami-123456 |
| 734 |
tags: |
| 735 |
Environment: Testing |
| 736 |
""" |
| 737 |
|
| 738 |
RETURN = r""" |
| 739 |
instance_ids: |
| 740 |
description: A list of EC2 instance IDs matching the provided specification and filters. |
| 741 |
returned: always |
| 742 |
type: list |
| 743 |
sample: ["i-0123456789abcdef0", "i-0123456789abcdef1"] |
| 744 |
version_added: 5.3.0 |
| 745 |
changed_ids: |
| 746 |
description: A list of the set of EC2 instance IDs changed by the module action. |
| 747 |
returned: when instances that must be present are launched |
| 748 |
type: list |
| 749 |
sample: ["i-0123456789abcdef0"] |
| 750 |
version_added: 5.3.0 |
| 751 |
terminated_ids: |
| 752 |
description: A list of the set of EC2 instance IDs terminated by the module action. |
| 753 |
returned: when instances that must be absent are terminated |
| 754 |
type: list |
| 755 |
sample: ["i-0123456789abcdef1"] |
| 756 |
version_added: 5.3.0 |
| 757 |
instances: |
| 758 |
description: A list of EC2 instances. |
| 759 |
returned: when O(wait=true) or when matching instances already exist |
| 760 |
type: complex |
| 761 |
contains: |
| 762 |
ami_launch_index: |
| 763 |
description: The AMI launch index, which can be used to find this instance in the launch group. |
| 764 |
returned: always |
| 765 |
type: int |
| 766 |
sample: 0 |
| 767 |
architecture: |
| 768 |
description: The architecture of the image. |
| 769 |
returned: always |
| 770 |
type: str |
| 771 |
sample: x86_64 |
| 772 |
block_device_mappings: |
| 773 |
description: Any block device mapping entries for the instance. |
| 774 |
returned: always |
| 775 |
type: complex |
| 776 |
contains: |
| 777 |
device_name: |
| 778 |
description: The device name exposed to the instance (for example, /dev/sdh or xvdh). |
| 779 |
returned: always |
| 780 |
type: str |
| 781 |
sample: /dev/sdh |
| 782 |
ebs: |
| 783 |
description: Parameters used to automatically set up EBS volumes when the instance is launched. |
| 784 |
returned: always |
| 785 |
type: complex |
| 786 |
contains: |
| 787 |
attach_time: |
| 788 |
description: The time stamp when the attachment initiated. |
| 789 |
returned: always |
| 790 |
type: str |
| 791 |
sample: "2017-03-23T22:51:24+00:00" |
| 792 |
delete_on_termination: |
| 793 |
description: Indicates whether the volume is deleted on instance termination. |
| 794 |
returned: always |
| 795 |
type: bool |
| 796 |
sample: true |
| 797 |
status: |
| 798 |
description: The attachment state. |
| 799 |
returned: always |
| 800 |
type: str |
| 801 |
sample: attached |
| 802 |
volume_id: |
| 803 |
description: The ID of the EBS volume. |
| 804 |
returned: always |
| 805 |
type: str |
| 806 |
sample: vol-12345678 |
| 807 |
capacity_reservation_specification: |
| 808 |
description: Information about the Capacity Reservation targeting option. |
| 809 |
type: complex |
| 810 |
contains: |
| 811 |
capacity_reservation_preference: |
| 812 |
description: Describes the Capacity Reservation preferences. |
| 813 |
type: str |
| 814 |
sample: open |
| 815 |
client_token: |
| 816 |
description: The idempotency token you provided when you launched the instance, if applicable. |
| 817 |
returned: always |
| 818 |
type: str |
| 819 |
sample: mytoken |
| 820 |
cpu_options: |
| 821 |
description: The CPU options for the instance. |
| 822 |
type: complex |
| 823 |
contains: |
| 824 |
core_count: |
| 825 |
description: The number of CPU cores for the instance. |
| 826 |
type: int |
| 827 |
sample: 1 |
| 828 |
threads_per_core: |
| 829 |
description: The number of threads per CPU core. |
| 830 |
type: int |
| 831 |
sample: 2 |
| 832 |
amd_sev_snp: |
| 833 |
description: Indicates whether the instance is enabled for AMD SEV-SNP. |
| 834 |
type: str |
| 835 |
sample: enabled |
| 836 |
current_instance_boot_mode: |
| 837 |
description: The boot mode that is used to boot the instance at launch or start. |
| 838 |
type: str |
| 839 |
sample: legacy-bios |
| 840 |
ebs_optimized: |
| 841 |
description: Indicates whether the instance is optimized for EBS I/O. |
| 842 |
returned: always |
| 843 |
type: bool |
| 844 |
sample: false |
| 845 |
ena_support: |
| 846 |
description: Specifies whether enhanced networking with ENA is enabled. |
| 847 |
returned: always |
| 848 |
type: bool |
| 849 |
sample: true |
| 850 |
enclave_options: |
| 851 |
description: Indicates whether the instance is enabled for Amazon Web Services Nitro Enclaves. |
| 852 |
type: dict |
| 853 |
contains: |
| 854 |
enabled: |
| 855 |
description: If this parameter is set to true, the instance is enabled for Amazon Web Services Nitro Enclaves. |
| 856 |
returned: always |
| 857 |
type: bool |
| 858 |
sample: false |
| 859 |
hibernation_options: |
| 860 |
description: Indicates whether the instance is enabled for hibernation. |
| 861 |
type: dict |
| 862 |
contains: |
| 863 |
configured: |
| 864 |
description: If true, your instance is enabled for hibernation; otherwise, it is not enabled for hibernation. |
| 865 |
returned: always |
| 866 |
type: bool |
| 867 |
sample: false |
| 868 |
hypervisor: |
| 869 |
description: The hypervisor type of the instance. |
| 870 |
returned: always |
| 871 |
type: str |
| 872 |
sample: xen |
| 873 |
iam_instance_profile: |
| 874 |
description: The IAM instance profile associated with the instance, if applicable. |
| 875 |
returned: always |
| 876 |
type: complex |
| 877 |
contains: |
| 878 |
arn: |
| 879 |
description: The Amazon Resource Name (ARN) of the instance profile. |
| 880 |
returned: always |
| 881 |
type: str |
| 882 |
sample: "arn:aws:iam::123456789012:instance-profile/myprofile" |
| 883 |
id: |
| 884 |
description: The ID of the instance profile. |
| 885 |
returned: always |
| 886 |
type: str |
| 887 |
sample: JFJ397FDG400FG9FD1N |
| 888 |
image_id: |
| 889 |
description: The ID of the AMI used to launch the instance. |
| 890 |
returned: always |
| 891 |
type: str |
| 892 |
sample: ami-0011223344 |
| 893 |
instance_id: |
| 894 |
description: The ID of the instance. |
| 895 |
returned: always |
| 896 |
type: str |
| 897 |
sample: i-012345678 |
| 898 |
instance_type: |
| 899 |
description: The instance type size of the running instance. |
| 900 |
returned: always |
| 901 |
type: str |
| 902 |
sample: t2.micro |
| 903 |
key_name: |
| 904 |
description: The name of the key pair, if this instance was launched with an associated key pair. |
| 905 |
returned: always |
| 906 |
type: str |
| 907 |
sample: my-key |
| 908 |
launch_time: |
| 909 |
description: The time the instance was launched. |
| 910 |
returned: always |
| 911 |
type: str |
| 912 |
sample: "2017-03-23T22:51:24+00:00" |
| 913 |
licenses: |
| 914 |
description: The license configurations for the instance. |
| 915 |
returned: When license specifications are provided. |
| 916 |
type: list |
| 917 |
elements: dict |
| 918 |
contains: |
| 919 |
license_configuration_arn: |
| 920 |
description: The Amazon Resource Name (ARN) of the license configuration. |
| 921 |
returned: always |
| 922 |
type: str |
| 923 |
sample: arn:aws:license-manager:us-east-1:123456789012:license-configuration:lic-0123456789 |
| 924 |
metadata_options: |
| 925 |
description: The metadata options for the instance. |
| 926 |
returned: always |
| 927 |
type: complex |
| 928 |
contains: |
| 929 |
http_endpoint: |
| 930 |
description: Indicates whether the HTTP metadata endpoint on your instances is enabled or disabled. |
| 931 |
type: str |
| 932 |
sample: enabled |
| 933 |
http_protocol_ipv6: |
| 934 |
description: Indicates whether the IPv6 endpoint for the instance metadata service is enabled or disabled. |
| 935 |
type: str |
| 936 |
sample: disabled |
| 937 |
http_put_response_hop_limit: |
| 938 |
description: The maximum number of hops that the metadata token can travel. |
| 939 |
type: int |
| 940 |
sample: 1 |
| 941 |
http_tokens: |
| 942 |
description: Indicates whether IMDSv2 is required. |
| 943 |
type: str |
| 944 |
sample: optional |
| 945 |
instance_metadata_tags: |
| 946 |
description: Indicates whether access to instance tags from the instance metadata is enabled or disabled. |
| 947 |
type: str |
| 948 |
sample: disabled |
| 949 |
state: |
| 950 |
description: The state of the metadata option changes. |
| 951 |
type: str |
| 952 |
sample: applied |
| 953 |
monitoring: |
| 954 |
description: The monitoring for the instance. |
| 955 |
returned: always |
| 956 |
type: complex |
| 957 |
contains: |
| 958 |
state: |
| 959 |
description: Indicates whether detailed monitoring is enabled. Otherwise, basic monitoring is enabled. |
| 960 |
returned: always |
| 961 |
type: str |
| 962 |
sample: disabled |
| 963 |
network_interfaces: |
| 964 |
description: One or more network interfaces for the instance. |
| 965 |
returned: always |
| 966 |
type: list |
| 967 |
elements: dict |
| 968 |
contains: |
| 969 |
association: |
| 970 |
description: The association information for an Elastic IPv4 associated with the network interface. |
| 971 |
returned: always |
| 972 |
type: complex |
| 973 |
contains: |
| 974 |
ip_owner_id: |
| 975 |
description: The ID of the owner of the Elastic IP address. |
| 976 |
returned: always |
| 977 |
type: str |
| 978 |
sample: amazon |
| 979 |
public_dns_name: |
| 980 |
description: The public DNS name. |
| 981 |
returned: always |
| 982 |
type: str |
| 983 |
sample: "" |
| 984 |
public_ip: |
| 985 |
description: The public IP address or Elastic IP address bound to the network interface. |
| 986 |
returned: always |
| 987 |
type: str |
| 988 |
sample: 1.2.3.4 |
| 989 |
attachment: |
| 990 |
description: The network interface attachment. |
| 991 |
returned: always |
| 992 |
type: complex |
| 993 |
contains: |
| 994 |
attach_time: |
| 995 |
description: The time stamp when the attachment initiated. |
| 996 |
returned: always |
| 997 |
type: str |
| 998 |
sample: "2017-03-23T22:51:24+00:00" |
| 999 |
attachment_id: |
| 1000 |
description: The ID of the network interface attachment. |
| 1001 |
returned: always |
| 1002 |
type: str |
| 1003 |
sample: eni-attach-3aff3f |
| 1004 |
delete_on_termination: |
| 1005 |
description: Indicates whether the network interface is deleted when the instance is terminated. |
| 1006 |
returned: always |
| 1007 |
type: bool |
| 1008 |
sample: true |
| 1009 |
device_index: |
| 1010 |
description: The index of the device on the instance for the network interface attachment. |
| 1011 |
returned: always |
| 1012 |
type: int |
| 1013 |
sample: 0 |
| 1014 |
network_card_index: |
| 1015 |
description: The index of the network card. |
| 1016 |
returned: always |
| 1017 |
type: int |
| 1018 |
sample: 0 |
| 1019 |
status: |
| 1020 |
description: The attachment state. |
| 1021 |
returned: always |
| 1022 |
type: str |
| 1023 |
sample: attached |
| 1024 |
description: |
| 1025 |
description: The description. |
| 1026 |
returned: always |
| 1027 |
type: str |
| 1028 |
sample: My interface |
| 1029 |
groups: |
| 1030 |
description: One or more security groups. |
| 1031 |
returned: always |
| 1032 |
type: list |
| 1033 |
elements: dict |
| 1034 |
contains: |
| 1035 |
group_id: |
| 1036 |
description: The ID of the security group. |
| 1037 |
returned: always |
| 1038 |
type: str |
| 1039 |
sample: sg-abcdef12 |
| 1040 |
group_name: |
| 1041 |
description: The name of the security group. |
| 1042 |
returned: always |
| 1043 |
type: str |
| 1044 |
sample: mygroup |
| 1045 |
interface_type: |
| 1046 |
description: The type of network interface. |
| 1047 |
returned: always |
| 1048 |
type: str |
| 1049 |
sample: interface |
| 1050 |
ipv6_addresses: |
| 1051 |
description: One or more IPv6 addresses associated with the network interface. |
| 1052 |
returned: always |
| 1053 |
type: list |
| 1054 |
elements: dict |
| 1055 |
contains: |
| 1056 |
ipv6_address: |
| 1057 |
description: The IPv6 address. |
| 1058 |
returned: always |
| 1059 |
type: str |
| 1060 |
sample: "2001:0db8:85a3:0000:0000:8a2e:0370:7334" |
| 1061 |
mac_address: |
| 1062 |
description: The MAC address. |
| 1063 |
returned: always |
| 1064 |
type: str |
| 1065 |
sample: "00:11:22:33:44:55" |
| 1066 |
network_interface_id: |
| 1067 |
description: The ID of the network interface. |
| 1068 |
returned: always |
| 1069 |
type: str |
| 1070 |
sample: eni-01234567 |
| 1071 |
owner_id: |
| 1072 |
description: The AWS account ID of the owner of the network interface. |
| 1073 |
returned: always |
| 1074 |
type: str |
| 1075 |
sample: 01234567890 |
| 1076 |
private_dns_name: |
| 1077 |
description: The private DNS hostname name assigned to the instance. |
| 1078 |
type: str |
| 1079 |
returned: always |
| 1080 |
sample: ip-10-1-0-156.ec2.internal |
| 1081 |
private_ip_address: |
| 1082 |
description: The IPv4 address of the network interface within the subnet. |
| 1083 |
returned: always |
| 1084 |
type: str |
| 1085 |
sample: 10.0.0.1 |
| 1086 |
private_ip_addresses: |
| 1087 |
description: The private IPv4 addresses associated with the network interface. |
| 1088 |
returned: always |
| 1089 |
type: list |
| 1090 |
elements: dict |
| 1091 |
contains: |
| 1092 |
association: |
| 1093 |
description: The association information for an Elastic IP address (IPv4) associated with the network interface. |
| 1094 |
type: complex |
| 1095 |
contains: |
| 1096 |
ip_owner_id: |
| 1097 |
description: The ID of the owner of the Elastic IP address. |
| 1098 |
returned: always |
| 1099 |
type: str |
| 1100 |
sample: amazon |
| 1101 |
public_dns_name: |
| 1102 |
description: The public DNS name. |
| 1103 |
returned: always |
| 1104 |
type: str |
| 1105 |
sample: "" |
| 1106 |
public_ip: |
| 1107 |
description: The public IP address or Elastic IP address bound to the network interface. |
| 1108 |
returned: always |
| 1109 |
type: str |
| 1110 |
sample: 1.2.3.4 |
| 1111 |
primary: |
| 1112 |
description: Indicates whether this IPv4 address is the primary private IP address of the network interface. |
| 1113 |
returned: always |
| 1114 |
type: bool |
| 1115 |
sample: true |
| 1116 |
private_dns_name: |
| 1117 |
description: The private DNS hostname name assigned to the instance. |
| 1118 |
type: str |
| 1119 |
returned: always |
| 1120 |
sample: ip-10-1-0-156.ec2.internal |
| 1121 |
private_ip_address: |
| 1122 |
description: The private IPv4 address of the network interface. |
| 1123 |
returned: always |
| 1124 |
type: str |
| 1125 |
sample: 10.0.0.1 |
| 1126 |
source_dest_check: |
| 1127 |
description: Indicates whether source/destination checking is enabled. |
| 1128 |
returned: always |
| 1129 |
type: bool |
| 1130 |
sample: true |
| 1131 |
status: |
| 1132 |
description: The status of the network interface. |
| 1133 |
returned: always |
| 1134 |
type: str |
| 1135 |
sample: in-use |
| 1136 |
subnet_id: |
| 1137 |
description: The ID of the subnet for the network interface. |
| 1138 |
returned: always |
| 1139 |
type: str |
| 1140 |
sample: subnet-0123456 |
| 1141 |
vpc_id: |
| 1142 |
description: The ID of the VPC for the network interface. |
| 1143 |
returned: always |
| 1144 |
type: str |
| 1145 |
sample: vpc-0123456 |
| 1146 |
placement: |
| 1147 |
description: The location where the instance launched, if applicable. |
| 1148 |
returned: always |
| 1149 |
type: complex |
| 1150 |
contains: |
| 1151 |
availability_zone: |
| 1152 |
description: The Availability Zone of the instance. |
| 1153 |
returned: always |
| 1154 |
type: str |
| 1155 |
sample: ap-southeast-2a |
| 1156 |
affinity: |
| 1157 |
description: The affinity setting for the instance on the Dedicated Host. |
| 1158 |
returned: When a placement group is specified. |
| 1159 |
type: str |
| 1160 |
group_id: |
| 1161 |
description: The ID of the placement group the instance is in (for cluster compute instances). |
| 1162 |
type: str |
| 1163 |
sample: "pg-01234566" |
| 1164 |
group_name: |
| 1165 |
description: The name of the placement group the instance is in (for cluster compute instances). |
| 1166 |
returned: always |
| 1167 |
type: str |
| 1168 |
sample: "my-placement-group" |
| 1169 |
host_id: |
| 1170 |
description: The ID of the Dedicated Host on which the instance resides. |
| 1171 |
type: str |
| 1172 |
host_resource_group_arn: |
| 1173 |
description: The ARN of the host resource group in which the instance is in. |
| 1174 |
type: str |
| 1175 |
sample: "arn:aws:resource-groups:us-east-1:123456789012:group/MyResourceGroup" |
| 1176 |
partition_number: |
| 1177 |
description: The number of the partition the instance is in. |
| 1178 |
type: int |
| 1179 |
sample: 1 |
| 1180 |
tenancy: |
| 1181 |
description: Type of tenancy to allow an instance to use. Default is shared tenancy. Dedicated tenancy will incur additional charges. |
| 1182 |
returned: always |
| 1183 |
type: str |
| 1184 |
sample: default |
| 1185 |
additional_info: |
| 1186 |
description: Reserved for Amazon's internal use. |
| 1187 |
returned: always |
| 1188 |
type: str |
| 1189 |
version_added: 7.1.0 |
| 1190 |
sample: |
| 1191 |
platform_details: |
| 1192 |
description: The platform details value for the instance. |
| 1193 |
returned: always |
| 1194 |
type: str |
| 1195 |
sample: Linux/UNIX |
| 1196 |
private_dns_name: |
| 1197 |
description: The private DNS name. |
| 1198 |
returned: always |
| 1199 |
type: str |
| 1200 |
sample: ip-10-0-0-1.ap-southeast-2.compute.internal |
| 1201 |
private_dns_name_options: |
| 1202 |
description: The options for the instance hostname. |
| 1203 |
type: dict |
| 1204 |
contains: |
| 1205 |
enable_resource_name_dns_a_record: |
| 1206 |
description: Indicates whether to respond to DNS queries for instance hostnames with DNS A records. |
| 1207 |
type: bool |
| 1208 |
sample: false |
| 1209 |
enable_resource_name_dns_aaaa_record: |
| 1210 |
description: Indicates whether to respond to DNS queries for instance hostnames with DNS AAAA records. |
| 1211 |
type: bool |
| 1212 |
sample: false |
| 1213 |
hostname_type: |
| 1214 |
description: The type of hostname to assign to an instance. |
| 1215 |
type: str |
| 1216 |
sample: ip-name |
| 1217 |
private_ip_address: |
| 1218 |
description: The IPv4 address of the network interface within the subnet. |
| 1219 |
returned: always |
| 1220 |
type: str |
| 1221 |
sample: 10.0.0.1 |
| 1222 |
product_codes: |
| 1223 |
description: One or more product codes. |
| 1224 |
returned: always |
| 1225 |
type: list |
| 1226 |
elements: dict |
| 1227 |
contains: |
| 1228 |
product_code_id: |
| 1229 |
description: The product code. |
| 1230 |
returned: always |
| 1231 |
type: str |
| 1232 |
sample: aw0evgkw8ef3n2498gndfgasdfsd5cce |
| 1233 |
product_code_type: |
| 1234 |
description: The type of product code. |
| 1235 |
returned: always |
| 1236 |
type: str |
| 1237 |
sample: marketplace |
| 1238 |
public_dns_name: |
| 1239 |
description: The public DNS name assigned to the instance. |
| 1240 |
returned: always |
| 1241 |
type: str |
| 1242 |
sample: |
| 1243 |
public_ip_address: |
| 1244 |
description: The public IPv4 address assigned to the instance |
| 1245 |
returned: always |
| 1246 |
type: str |
| 1247 |
sample: 52.0.0.1 |
| 1248 |
root_device_name: |
| 1249 |
description: The device name of the root device |
| 1250 |
returned: always |
| 1251 |
type: str |
| 1252 |
sample: /dev/sda1 |
| 1253 |
root_device_type: |
| 1254 |
description: The type of root device used by the AMI. |
| 1255 |
returned: always |
| 1256 |
type: str |
| 1257 |
sample: ebs |
| 1258 |
security_groups: |
| 1259 |
description: One or more security groups for the instance. |
| 1260 |
returned: always |
| 1261 |
type: list |
| 1262 |
elements: dict |
| 1263 |
contains: |
| 1264 |
group_id: |
| 1265 |
description: The ID of the security group. |
| 1266 |
returned: always |
| 1267 |
type: str |
| 1268 |
sample: sg-0123456 |
| 1269 |
group_name: |
| 1270 |
description: The name of the security group. |
| 1271 |
returned: always |
| 1272 |
type: str |
| 1273 |
sample: my-security-group |
| 1274 |
source_dest_check: |
| 1275 |
description: Indicates whether source/destination checking is enabled. |
| 1276 |
returned: always |
| 1277 |
type: bool |
| 1278 |
sample: true |
| 1279 |
state: |
| 1280 |
description: The current state of the instance. |
| 1281 |
returned: always |
| 1282 |
type: complex |
| 1283 |
contains: |
| 1284 |
code: |
| 1285 |
description: The low byte represents the state. |
| 1286 |
returned: always |
| 1287 |
type: int |
| 1288 |
sample: 16 |
| 1289 |
name: |
| 1290 |
description: The name of the state. |
| 1291 |
returned: always |
| 1292 |
type: str |
| 1293 |
sample: running |
| 1294 |
state_transition_reason: |
| 1295 |
description: The reason for the most recent state transition. |
| 1296 |
returned: always |
| 1297 |
type: str |
| 1298 |
sample: |
| 1299 |
subnet_id: |
| 1300 |
description: The ID of the subnet in which the instance is running. |
| 1301 |
returned: always |
| 1302 |
type: str |
| 1303 |
sample: subnet-00abcdef |
| 1304 |
tags: |
| 1305 |
description: Any tags assigned to the instance. |
| 1306 |
returned: always |
| 1307 |
type: dict |
| 1308 |
sample: |
| 1309 |
virtualization_type: |
| 1310 |
description: The type of virtualization of the AMI. |
| 1311 |
returned: always |
| 1312 |
type: str |
| 1313 |
sample: hvm |
| 1314 |
vpc_id: |
| 1315 |
description: The ID of the VPC the instance is in. |
| 1316 |
returned: always |
| 1317 |
type: dict |
| 1318 |
sample: vpc-0011223344 |
| 1319 |
""" |
| 1320 |
|
| 1321 |
import time |
| 1322 |
import uuid |
| 1323 |
from collections import namedtuple |
| 1324 |
from typing import Any |
| 1325 |
from typing import Dict |
| 1326 |
from typing import List |
| 1327 |
from typing import Optional |
| 1328 |
from typing import Set |
| 1329 |
from typing import Tuple |
| 1330 |
from typing import Union |
| 1331 |
|
| 1332 |
try: |
| 1333 |
import botocore |
| 1334 |
except ImportError: |
| 1335 |
pass # caught by AnsibleAWSModule |
| 1336 |
|
| 1337 |
|
| 1338 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 1339 |
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict |
| 1340 |
from ansible.module_utils.common.text.converters import to_native |
| 1341 |
|
| 1342 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error |
| 1343 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import associate_iam_instance_profile |
| 1344 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import attach_network_interface |
| 1345 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_iam_instance_profile_associations |
| 1346 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_instance_attribute |
| 1347 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_instance_status |
| 1348 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_instances |
| 1349 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_subnets |
| 1350 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_vpcs |
| 1351 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import determine_iam_arn_from_name |
| 1352 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags |
| 1353 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import get_ec2_security_group_ids_from_names |
| 1354 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import modify_instance_attribute |
| 1355 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import modify_instance_metadata_options |
| 1356 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import replace_iam_instance_profile_association |
| 1357 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import run_instances as run_ec2_instances |
| 1358 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import start_instances |
| 1359 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import stop_instances |
| 1360 |
from ansible_collections.amazon.aws.plugins.module_utils.ec2 import terminate_instances |
| 1361 |
from ansible_collections.amazon.aws.plugins.module_utils.exceptions import AnsibleAWSError |
| 1362 |
from ansible_collections.amazon.aws.plugins.module_utils.exceptions import is_ansible_aws_error_code |
| 1363 |
from ansible_collections.amazon.aws.plugins.module_utils.exceptions import is_ansible_aws_error_message |
| 1364 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 1365 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 1366 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict |
| 1367 |
from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications |
| 1368 |
from ansible_collections.amazon.aws.plugins.module_utils.tower import tower_callback_script |
| 1369 |
from ansible_collections.amazon.aws.plugins.module_utils.transformation import ansible_dict_to_boto3_filter_list |
| 1370 |
|
| 1371 |
|
| 1372 |
def build_volume_spec(params: Dict[str, Any]) -> List[Dict[str, Any]]: |
| 1373 |
volumes = params.get("volumes") or [] |
| 1374 |
for volume in volumes: |
| 1375 |
if "ebs" in volume: |
| 1376 |
for int_value in ["volume_size", "iops"]: |
| 1377 |
if int_value in volume["ebs"]: |
| 1378 |
volume["ebs"][int_value] = int(volume["ebs"][int_value]) |
| 1379 |
if "volume_type" in volume["ebs"] and volume["ebs"]["volume_type"] == "gp3": |
| 1380 |
if not volume["ebs"].get("iops"): |
| 1381 |
volume["ebs"]["iops"] = 3000 |
| 1382 |
if "throughput" in volume["ebs"]: |
| 1383 |
volume["ebs"]["throughput"] = int(volume["ebs"]["throughput"]) |
| 1384 |
else: |
| 1385 |
volume["ebs"]["throughput"] = 125 |
| 1386 |
|
| 1387 |
return [snake_dict_to_camel_dict(v, capitalize_first=True) for v in volumes] |
| 1388 |
|
| 1389 |
|
| 1390 |
def add_or_update_instance_profile( |
| 1391 |
client, module: AnsibleAWSModule, instance: Dict[str, Any], desired_profile_name: str |
| 1392 |
) -> bool: |
| 1393 |
instance_profile_setting = instance.get("IamInstanceProfile") |
| 1394 |
iam_client = None |
| 1395 |
if instance_profile_setting and desired_profile_name: |
| 1396 |
if desired_profile_name in (instance_profile_setting.get("Name"), instance_profile_setting.get("Arn")): |
| 1397 |
# great, the profile we asked for is what's there |
| 1398 |
return False |
| 1399 |
else: |
| 1400 |
iam_client = module.client("iam") |
| 1401 |
desired_arn = determine_iam_arn_from_name(iam_client, desired_profile_name) |
| 1402 |
if instance_profile_setting.get("Arn") == desired_arn: |
| 1403 |
return False |
| 1404 |
|
| 1405 |
# update association |
| 1406 |
try: |
| 1407 |
association = describe_iam_instance_profile_associations( |
| 1408 |
client, Filters=[{"Name": "instance-id", "Values": [instance["InstanceId"]]}] |
| 1409 |
) |
| 1410 |
except AnsibleEC2Error as e: |
| 1411 |
# check for InvalidAssociationID.NotFound |
| 1412 |
module.fail_json_aws(e, "Could not find instance profile association") |
| 1413 |
try: |
| 1414 |
iam_client = iam_client or module.client("iam") |
| 1415 |
replace_iam_instance_profile_association( |
| 1416 |
client, |
| 1417 |
association_id=association[0]["AssociationId"], |
| 1418 |
iam_instance_profile={"Arn": determine_iam_arn_from_name(iam_client, desired_profile_name)}, |
| 1419 |
) |
| 1420 |
return True |
| 1421 |
except AnsibleEC2Error as e: |
| 1422 |
module.fail_json_aws(e, "Could not associate instance profile") |
| 1423 |
|
| 1424 |
if not instance_profile_setting and desired_profile_name: |
| 1425 |
# create association |
| 1426 |
try: |
| 1427 |
iam_client = iam_client or module.client("iam") |
| 1428 |
associate_iam_instance_profile( |
| 1429 |
client, |
| 1430 |
iam_instance_profile={"Arn": determine_iam_arn_from_name(iam_client, desired_profile_name)}, |
| 1431 |
instance_id=instance["InstanceId"], |
| 1432 |
) |
| 1433 |
return True |
| 1434 |
except AnsibleEC2Error as e: |
| 1435 |
module.fail_json_aws(e, "Could not associate new instance profile") |
| 1436 |
|
| 1437 |
return False |
| 1438 |
|
| 1439 |
|
| 1440 |
def validate_assign_public_ip(module: AnsibleAWSModule) -> None: |
| 1441 |
""" |
| 1442 |
Validate Network interface public IP configuration |
| 1443 |
Parameters: |
| 1444 |
module: The ansible AWS module. |
| 1445 |
""" |
| 1446 |
network_interfaces = module.params.get("network_interfaces") or [] |
| 1447 |
network_interfaces_ids = module.params.get("network_interfaces_ids") or [] |
| 1448 |
if len(network_interfaces + network_interfaces_ids) > 1 and any( |
| 1449 |
i.get("assign_public_ip") for i in network_interfaces if i.get("assign_public_ip") is not None |
| 1450 |
): |
| 1451 |
module.fail_json(msg="The option 'assign_public_ip' cannot be set to true with multiple network interfaces.") |
| 1452 |
|
| 1453 |
|
| 1454 |
def validate_network_params(module: AnsibleAWSModule, nb_instances: int) -> None: |
| 1455 |
""" |
| 1456 |
This function is used to validate network specifications with the following constraints |
| 1457 |
- 'assign_public_ip' cannot set to True when multiple network interfaces are specified |
| 1458 |
- 'private_ip_addresses' only one IP can be set as primary |
| 1459 |
- 'private_ip_addresses' or 'private_ip_address' can't be specified if launching more than one instance |
| 1460 |
Parameters: |
| 1461 |
module: The ansible AWS module. |
| 1462 |
nb_instances: number of instance to create. |
| 1463 |
""" |
| 1464 |
validate_assign_public_ip(module) |
| 1465 |
|
| 1466 |
network_interfaces = module.params.get("network_interfaces") |
| 1467 |
if network_interfaces: |
| 1468 |
# private_ip_addresses: ensure only one private ip is set as primary |
| 1469 |
for inty in network_interfaces: |
| 1470 |
if len([i for i in inty.get("private_ip_addresses") or [] if i.get("primary")]) > 1: |
| 1471 |
module.fail_json( |
| 1472 |
msg="Only one primary private IP address can be specified when creating network interface." |
| 1473 |
) |
| 1474 |
|
| 1475 |
# Ensure none of 'private_ip_address', 'private_ip_addresses', 'ipv6_addresses' were provided |
| 1476 |
# when launching more than one instance |
| 1477 |
if nb_instances > 1: |
| 1478 |
for opt in ("private_ip_address", "private_ip_addresses", "ipv6_addresses"): |
| 1479 |
if any(True for inty in network_interfaces if inty.get(opt)): |
| 1480 |
module.fail_json( |
| 1481 |
msg=f"The option '{opt}' cannot be specified when launching more than one instance." |
| 1482 |
) |
| 1483 |
|
| 1484 |
|
| 1485 |
def ansible_to_boto3_eni_specification( |
| 1486 |
client, |
| 1487 |
module: AnsibleAWSModule, |
| 1488 |
interface: Dict[str, Any], |
| 1489 |
subnet_id: Optional[str], |
| 1490 |
groups: Optional[Union[List[str], str]], |
| 1491 |
) -> Dict[str, Any]: |
| 1492 |
""" |
| 1493 |
Converts Ansible network interface specifications into AWS network interface spec |
| 1494 |
Parameters: |
| 1495 |
interface: Ansible network interface specification |
| 1496 |
subnet_id: Subnet Id |
| 1497 |
security_groups: Optional list of security groups. |
| 1498 |
security_group: Optional security group. |
| 1499 |
Returns: |
| 1500 |
AWS network interface specification. |
| 1501 |
""" |
| 1502 |
spec = { |
| 1503 |
"DeviceIndex": interface.get("device_index", 0), |
| 1504 |
} |
| 1505 |
if interface.get("assign_public_ip"): |
| 1506 |
spec["AssociatePublicIpAddress"] = interface["assign_public_ip"] |
| 1507 |
|
| 1508 |
if interface.get("subnet_id"): |
| 1509 |
spec["SubnetId"] = interface["subnet_id"] |
| 1510 |
elif subnet_id: |
| 1511 |
spec["SubnetId"] = subnet_id |
| 1512 |
else: |
| 1513 |
spec["SubnetId"] = describe_default_subnet(client, module) |
| 1514 |
|
| 1515 |
if interface.get("ipv6_addresses"): |
| 1516 |
spec["Ipv6Addresses"] = [{"Ipv6Address": a} for a in interface["ipv6_addresses"]] |
| 1517 |
|
| 1518 |
if interface.get("private_ip_address"): |
| 1519 |
spec["PrivateIpAddress"] = interface["private_ip_address"] |
| 1520 |
|
| 1521 |
if interface.get("private_ip_addresses"): |
| 1522 |
spec["PrivateIpAddresses"] = [] |
| 1523 |
for addr in interface["private_ip_addresses"]: |
| 1524 |
d = {"PrivateIpAddress": addr} |
| 1525 |
if isinstance(addr, dict): |
| 1526 |
d = {"PrivateIpAddress": addr.get("private_ip_address")} |
| 1527 |
if addr.get("primary") is not None: |
| 1528 |
d.update({"Primary": addr.get("primary")}) |
| 1529 |
spec["PrivateIpAddresses"].append(d) |
| 1530 |
|
| 1531 |
spec["DeleteOnTermination"] = interface.get("delete_on_termination", True) |
| 1532 |
|
| 1533 |
interface_groups = interface.get("groups") or groups |
| 1534 |
if interface_groups: |
| 1535 |
spec["Groups"] = discover_security_groups(client, module, groups=interface_groups, subnet_id=spec["SubnetId"]) |
| 1536 |
if interface.get("description") is not None: |
| 1537 |
spec["Description"] = interface["description"] |
| 1538 |
return spec |
| 1539 |
|
| 1540 |
|
| 1541 |
def build_network_spec(client, module: AnsibleAWSModule) -> List[Dict[str, Any]]: |
| 1542 |
""" |
| 1543 |
Returns network interface specifications for instance to be created. |
| 1544 |
Parameters: |
| 1545 |
module: The ansible AWS module. |
| 1546 |
Returns: |
| 1547 |
network specs (list): List of network interfaces specifications |
| 1548 |
""" |
| 1549 |
|
| 1550 |
# They specified network_interfaces_ids (mutually exclusive with security_group(s) options) |
| 1551 |
interfaces = [] |
| 1552 |
params = module.params |
| 1553 |
network_interfaces_ids = params.get("network_interfaces_ids") |
| 1554 |
if network_interfaces_ids: |
| 1555 |
interfaces = [ |
| 1556 |
{"NetworkInterfaceId": eni.get("id"), "DeviceIndex": eni.get("device_index")} |
| 1557 |
for eni in network_interfaces_ids |
| 1558 |
] |
| 1559 |
|
| 1560 |
network = params.get("network") |
| 1561 |
groups = params.get("security_groups") or params.get("security_group") |
| 1562 |
vpc_subnet_id = params.get("vpc_subnet_id") |
| 1563 |
network_interfaces = params.get("network_interfaces") |
| 1564 |
if (network and not network.get("interfaces")) or network_interfaces: |
| 1565 |
# They specified network interfaces using `network` or `network_interfaces` options |
| 1566 |
if network and not network.get("interfaces"): |
| 1567 |
network_interfaces = [network] |
| 1568 |
interfaces.extend( |
| 1569 |
[ |
| 1570 |
ansible_to_boto3_eni_specification(client, module, inty, vpc_subnet_id, groups) |
| 1571 |
for inty in network_interfaces |
| 1572 |
] |
| 1573 |
) |
| 1574 |
elif not network and not network_interfaces_ids and not module.params.get("launch_template"): |
| 1575 |
# No network interface configuration specified and no launch template |
| 1576 |
# Build network interface using subnet_id and security group(s) defined in the module |
| 1577 |
interfaces.append(ansible_to_boto3_eni_specification(client, module, {}, vpc_subnet_id, groups)) |
| 1578 |
elif network: |
| 1579 |
# handle list of `network.interfaces` options |
| 1580 |
interfaces.extend( |
| 1581 |
[ |
| 1582 |
{"DeviceIndex": idx, "NetworkInterfaceId": inty if isinstance(inty, str) else inty.get("id")} |
| 1583 |
for idx, inty in enumerate(network.get("interfaces", [])) |
| 1584 |
] |
| 1585 |
) |
| 1586 |
return interfaces |
| 1587 |
|
| 1588 |
|
| 1589 |
def warn_if_public_ip_assignment_changed(module: AnsibleAWSModule, instance: Dict[str, Any]) -> None: |
| 1590 |
# This is a non-modifiable attribute. |
| 1591 |
assign_public_ip = (module.params.get("network") or {}).get("assign_public_ip") |
| 1592 |
validate_assign_public_ip(module) |
| 1593 |
network_interfaces = module.params.get("network_interfaces") |
| 1594 |
if network_interfaces: |
| 1595 |
# Either we only have one network interface or multiple network interface with 'assign_public_ip=false' |
| 1596 |
# Anyways the value 'assign_public_ip' in the first item should be enough to determine whether |
| 1597 |
# the user wants to update the public IP or not |
| 1598 |
assign_public_ip = network_interfaces[0].get("assign_public_ip") |
| 1599 |
if assign_public_ip is None: |
| 1600 |
return |
| 1601 |
|
| 1602 |
# Check that public ip assignment is the same and warn if not |
| 1603 |
public_dns_name = instance.get("PublicDnsName") |
| 1604 |
if (public_dns_name and not assign_public_ip) or (assign_public_ip and not public_dns_name): |
| 1605 |
module.warn( |
| 1606 |
f"Unable to modify public ip assignment to {assign_public_ip} for instance {instance['InstanceId']}." |
| 1607 |
" Whether or not to assign a public IP is determined during instance creation." |
| 1608 |
) |
| 1609 |
|
| 1610 |
|
| 1611 |
def warn_if_cpu_options_changed(module: AnsibleAWSModule, instance: Dict[str, Any]) -> None: |
| 1612 |
# This is a non-modifiable attribute. |
| 1613 |
cpu_options = module.params.get("cpu_options") |
| 1614 |
if cpu_options is None: |
| 1615 |
return |
| 1616 |
|
| 1617 |
# Check that the CpuOptions set are the same and warn if not |
| 1618 |
core_count_curr = instance["CpuOptions"].get("CoreCount") |
| 1619 |
core_count = cpu_options.get("core_count") |
| 1620 |
threads_per_core_curr = instance["CpuOptions"].get("ThreadsPerCore") |
| 1621 |
threads_per_core = cpu_options.get("threads_per_core") |
| 1622 |
if core_count_curr != core_count: |
| 1623 |
module.warn( |
| 1624 |
f"Unable to modify core_count from {core_count_curr} to {core_count}. Assigning a number of core is" |
| 1625 |
" determinted during instance creation" |
| 1626 |
) |
| 1627 |
|
| 1628 |
if threads_per_core_curr != threads_per_core: |
| 1629 |
module.warn( |
| 1630 |
f"Unable to modify threads_per_core from {threads_per_core_curr} to {threads_per_core}. Assigning a number" |
| 1631 |
" of threads per core is determined during instance creation." |
| 1632 |
) |
| 1633 |
|
| 1634 |
|
| 1635 |
def discover_security_groups( |
| 1636 |
client, |
| 1637 |
module: AnsibleAWSModule, |
| 1638 |
groups: Union[str, List[str]], |
| 1639 |
parent_vpc_id: Optional[str] = None, |
| 1640 |
subnet_id: Optional[str] = None, |
| 1641 |
) -> List[str]: |
| 1642 |
if subnet_id is not None: |
| 1643 |
try: |
| 1644 |
sub = describe_subnets(client, SubnetIds=[subnet_id]) |
| 1645 |
except is_ansible_aws_error_code("InvalidGroup.NotFound"): |
| 1646 |
module.fail_json( |
| 1647 |
f"Could not find subnet {subnet_id} to associate security groups. Please check the vpc_subnet_id and" |
| 1648 |
" security_groups parameters." |
| 1649 |
) |
| 1650 |
except AnsibleAWSError as e: # pylint: disable=duplicate-except |
| 1651 |
module.fail_json_aws(e, msg=f"Error while searching for subnet {subnet_id} parent VPC.") |
| 1652 |
parent_vpc_id = sub[0]["VpcId"] |
| 1653 |
|
| 1654 |
return get_ec2_security_group_ids_from_names(groups, client, vpc_id=parent_vpc_id) |
| 1655 |
|
| 1656 |
|
| 1657 |
def build_userdata(params): |
| 1658 |
if params.get("user_data") is not None: |
| 1659 |
return {"UserData": to_native(params.get("user_data"))} |
| 1660 |
if params.get("aap_callback"): |
| 1661 |
userdata = tower_callback_script( |
| 1662 |
tower_address=params.get("aap_callback").get("tower_address"), |
| 1663 |
job_template_id=params.get("aap_callback").get("job_template_id"), |
| 1664 |
host_config_key=params.get("aap_callback").get("host_config_key"), |
| 1665 |
windows=params.get("aap_callback").get("windows"), |
| 1666 |
passwd=params.get("aap_callback").get("set_password"), |
| 1667 |
) |
| 1668 |
return {"UserData": userdata} |
| 1669 |
return {} |
| 1670 |
|
| 1671 |
|
| 1672 |
def build_top_level_options(module: AnsibleAWSModule) -> Dict[str, Any]: |
| 1673 |
spec = {} |
| 1674 |
params = module.params |
| 1675 |
if params.get("image_id"): |
| 1676 |
spec["ImageId"] = params["image_id"] |
| 1677 |
elif params.get("image"): |
| 1678 |
image = params.get("image") |
| 1679 |
spec["ImageId"] = image.get("id") |
| 1680 |
if image.get("ramdisk"): |
| 1681 |
spec["RamdiskId"] = image["ramdisk"] |
| 1682 |
if image.get("kernel"): |
| 1683 |
spec["KernelId"] = image["kernel"] |
| 1684 |
if not spec.get("ImageId") and not params.get("launch_template"): |
| 1685 |
module.fail_json( |
| 1686 |
msg="You must include an image_id or image.id parameter to create an instance, or use a launch_template." |
| 1687 |
) |
| 1688 |
|
| 1689 |
if params.get("key_name") is not None: |
| 1690 |
spec["KeyName"] = params.get("key_name") |
| 1691 |
|
| 1692 |
spec.update(build_userdata(params)) |
| 1693 |
|
| 1694 |
if params.get("launch_template") is not None: |
| 1695 |
spec["LaunchTemplate"] = {} |
| 1696 |
if not params.get("launch_template").get("id") and not params.get("launch_template").get("name"): |
| 1697 |
module.fail_json( |
| 1698 |
msg=( |
| 1699 |
"Could not create instance with launch template. Either launch_template.name or launch_template.id" |
| 1700 |
" parameters are required" |
| 1701 |
) |
| 1702 |
) |
| 1703 |
|
| 1704 |
if params.get("launch_template").get("id") is not None: |
| 1705 |
spec["LaunchTemplate"]["LaunchTemplateId"] = params.get("launch_template").get("id") |
| 1706 |
if params.get("launch_template").get("name") is not None: |
| 1707 |
spec["LaunchTemplate"]["LaunchTemplateName"] = params.get("launch_template").get("name") |
| 1708 |
if params.get("launch_template").get("version") is not None: |
| 1709 |
spec["LaunchTemplate"]["Version"] = to_native(params.get("launch_template").get("version")) |
| 1710 |
|
| 1711 |
if params.get("detailed_monitoring", False): |
| 1712 |
spec["Monitoring"] = {"Enabled": True} |
| 1713 |
if params.get("cpu_credit_specification") is not None: |
| 1714 |
spec["CreditSpecification"] = {"CpuCredits": params.get("cpu_credit_specification")} |
| 1715 |
if params.get("tenancy") is not None: |
| 1716 |
spec["Placement"] = {"Tenancy": params.get("tenancy")} |
| 1717 |
if params.get("placement_group"): |
| 1718 |
if "Placement" in spec: |
| 1719 |
spec["Placement"]["GroupName"] = str(params.get("placement_group")) |
| 1720 |
else: |
| 1721 |
spec.setdefault("Placement", {"GroupName": str(params.get("placement_group"))}) |
| 1722 |
if params.get("placement") is not None: |
| 1723 |
spec["Placement"] = {} |
| 1724 |
if params.get("placement").get("availability_zone") is not None: |
| 1725 |
spec["Placement"]["AvailabilityZone"] = params.get("placement").get("availability_zone") |
| 1726 |
if params.get("placement").get("affinity") is not None: |
| 1727 |
spec["Placement"]["Affinity"] = params.get("placement").get("affinity") |
| 1728 |
if params.get("placement").get("group_name") is not None: |
| 1729 |
spec["Placement"]["GroupName"] = params.get("placement").get("group_name") |
| 1730 |
if params.get("placement").get("host_id") is not None: |
| 1731 |
spec["Placement"]["HostId"] = params.get("placement").get("host_id") |
| 1732 |
if params.get("placement").get("host_resource_group_arn") is not None: |
| 1733 |
spec["Placement"]["HostResourceGroupArn"] = params.get("placement").get("host_resource_group_arn") |
| 1734 |
if params.get("placement").get("partition_number") is not None: |
| 1735 |
spec["Placement"]["PartitionNumber"] = params.get("placement").get("partition_number") |
| 1736 |
if params.get("placement").get("tenancy") is not None: |
| 1737 |
spec["Placement"]["Tenancy"] = params.get("placement").get("tenancy") |
| 1738 |
if params.get("ebs_optimized") is not None: |
| 1739 |
spec["EbsOptimized"] = params.get("ebs_optimized") |
| 1740 |
if params.get("instance_initiated_shutdown_behavior"): |
| 1741 |
spec["InstanceInitiatedShutdownBehavior"] = params.get("instance_initiated_shutdown_behavior") |
| 1742 |
if params.get("termination_protection") is not None: |
| 1743 |
spec["DisableApiTermination"] = params.get("termination_protection") |
| 1744 |
if params.get("hibernation_options") and params.get("volumes"): |
| 1745 |
for vol in params["volumes"]: |
| 1746 |
if vol.get("ebs") and vol["ebs"].get("encrypted"): |
| 1747 |
spec["HibernationOptions"] = {"Configured": True} |
| 1748 |
else: |
| 1749 |
module.fail_json( |
| 1750 |
msg=( |
| 1751 |
"Hibernation prerequisites not satisfied. Refer to" |
| 1752 |
" https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/hibernating-prerequisites.html" |
| 1753 |
) |
| 1754 |
) |
| 1755 |
if params.get("cpu_options") is not None: |
| 1756 |
spec["CpuOptions"] = {} |
| 1757 |
spec["CpuOptions"]["ThreadsPerCore"] = params.get("cpu_options").get("threads_per_core") |
| 1758 |
spec["CpuOptions"]["CoreCount"] = params.get("cpu_options").get("core_count") |
| 1759 |
if params.get("metadata_options"): |
| 1760 |
spec["MetadataOptions"] = {} |
| 1761 |
spec["MetadataOptions"]["HttpEndpoint"] = params.get("metadata_options").get("http_endpoint") |
| 1762 |
spec["MetadataOptions"]["HttpTokens"] = params.get("metadata_options").get("http_tokens") |
| 1763 |
spec["MetadataOptions"]["HttpPutResponseHopLimit"] = params.get("metadata_options").get( |
| 1764 |
"http_put_response_hop_limit" |
| 1765 |
) |
| 1766 |
spec["MetadataOptions"]["HttpProtocolIpv6"] = params.get("metadata_options").get("http_protocol_ipv6") |
| 1767 |
spec["MetadataOptions"]["InstanceMetadataTags"] = params.get("metadata_options").get("instance_metadata_tags") |
| 1768 |
if params.get("additional_info"): |
| 1769 |
spec["AdditionalInfo"] = params.get("additional_info") |
| 1770 |
if params.get("license_specifications"): |
| 1771 |
spec["LicenseSpecifications"] = [] |
| 1772 |
for license_configuration in params.get("license_specifications"): |
| 1773 |
spec["LicenseSpecifications"].append( |
| 1774 |
{"LicenseConfigurationArn": license_configuration.get("license_configuration_arn")} |
| 1775 |
) |
| 1776 |
return spec |
| 1777 |
|
| 1778 |
|
| 1779 |
def build_instance_tags(params: Dict[str, Any]) -> List[Dict[str, Any]]: |
| 1780 |
tags = params.get("tags") or {} |
| 1781 |
if params.get("name") is not None: |
| 1782 |
tags["Name"] = params.get("name") |
| 1783 |
specs = boto3_tag_specifications(tags, ["volume", "instance"]) |
| 1784 |
return specs |
| 1785 |
|
| 1786 |
|
| 1787 |
def build_run_instance_spec(client, module: AnsibleAWSModule, current_count: int = 0) -> Dict[str, Any]: |
| 1788 |
spec = dict( |
| 1789 |
ClientToken=uuid.uuid4().hex, |
| 1790 |
) |
| 1791 |
params = module.params |
| 1792 |
spec.update(**build_top_level_options(module)) |
| 1793 |
|
| 1794 |
nb_instances = params.get("count") or 1 |
| 1795 |
if params.get("exact_count"): |
| 1796 |
nb_instances = params.get("exact_count") - current_count |
| 1797 |
|
| 1798 |
spec["MinCount"] = nb_instances |
| 1799 |
spec["MaxCount"] = nb_instances |
| 1800 |
|
| 1801 |
# Validate network parameters |
| 1802 |
validate_network_params(module, nb_instances) |
| 1803 |
# Build network specs |
| 1804 |
network_specs = build_network_spec(client, module) |
| 1805 |
if network_specs: |
| 1806 |
spec["NetworkInterfaces"] = network_specs |
| 1807 |
# Build volume specs |
| 1808 |
volume_specs = build_volume_spec(params) |
| 1809 |
if volume_specs: |
| 1810 |
spec["BlockDeviceMappings"] = volume_specs |
| 1811 |
|
| 1812 |
tag_spec = build_instance_tags(params) |
| 1813 |
if tag_spec is not None: |
| 1814 |
spec["TagSpecifications"] = tag_spec |
| 1815 |
|
| 1816 |
# IAM profile |
| 1817 |
if params.get("iam_instance_profile"): |
| 1818 |
spec["IamInstanceProfile"] = dict( |
| 1819 |
Arn=determine_iam_arn_from_name(module.client("iam"), params.get("iam_instance_profile")) |
| 1820 |
) |
| 1821 |
|
| 1822 |
if params.get("instance_type"): |
| 1823 |
spec["InstanceType"] = params["instance_type"] |
| 1824 |
|
| 1825 |
if not (params.get("instance_type") or params.get("launch_template")): |
| 1826 |
raise AnsibleEC2Error( |
| 1827 |
"At least one of 'instance_type' and 'launch_template' must be passed when launching instances." |
| 1828 |
) |
| 1829 |
|
| 1830 |
return spec |
| 1831 |
|
| 1832 |
|
| 1833 |
def await_instances( |
| 1834 |
client, module: AnsibleAWSModule, ids: List[str], desired_module_state: str = "present", force_wait: bool = False |
| 1835 |
) -> None: |
| 1836 |
if not module.params.get("wait", True) and not force_wait: |
| 1837 |
# the user asked not to wait for anything |
| 1838 |
return |
| 1839 |
|
| 1840 |
if module.check_mode: |
| 1841 |
# In check mode, there is no change even if you wait. |
| 1842 |
return |
| 1843 |
|
| 1844 |
# Map ansible state to boto3 waiter type |
| 1845 |
state_to_boto3_waiter = { |
| 1846 |
"present": "instance_exists", |
| 1847 |
"started": "instance_status_ok", |
| 1848 |
"running": "instance_running", |
| 1849 |
"stopped": "instance_stopped", |
| 1850 |
"restarted": "instance_status_ok", |
| 1851 |
"rebooted": "instance_running", |
| 1852 |
"terminated": "instance_terminated", |
| 1853 |
"absent": "instance_terminated", |
| 1854 |
} |
| 1855 |
if desired_module_state not in state_to_boto3_waiter: |
| 1856 |
module.fail_json(msg=f"Cannot wait for state {desired_module_state}, invalid state") |
| 1857 |
boto3_waiter_type = state_to_boto3_waiter[desired_module_state] |
| 1858 |
waiter = client.get_waiter(boto3_waiter_type) |
| 1859 |
try: |
| 1860 |
waiter.wait( |
| 1861 |
InstanceIds=ids, |
| 1862 |
WaiterConfig={ |
| 1863 |
"Delay": 15, |
| 1864 |
"MaxAttempts": module.params.get("wait_timeout", 600) // 15, |
| 1865 |
}, |
| 1866 |
) |
| 1867 |
except botocore.exceptions.WaiterConfigError as e: |
| 1868 |
instance_ids = ", ".join(ids) |
| 1869 |
module.fail_json( |
| 1870 |
msg=f"{to_native(e)}. Error waiting for instances {instance_ids} to reach state {boto3_waiter_type}" |
| 1871 |
) |
| 1872 |
except botocore.exceptions.WaiterError as e: |
| 1873 |
instance_ids = ", ".join(ids) |
| 1874 |
module.warn(f"Instances {instance_ids} took too long to reach state {boto3_waiter_type}. {to_native(e)}") |
| 1875 |
|
| 1876 |
|
| 1877 |
def diff_instance_and_params( |
| 1878 |
client, module: AnsibleAWSModule, instance: Dict[str, Any], skip: Optional[List[str]] = None |
| 1879 |
) -> List[Dict[str, Any]]: |
| 1880 |
"""boto3 instance obj, module params""" |
| 1881 |
|
| 1882 |
if skip is None: |
| 1883 |
skip = [] |
| 1884 |
|
| 1885 |
changes_to_apply = [] |
| 1886 |
id_ = instance["InstanceId"] |
| 1887 |
|
| 1888 |
ParamMapper = namedtuple("ParamMapper", ["param_key", "instance_key", "attribute_name", "add_value"]) |
| 1889 |
|
| 1890 |
def value_wrapper(v): |
| 1891 |
return {"Value": v} |
| 1892 |
|
| 1893 |
param_mappings = [ |
| 1894 |
ParamMapper("ebs_optimized", "EbsOptimized", "ebsOptimized", value_wrapper), |
| 1895 |
ParamMapper("termination_protection", "DisableApiTermination", "disableApiTermination", value_wrapper), |
| 1896 |
ParamMapper("instance_type", "InstanceType", "instanceType", value_wrapper), |
| 1897 |
# user data is an immutable property |
| 1898 |
# ParamMapper('user_data', 'UserData', 'userData', value_wrapper), |
| 1899 |
] |
| 1900 |
|
| 1901 |
for mapping in param_mappings: |
| 1902 |
if module.params.get(mapping.param_key) is None: |
| 1903 |
continue |
| 1904 |
if mapping.instance_key in skip: |
| 1905 |
continue |
| 1906 |
|
| 1907 |
try: |
| 1908 |
value = describe_instance_attribute(client, instance_id=id_, attribute=mapping.attribute_name) |
| 1909 |
except AnsibleEC2Error as e: |
| 1910 |
module.fail_json_aws(e, msg=f"Could not describe attribute {mapping.attribute_name} for instance {id_}") |
| 1911 |
if value[mapping.instance_key]["Value"] != module.params.get(mapping.param_key): |
| 1912 |
arguments = dict( |
| 1913 |
InstanceId=instance["InstanceId"], |
| 1914 |
# Attribute=mapping.attribute_name, |
| 1915 |
) |
| 1916 |
arguments[mapping.instance_key] = mapping.add_value(module.params.get(mapping.param_key)) |
| 1917 |
changes_to_apply.append(arguments) |
| 1918 |
|
| 1919 |
network_interfaces = module.params.get("network_interfaces") |
| 1920 |
if not network_interfaces and module.params.get("network") and not module.params["network"].get("interfaces"): |
| 1921 |
network_interfaces = [module.params["network"]] |
| 1922 |
if network_interfaces or module.params.get("security_groups") or module.params.get("security_group"): |
| 1923 |
if len(network_interfaces or []) > 1 or len(instance["NetworkInterfaces"]) > 1: |
| 1924 |
module.warn("Skipping group modification because instance contains mutiple network interfaces.") |
| 1925 |
else: |
| 1926 |
try: |
| 1927 |
value = describe_instance_attribute(client, instance_id=id_, attribute="groupSet") |
| 1928 |
except AnsibleEC2Error as e: |
| 1929 |
module.fail_json_aws(e, msg=f"Could not describe attribute groupSet for instance {id_}") |
| 1930 |
|
| 1931 |
# Read interface subnet |
| 1932 |
subnet_id = None |
| 1933 |
groups = None |
| 1934 |
if network_interfaces: |
| 1935 |
subnet_id = network_interfaces[0].get("subnet_id") |
| 1936 |
groups = network_interfaces[0].get("groups") |
| 1937 |
if not subnet_id and module.params.get("vpc_subnet_id"): |
| 1938 |
subnet_id = module.params.get("vpc_subnet_id") |
| 1939 |
elif module.params.get("vpc_subnet_id"): |
| 1940 |
subnet_id = module.params.get("vpc_subnet_id") |
| 1941 |
else: |
| 1942 |
subnet_id = describe_default_subnet(client, module, use_availability_zone=False) |
| 1943 |
|
| 1944 |
# Read groups |
| 1945 |
groups = groups or module.params.get("security_groups") or module.params.get("security_group") |
| 1946 |
if groups: |
| 1947 |
groups = discover_security_groups(client, module, groups=groups, subnet_id=subnet_id) |
| 1948 |
instance_groups = [g["GroupId"] for g in value["Groups"]] |
| 1949 |
if set(instance_groups) != set(groups): |
| 1950 |
changes_to_apply.append(dict(Groups=groups, InstanceId=instance["InstanceId"])) |
| 1951 |
|
| 1952 |
source_dest_check = module.params.get("source_dest_check") |
| 1953 |
if source_dest_check is None: |
| 1954 |
source_dest_check = (module.params.get("network") or {}).get("source_dest_check") |
| 1955 |
# network.source_dest_check is nested, so needs to be treated separately |
| 1956 |
if source_dest_check is not None: |
| 1957 |
source_dest_check = bool(source_dest_check) |
| 1958 |
if source_dest_check is not None and instance["SourceDestCheck"] != source_dest_check: |
| 1959 |
changes_to_apply.append( |
| 1960 |
dict( |
| 1961 |
InstanceId=instance["InstanceId"], |
| 1962 |
SourceDestCheck={"Value": source_dest_check}, |
| 1963 |
) |
| 1964 |
) |
| 1965 |
|
| 1966 |
return changes_to_apply |
| 1967 |
|
| 1968 |
|
| 1969 |
def change_instance_metadata_options(client, module: AnsibleAWSModule, instance: Dict[str, str]) -> bool: |
| 1970 |
metadata_options_to_apply = module.params.get("metadata_options") |
| 1971 |
|
| 1972 |
if metadata_options_to_apply is None: |
| 1973 |
return False |
| 1974 |
|
| 1975 |
existing_metadata_options = camel_dict_to_snake_dict(instance.get("MetadataOptions")) |
| 1976 |
|
| 1977 |
changes_to_apply = { |
| 1978 |
key: metadata_options_to_apply[key] |
| 1979 |
for key in set(existing_metadata_options) & set(metadata_options_to_apply) |
| 1980 |
if existing_metadata_options[key] != metadata_options_to_apply[key] |
| 1981 |
} |
| 1982 |
|
| 1983 |
if not changes_to_apply: |
| 1984 |
return False |
| 1985 |
|
| 1986 |
request_args = { |
| 1987 |
"HttpTokens": changes_to_apply.get("http_tokens") or existing_metadata_options.get("http_tokens"), |
| 1988 |
"HttpPutResponseHopLimit": changes_to_apply.get("http_put_response_hop_limit") |
| 1989 |
or existing_metadata_options.get("http_put_response_hop_limit"), |
| 1990 |
"HttpEndpoint": changes_to_apply.get("http_endpoint") or existing_metadata_options.get("http_endpoint"), |
| 1991 |
"HttpProtocolIpv6": changes_to_apply.get("http_protocol_ipv6") |
| 1992 |
or existing_metadata_options.get("http_protocol_ipv6"), |
| 1993 |
"InstanceMetadataTags": changes_to_apply.get("instance_metadata_tags") |
| 1994 |
or existing_metadata_options.get("instance_metadata_tags"), |
| 1995 |
} |
| 1996 |
|
| 1997 |
changed = True |
| 1998 |
if not module.check_mode: |
| 1999 |
try: |
| 2000 |
modify_instance_metadata_options(client, instance["InstanceId"], **request_args) |
| 2001 |
except AnsibleEC2Error as e: |
| 2002 |
module.fail_json_aws( |
| 2003 |
e, msg=f"Failed to update instance metadata options for instance ID: {instance['InstanceId']}" |
| 2004 |
) |
| 2005 |
return changed |
| 2006 |
|
| 2007 |
|
| 2008 |
def change_network_attachments(client, module: AnsibleAWSModule, instance: Dict[str, Any]) -> bool: |
| 2009 |
""" |
| 2010 |
Attach Network interfaces to the instance |
| 2011 |
Parameters: |
| 2012 |
client: AWS API client. |
| 2013 |
module: The ansible AWS module. |
| 2014 |
instance: A dictionnary describing the instance. |
| 2015 |
Returns: |
| 2016 |
A boolean set to True if changes have been done. |
| 2017 |
""" |
| 2018 |
new_enis = [ |
| 2019 |
eni.get("id") |
| 2020 |
for eni in module.params.get("network_interfaces_ids") |
| 2021 |
or (module.params.get("network") or {}).get("interfaces") |
| 2022 |
or [] |
| 2023 |
] |
| 2024 |
if not new_enis: |
| 2025 |
return False |
| 2026 |
|
| 2027 |
new_ids = map(lambda x: x.get("id") if isinstance(x, dict) else x, new_enis) |
| 2028 |
old_ids = [inty["NetworkInterfaceId"] for inty in instance["NetworkInterfaces"]] |
| 2029 |
to_attach = set(new_ids) - set(old_ids) |
| 2030 |
if not module.check_mode: |
| 2031 |
for idx, eni in enumerate(new_enis): |
| 2032 |
eni_id = eni |
| 2033 |
device_index = idx |
| 2034 |
if isinstance(eni, dict): |
| 2035 |
eni_id = eni.get("id") |
| 2036 |
device_index = eni.get("device_index") or idx |
| 2037 |
if eni_id in to_attach: |
| 2038 |
try: |
| 2039 |
attach_network_interface( |
| 2040 |
client, |
| 2041 |
DeviceIndex=device_index, |
| 2042 |
InstanceId=instance["InstanceId"], |
| 2043 |
NetworkInterfaceId=eni_id, |
| 2044 |
) |
| 2045 |
except AnsibleEC2Error as e: |
| 2046 |
module.fail_json_aws( |
| 2047 |
e, msg=f"Could not attach interface {eni_id} to instance {instance['InstanceId']}" |
| 2048 |
) |
| 2049 |
return bool(to_attach) |
| 2050 |
|
| 2051 |
|
| 2052 |
def find_instances( |
| 2053 |
client, module: AnsibleAWSModule, ids: Optional[List[str]] = None, filters: Optional[Dict[str, Any]] = None |
| 2054 |
) -> List[Dict[str, Any]]: |
| 2055 |
sanitized_filters = dict() |
| 2056 |
|
| 2057 |
if ids: |
| 2058 |
params = dict(InstanceIds=ids) |
| 2059 |
elif filters is None: |
| 2060 |
module.fail_json(msg="No filters provided when they were required") |
| 2061 |
else: |
| 2062 |
for key in list(filters.keys()): |
| 2063 |
if not key.startswith("tag:"): |
| 2064 |
sanitized_filters[key.replace("_", "-")] = filters[key] |
| 2065 |
else: |
| 2066 |
sanitized_filters[key] = filters[key] |
| 2067 |
params = dict(Filters=ansible_dict_to_boto3_filter_list(sanitized_filters)) |
| 2068 |
|
| 2069 |
instances = [] |
| 2070 |
for reservation in describe_instances(client, **params): |
| 2071 |
instances.extend(reservation["Instances"]) |
| 2072 |
return instances |
| 2073 |
|
| 2074 |
|
| 2075 |
def get_default_vpc(client, module: AnsibleAWSModule) -> Optional[Dict[str, Any]]: |
| 2076 |
try: |
| 2077 |
vpcs = describe_vpcs(client, Filters=ansible_dict_to_boto3_filter_list({"isDefault": "true"})) |
| 2078 |
except AnsibleEC2Error as e: |
| 2079 |
module.fail_json_aws(e, msg="Could not describe default VPC") |
| 2080 |
return vpcs[0] if vpcs else None |
| 2081 |
|
| 2082 |
|
| 2083 |
def get_default_subnet( |
| 2084 |
client, module: AnsibleAWSModule, vpc: Dict[str, Any], availability_zone=None |
| 2085 |
) -> Optional[Dict[str, Any]]: |
| 2086 |
try: |
| 2087 |
subnets = describe_subnets( |
| 2088 |
client, |
| 2089 |
Filters=ansible_dict_to_boto3_filter_list( |
| 2090 |
{ |
| 2091 |
"vpc-id": vpc["VpcId"], |
| 2092 |
"state": "available", |
| 2093 |
"default-for-az": "true", |
| 2094 |
} |
| 2095 |
), |
| 2096 |
) |
| 2097 |
except AnsibleEC2Error as e: |
| 2098 |
module.fail_json_aws(e, msg=f"Could not describe default subnets for VPC {vpc['VpcId']}") |
| 2099 |
result = None |
| 2100 |
if subnets: |
| 2101 |
if availability_zone is not None: |
| 2102 |
subs_by_az = dict((subnet["AvailabilityZone"], subnet) for subnet in subnets) |
| 2103 |
if availability_zone in subs_by_az: |
| 2104 |
return subs_by_az[availability_zone] |
| 2105 |
|
| 2106 |
# to have a deterministic sorting order, we sort by AZ so we'll always pick the `a` subnet first |
| 2107 |
# there can only be one default-for-az subnet per AZ, so the AZ key is always unique in this list |
| 2108 |
by_az = sorted(subnets, key=lambda s: s["AvailabilityZone"]) |
| 2109 |
result = by_az[0] |
| 2110 |
return result |
| 2111 |
|
| 2112 |
|
| 2113 |
def ensure_instance_state( |
| 2114 |
client, module: AnsibleAWSModule, desired_module_state: str, filters: Optional[Dict[str, Any]] |
| 2115 |
) -> Dict[str, Any]: |
| 2116 |
""" |
| 2117 |
Sets return keys depending on the desired instance state |
| 2118 |
""" |
| 2119 |
results = dict() |
| 2120 |
changed = False |
| 2121 |
if desired_module_state in ("running", "started"): |
| 2122 |
_changed, failed, instances, failure_reason = change_instance_state( |
| 2123 |
client, module, filters=filters, desired_module_state=desired_module_state |
| 2124 |
) |
| 2125 |
changed |= bool(len(_changed)) |
| 2126 |
|
| 2127 |
if failed: |
| 2128 |
module.fail_json( |
| 2129 |
msg=f"Unable to start instances: {failure_reason}", |
| 2130 |
reboot_success=list(_changed), |
| 2131 |
reboot_failed=failed, |
| 2132 |
) |
| 2133 |
|
| 2134 |
results = dict( |
| 2135 |
msg="Instances started", |
| 2136 |
start_success=list(_changed), |
| 2137 |
start_failed=[], |
| 2138 |
# Avoid breaking things 'reboot' is wrong but used to be returned |
| 2139 |
reboot_success=list(_changed), |
| 2140 |
reboot_failed=[], |
| 2141 |
changed=changed, |
| 2142 |
instances=[pretty_instance(i) for i in instances], |
| 2143 |
) |
| 2144 |
elif desired_module_state in ("restarted", "rebooted"): |
| 2145 |
# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-reboot.html |
| 2146 |
# The Ansible behaviour of issuing a stop/start has a minor impact on user billing |
| 2147 |
# This will need to be changelogged if we ever change to client.reboot_instance |
| 2148 |
_changed, failed, instances, failure_reason = change_instance_state( |
| 2149 |
client, |
| 2150 |
module, |
| 2151 |
filters=filters, |
| 2152 |
desired_module_state="stopped", |
| 2153 |
) |
| 2154 |
|
| 2155 |
if failed: |
| 2156 |
module.fail_json( |
| 2157 |
msg=f"Unable to stop instances: {failure_reason}", |
| 2158 |
stop_success=list(_changed), |
| 2159 |
stop_failed=failed, |
| 2160 |
) |
| 2161 |
|
| 2162 |
changed |= bool(len(_changed)) |
| 2163 |
_changed, failed, instances, failure_reason = change_instance_state( |
| 2164 |
client, |
| 2165 |
module, |
| 2166 |
filters=filters, |
| 2167 |
desired_module_state=desired_module_state, |
| 2168 |
) |
| 2169 |
changed |= bool(len(_changed)) |
| 2170 |
|
| 2171 |
if failed: |
| 2172 |
module.fail_json( |
| 2173 |
msg=f"Unable to restart instances: {failure_reason}", |
| 2174 |
reboot_success=list(_changed), |
| 2175 |
reboot_failed=failed, |
| 2176 |
) |
| 2177 |
|
| 2178 |
results = dict( |
| 2179 |
msg="Instances restarted", |
| 2180 |
reboot_success=list(_changed), |
| 2181 |
changed=changed, |
| 2182 |
reboot_failed=[], |
| 2183 |
instances=[pretty_instance(i) for i in instances], |
| 2184 |
) |
| 2185 |
elif desired_module_state in ("stopped",): |
| 2186 |
_changed, failed, instances, failure_reason = change_instance_state( |
| 2187 |
client, |
| 2188 |
module, |
| 2189 |
filters=filters, |
| 2190 |
desired_module_state=desired_module_state, |
| 2191 |
) |
| 2192 |
changed |= bool(len(_changed)) |
| 2193 |
|
| 2194 |
if failed: |
| 2195 |
module.fail_json( |
| 2196 |
msg=f"Unable to stop instances: {failure_reason}", |
| 2197 |
stop_success=list(_changed), |
| 2198 |
stop_failed=failed, |
| 2199 |
) |
| 2200 |
|
| 2201 |
results = dict( |
| 2202 |
msg="Instances stopped", |
| 2203 |
stop_success=list(_changed), |
| 2204 |
changed=changed, |
| 2205 |
stop_failed=[], |
| 2206 |
instances=[pretty_instance(i) for i in instances], |
| 2207 |
) |
| 2208 |
elif desired_module_state in ("absent", "terminated"): |
| 2209 |
terminated, terminate_failed, instances, failure_reason = change_instance_state( |
| 2210 |
client, |
| 2211 |
module, |
| 2212 |
filters=filters, |
| 2213 |
desired_module_state=desired_module_state, |
| 2214 |
) |
| 2215 |
|
| 2216 |
if terminate_failed: |
| 2217 |
module.fail_json( |
| 2218 |
msg=f"Unable to terminate instances: {failure_reason}", |
| 2219 |
terminate_success=list(terminated), |
| 2220 |
terminate_failed=terminate_failed, |
| 2221 |
) |
| 2222 |
results = dict( |
| 2223 |
msg="Instances terminated", |
| 2224 |
terminate_success=list(terminated), |
| 2225 |
changed=bool(len(terminated)), |
| 2226 |
terminate_failed=[], |
| 2227 |
instances=[pretty_instance(i) for i in instances], |
| 2228 |
) |
| 2229 |
return results |
| 2230 |
|
| 2231 |
|
| 2232 |
def change_instance_state( |
| 2233 |
client, module: AnsibleAWSModule, filters: Optional[Dict[str, Any]], desired_module_state: str |
| 2234 |
) -> Tuple[Set[str], List[str], Optional[List[Dict[str, Any]]], str]: |
| 2235 |
# Map ansible state to ec2 state |
| 2236 |
ec2_instance_states = { |
| 2237 |
"present": "running", |
| 2238 |
"started": "running", |
| 2239 |
"running": "running", |
| 2240 |
"stopped": "stopped", |
| 2241 |
"restarted": "running", |
| 2242 |
"rebooted": "running", |
| 2243 |
"terminated": "terminated", |
| 2244 |
"absent": "terminated", |
| 2245 |
} |
| 2246 |
desired_ec2_state = ec2_instance_states[desired_module_state] |
| 2247 |
changed = set() |
| 2248 |
instances = find_instances(client, module, filters=filters) |
| 2249 |
to_change = set(i["InstanceId"] for i in instances if i["State"]["Name"] != desired_ec2_state) |
| 2250 |
unchanged = set() |
| 2251 |
failure_reason = "" |
| 2252 |
|
| 2253 |
for inst in instances: |
| 2254 |
try: |
| 2255 |
if desired_ec2_state == "terminated": |
| 2256 |
# Before terminating an instance we need for them to leave |
| 2257 |
# 'pending' or 'stopping' (if they're in those states) |
| 2258 |
if inst["State"]["Name"] == "stopping": |
| 2259 |
await_instances( |
| 2260 |
client, module, [inst["InstanceId"]], desired_module_state="stopped", force_wait=True |
| 2261 |
) |
| 2262 |
elif inst["State"]["Name"] == "pending": |
| 2263 |
await_instances( |
| 2264 |
client, module, [inst["InstanceId"]], desired_module_state="running", force_wait=True |
| 2265 |
) |
| 2266 |
|
| 2267 |
if module.check_mode: |
| 2268 |
changed.add(inst["InstanceId"]) |
| 2269 |
continue |
| 2270 |
|
| 2271 |
# TODO use a client-token to prevent double-sends of these start/stop/terminate commands |
| 2272 |
# https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html |
| 2273 |
resp = terminate_instances(client, instance_ids=[inst["InstanceId"]]) |
| 2274 |
changed.update([i["InstanceId"] for i in resp]) |
| 2275 |
if desired_ec2_state == "stopped": |
| 2276 |
# Before stopping an instance we need for them to leave |
| 2277 |
# 'pending' |
| 2278 |
if inst["State"]["Name"] == "pending": |
| 2279 |
await_instances( |
| 2280 |
client, module, [inst["InstanceId"]], desired_module_state="running", force_wait=True |
| 2281 |
) |
| 2282 |
# Already moving to the relevant state |
| 2283 |
elif inst["State"]["Name"] in ("stopping", "stopped"): |
| 2284 |
unchanged.add(inst["InstanceId"]) |
| 2285 |
continue |
| 2286 |
|
| 2287 |
if module.check_mode: |
| 2288 |
changed.add(inst["InstanceId"]) |
| 2289 |
continue |
| 2290 |
resp = stop_instances(client, instance_ids=[inst["InstanceId"]]) |
| 2291 |
changed.update([i["InstanceId"] for i in resp]) |
| 2292 |
if desired_ec2_state == "running": |
| 2293 |
if inst["State"]["Name"] in ("pending", "running"): |
| 2294 |
unchanged.add(inst["InstanceId"]) |
| 2295 |
continue |
| 2296 |
if inst["State"]["Name"] == "stopping": |
| 2297 |
await_instances( |
| 2298 |
client, module, [inst["InstanceId"]], desired_module_state="stopped", force_wait=True |
| 2299 |
) |
| 2300 |
|
| 2301 |
if module.check_mode: |
| 2302 |
changed.add(inst["InstanceId"]) |
| 2303 |
continue |
| 2304 |
|
| 2305 |
resp = start_instances(client, instance_ids=[inst["InstanceId"]]) |
| 2306 |
changed.update([i["InstanceId"] for i in resp]) |
| 2307 |
except AnsibleEC2Error as e: |
| 2308 |
failure_reason = str(e) |
| 2309 |
|
| 2310 |
if changed: |
| 2311 |
await_instances(client, module, ids=list(changed) + list(unchanged), desired_module_state=desired_module_state) |
| 2312 |
|
| 2313 |
change_failed = list(to_change - changed) |
| 2314 |
|
| 2315 |
if instances: |
| 2316 |
instances = find_instances(client, module, ids=list(i["InstanceId"] for i in instances)) |
| 2317 |
return changed, change_failed, instances, failure_reason |
| 2318 |
|
| 2319 |
|
| 2320 |
def pretty_instance(i): |
| 2321 |
instance = camel_dict_to_snake_dict(i, ignore_list=["Tags"]) |
| 2322 |
instance["tags"] = boto3_tag_list_to_ansible_dict(i.get("Tags", {})) |
| 2323 |
return instance |
| 2324 |
|
| 2325 |
|
| 2326 |
def modify_instance_type( |
| 2327 |
client, |
| 2328 |
module: AnsibleAWSModule, |
| 2329 |
state: str, |
| 2330 |
instance_id: str, |
| 2331 |
changes: Dict[str, Dict[str, str]], |
| 2332 |
) -> None: |
| 2333 |
filters = { |
| 2334 |
"instance-id": [instance_id], |
| 2335 |
} |
| 2336 |
# Ensure that the instance is stopped before changing the instance type |
| 2337 |
ensure_instance_state(client, module, "stopped", filters) |
| 2338 |
|
| 2339 |
# force wait for the instance to be stopped |
| 2340 |
await_instances(client, module, ids=[instance_id], desired_module_state="stopped", force_wait=True) |
| 2341 |
|
| 2342 |
# Modify instance type |
| 2343 |
modify_instance_attribute(client, instance_id=instance_id, **changes) |
| 2344 |
|
| 2345 |
# Ensure instance state |
| 2346 |
desired_module_state = "running" if state == "present" else state |
| 2347 |
ensure_instance_state(client, module, desired_module_state, filters) |
| 2348 |
|
| 2349 |
|
| 2350 |
def modify_ec2_instance_attribute(client, module: AnsibleAWSModule, state: str, changes: List[Dict[str, Any]]) -> None: |
| 2351 |
if not module.check_mode: |
| 2352 |
for c in changes: |
| 2353 |
instance_id = c.pop("InstanceId") |
| 2354 |
try: |
| 2355 |
if "InstanceType" in c: |
| 2356 |
modify_instance_type(client, module, state, instance_id, c) |
| 2357 |
else: |
| 2358 |
modify_instance_attribute(client, instance_id=instance_id, **c) |
| 2359 |
except AnsibleEC2Error as e: |
| 2360 |
module.fail_json_aws(e, msg=f"Could not apply change {str(c)} to existing instance.") |
| 2361 |
|
| 2362 |
|
| 2363 |
def handle_existing( |
| 2364 |
client, |
| 2365 |
module: AnsibleAWSModule, |
| 2366 |
existing_matches: List[Dict[str, Any]], |
| 2367 |
state: str, |
| 2368 |
filters: Optional[Dict[str, Any]], |
| 2369 |
) -> Dict[str, Any]: |
| 2370 |
tags = module.params.get("tags") |
| 2371 |
purge_tags = module.params.get("purge_tags") |
| 2372 |
name = module.params.get("name") |
| 2373 |
|
| 2374 |
# Name is a tag rather than a direct parameter, we need to inject 'Name' |
| 2375 |
# into tags, but since tags isn't explicitly passed we'll treat it not being |
| 2376 |
# set as purge_tags == False |
| 2377 |
if name: |
| 2378 |
if tags is None: |
| 2379 |
purge_tags = False |
| 2380 |
tags = {} |
| 2381 |
tags.update({"Name": name}) |
| 2382 |
|
| 2383 |
changed = False |
| 2384 |
all_changes = list() |
| 2385 |
|
| 2386 |
for instance in existing_matches: |
| 2387 |
changed |= ensure_ec2_tags(client, module, instance["InstanceId"], tags=tags, purge_tags=purge_tags) |
| 2388 |
|
| 2389 |
changed |= change_instance_metadata_options(client, module, instance) |
| 2390 |
|
| 2391 |
changes = diff_instance_and_params(client, module, instance) |
| 2392 |
# modify instance attributes |
| 2393 |
modify_ec2_instance_attribute(client, module, state, changes) |
| 2394 |
|
| 2395 |
all_changes.extend(changes) |
| 2396 |
changed |= bool(changes) |
| 2397 |
changed |= add_or_update_instance_profile(client, module, instance, module.params.get("iam_instance_profile")) |
| 2398 |
changed |= change_network_attachments(client, module, instance) |
| 2399 |
|
| 2400 |
altered = find_instances(client, module, ids=[i["InstanceId"] for i in existing_matches]) |
| 2401 |
alter_config_result = dict( |
| 2402 |
changed=changed, |
| 2403 |
instances=[pretty_instance(i) for i in altered], |
| 2404 |
instance_ids=[i["InstanceId"] for i in altered], |
| 2405 |
changes=changes, |
| 2406 |
) |
| 2407 |
|
| 2408 |
state_results = ensure_instance_state(client, module, state, filters) |
| 2409 |
alter_config_result["changed"] |= state_results.pop("changed", False) |
| 2410 |
result = {**state_results, **alter_config_result} |
| 2411 |
|
| 2412 |
return result |
| 2413 |
|
| 2414 |
|
| 2415 |
def enforce_count( |
| 2416 |
client, |
| 2417 |
module: AnsibleAWSModule, |
| 2418 |
existing_matches: List[Dict[str, Any]], |
| 2419 |
desired_module_state: str, |
| 2420 |
filters: Optional[Dict[str, Any]], |
| 2421 |
) -> Dict[str, Any]: |
| 2422 |
exact_count = module.params.get("exact_count") |
| 2423 |
|
| 2424 |
current_count = len(existing_matches) |
| 2425 |
if current_count == exact_count: |
| 2426 |
if desired_module_state not in ("absent", "terminated"): |
| 2427 |
results = handle_existing(client, module, existing_matches, desired_module_state, filters) |
| 2428 |
else: |
| 2429 |
results = ensure_instance_state(client, module, desired_module_state, filters) |
| 2430 |
if results["changed"]: |
| 2431 |
return results |
| 2432 |
return dict( |
| 2433 |
changed=False, |
| 2434 |
instances=[pretty_instance(i) for i in existing_matches], |
| 2435 |
instance_ids=[i["InstanceId"] for i in existing_matches], |
| 2436 |
msg=f"{exact_count} instances already {desired_module_state}, nothing to do.", |
| 2437 |
) |
| 2438 |
|
| 2439 |
if current_count < exact_count: |
| 2440 |
# launch instances |
| 2441 |
results = ensure_present( |
| 2442 |
client, |
| 2443 |
module, |
| 2444 |
existing_matches=existing_matches, |
| 2445 |
desired_module_state=desired_module_state, |
| 2446 |
current_count=current_count, |
| 2447 |
) |
| 2448 |
else: |
| 2449 |
# terminate instances |
| 2450 |
to_terminate = current_count - exact_count |
| 2451 |
# sort the instances from least recent to most recent based on launch time |
| 2452 |
existing_matches = sorted(existing_matches, key=lambda inst: inst["LaunchTime"]) |
| 2453 |
# get the instance ids of instances with the count tag on them |
| 2454 |
all_instance_ids = [x["InstanceId"] for x in existing_matches] |
| 2455 |
terminate_ids = all_instance_ids[0:to_terminate] |
| 2456 |
results = dict( |
| 2457 |
changed=True, |
| 2458 |
terminated_ids=terminate_ids, |
| 2459 |
instance_ids=all_instance_ids, |
| 2460 |
msg=f"Would have terminated following instances if not in check mode {terminate_ids}", |
| 2461 |
) |
| 2462 |
if not module.check_mode: |
| 2463 |
# terminate instances |
| 2464 |
try: |
| 2465 |
terminate_instances(client, terminate_ids) |
| 2466 |
except AnsibleAWSError as e: |
| 2467 |
module.fail_json(e, msg="Unable to terminate instances") |
| 2468 |
await_instances(client, module, terminate_ids, desired_module_state="terminated", force_wait=True) |
| 2469 |
|
| 2470 |
# include data for all matched instances in addition to the list of terminations |
| 2471 |
# allowing for recovery of metadata from the destructive operation |
| 2472 |
results = dict( |
| 2473 |
changed=True, |
| 2474 |
msg="Successfully terminated instances.", |
| 2475 |
terminated_ids=terminate_ids, |
| 2476 |
instance_ids=all_instance_ids, |
| 2477 |
instances=existing_matches, |
| 2478 |
) |
| 2479 |
|
| 2480 |
if not module.check_mode: |
| 2481 |
# Find instances |
| 2482 |
existing_matches = find_instances(client, module, filters=filters) |
| 2483 |
# Update instance attributes |
| 2484 |
updated_results = handle_existing(client, module, existing_matches, desired_module_state, filters) |
| 2485 |
if updated_results["changed"]: |
| 2486 |
results = updated_results |
| 2487 |
return results |
| 2488 |
|
| 2489 |
|
| 2490 |
def ensure_present( |
| 2491 |
client, |
| 2492 |
module: AnsibleAWSModule, |
| 2493 |
existing_matches: Optional[List[Dict[str, Any]]], |
| 2494 |
desired_module_state: str, |
| 2495 |
current_count: Optional[int] = None, |
| 2496 |
) -> Dict[str, Any]: |
| 2497 |
tags = dict(module.params.get("tags") or {}) |
| 2498 |
name = module.params.get("name") |
| 2499 |
if name: |
| 2500 |
tags["Name"] = name |
| 2501 |
|
| 2502 |
instance_spec = build_run_instance_spec(client, module, current_count) |
| 2503 |
# If check mode is enabled,suspend 'ensure function'. |
| 2504 |
if module.check_mode: |
| 2505 |
if existing_matches: |
| 2506 |
instance_ids = [x["InstanceId"] for x in existing_matches] |
| 2507 |
return dict( |
| 2508 |
changed=True, |
| 2509 |
instance_ids=instance_ids, |
| 2510 |
instances=existing_matches, |
| 2511 |
spec=instance_spec, |
| 2512 |
msg="Would have launched instances if not in check_mode.", |
| 2513 |
) |
| 2514 |
else: |
| 2515 |
return dict( |
| 2516 |
changed=True, |
| 2517 |
spec=instance_spec, |
| 2518 |
msg="Would have launched instances if not in check_mode.", |
| 2519 |
) |
| 2520 |
instance_response = run_instances(client, **instance_spec) |
| 2521 |
instances = instance_response["Instances"] |
| 2522 |
instance_ids = [i["InstanceId"] for i in instances] |
| 2523 |
|
| 2524 |
# Wait for instances to exist in the EC2 API before |
| 2525 |
# attempting to modify them |
| 2526 |
await_instances(client, module, instance_ids, desired_module_state="present", force_wait=True) |
| 2527 |
|
| 2528 |
for ins in instances: |
| 2529 |
# Wait for instances to exist (don't check state) |
| 2530 |
try: |
| 2531 |
describe_instance_status( |
| 2532 |
client, |
| 2533 |
InstanceIds=[ins["InstanceId"]], |
| 2534 |
IncludeAllInstances=True, |
| 2535 |
) |
| 2536 |
except AnsibleEC2Error as e: |
| 2537 |
module.fail_json_aws(e, msg="Failed to fetch status of new EC2 instance") |
| 2538 |
changes = diff_instance_and_params(client, module, ins, skip=["UserData", "EbsOptimized"]) |
| 2539 |
# modify instance attributes |
| 2540 |
modify_ec2_instance_attribute(client, module, desired_module_state, changes) |
| 2541 |
|
| 2542 |
if existing_matches: |
| 2543 |
# If we came from enforce_count, create a second list to distinguish |
| 2544 |
# between existing and new instances when returning the entire cohort |
| 2545 |
all_instance_ids = [x["InstanceId"] for x in existing_matches] + instance_ids |
| 2546 |
if not module.params.get("wait"): |
| 2547 |
if existing_matches: |
| 2548 |
return dict( |
| 2549 |
changed=True, |
| 2550 |
changed_ids=instance_ids, |
| 2551 |
instance_ids=all_instance_ids, |
| 2552 |
spec=instance_spec, |
| 2553 |
) |
| 2554 |
else: |
| 2555 |
return dict( |
| 2556 |
changed=True, |
| 2557 |
instance_ids=instance_ids, |
| 2558 |
spec=instance_spec, |
| 2559 |
) |
| 2560 |
await_instances(client, module, instance_ids, desired_module_state=desired_module_state) |
| 2561 |
instances = find_instances(client, module, ids=instance_ids) |
| 2562 |
|
| 2563 |
if existing_matches: |
| 2564 |
all_instances = existing_matches + instances |
| 2565 |
return dict( |
| 2566 |
changed=True, |
| 2567 |
changed_ids=instance_ids, |
| 2568 |
instance_ids=all_instance_ids, |
| 2569 |
instances=[pretty_instance(i) for i in all_instances], |
| 2570 |
spec=instance_spec, |
| 2571 |
) |
| 2572 |
else: |
| 2573 |
return dict( |
| 2574 |
changed=True, |
| 2575 |
instance_ids=instance_ids, |
| 2576 |
instances=[pretty_instance(i) for i in instances], |
| 2577 |
spec=instance_spec, |
| 2578 |
) |
| 2579 |
|
| 2580 |
|
| 2581 |
def run_instances(client, **instance_spec: Dict[str, Any]) -> Dict[str, Any]: |
| 2582 |
try: |
| 2583 |
return run_ec2_instances(client, **instance_spec) |
| 2584 |
except is_ansible_aws_error_message("Invalid IAM Instance Profile ARN"): |
| 2585 |
# If the instance profile has just been created, it takes some time to be visible by ec2 |
| 2586 |
# So we wait 10 second and retry the run_instances |
| 2587 |
time.sleep(10) |
| 2588 |
return run_ec2_instances(client, **instance_spec) |
| 2589 |
|
| 2590 |
|
| 2591 |
def describe_default_subnet(client, module: AnsibleAWSModule, use_availability_zone: bool = True) -> str: |
| 2592 |
""" |
| 2593 |
Read default subnet associated to the AWS account |
| 2594 |
Parameters: |
| 2595 |
client: AWS API client |
| 2596 |
module: The Ansible AWS module |
| 2597 |
use_availability_zone: Whether to use availability zone to find the default subnet. |
| 2598 |
Returns: |
| 2599 |
The default subnet id. |
| 2600 |
""" |
| 2601 |
default_vpc = get_default_vpc(client, module) |
| 2602 |
if not default_vpc: |
| 2603 |
module.fail_json( |
| 2604 |
msg=("No default subnet could be found - you must include a VPC subnet ID (vpc_subnet_id parameter).") |
| 2605 |
) |
| 2606 |
availability_zone = module.params.get("availability_zone") if use_availability_zone else None |
| 2607 |
return get_default_subnet(client, module, default_vpc, availability_zone)["SubnetId"] |
| 2608 |
|
| 2609 |
|
| 2610 |
def build_network_filters(client, module: AnsibleAWSModule) -> Dict[str, List[str]]: |
| 2611 |
""" |
| 2612 |
Create Network filters for the DescribeInstances API |
| 2613 |
Returns: |
| 2614 |
Dictionnary of network filters |
| 2615 |
""" |
| 2616 |
filters = {} |
| 2617 |
network_interfaces_ids = module.params.get("network_interfaces_ids") or (module.params.get("network") or {}).get( |
| 2618 |
"interfaces" |
| 2619 |
) |
| 2620 |
if module.params.get("vpc_subnet_id"): |
| 2621 |
filters["subnet-id"] = [module.params.get("vpc_subnet_id")] |
| 2622 |
elif network_interfaces_ids: |
| 2623 |
filters["network-interface.network-interface-id"] = [ |
| 2624 |
eni["id"] if isinstance(eni, dict) else eni for eni in network_interfaces_ids |
| 2625 |
] |
| 2626 |
else: |
| 2627 |
filters["subnet-id"] = describe_default_subnet(client, module) |
| 2628 |
return filters |
| 2629 |
|
| 2630 |
|
| 2631 |
def build_filters(client, module: AnsibleAWSModule) -> Dict[str, Any]: |
| 2632 |
# all states except shutting-down and terminated |
| 2633 |
instance_state_names = ["pending", "running", "stopping", "stopped"] |
| 2634 |
filters = {} |
| 2635 |
instance_ids = module.params.get("instance_ids") |
| 2636 |
if isinstance(instance_ids, str): |
| 2637 |
filters = {"instance-id": [instance_ids], "instance-state-name": instance_state_names} |
| 2638 |
elif isinstance(instance_ids, list) and len(instance_ids): |
| 2639 |
filters = {"instance-id": instance_ids, "instance-state-name": instance_state_names} |
| 2640 |
else: |
| 2641 |
if not module.params.get("launch_template"): |
| 2642 |
# Network filters |
| 2643 |
filters.update(build_network_filters(client, module)) |
| 2644 |
if module.params.get("name"): |
| 2645 |
filters["tag:Name"] = [module.params.get("name")] |
| 2646 |
elif module.params.get("tags"): |
| 2647 |
name_tag = module.params.get("tags").get("Name", None) |
| 2648 |
if name_tag: |
| 2649 |
filters["tag:Name"] = [name_tag] |
| 2650 |
|
| 2651 |
if module.params.get("image_id"): |
| 2652 |
filters["image-id"] = [module.params.get("image_id")] |
| 2653 |
elif (module.params.get("image") or {}).get("id"): |
| 2654 |
filters["image-id"] = [module.params.get("image", {}).get("id")] |
| 2655 |
|
| 2656 |
if filters: |
| 2657 |
# add the instance state filter if any filter key was provided |
| 2658 |
filters["instance-state-name"] = instance_state_names |
| 2659 |
return filters |
| 2660 |
|
| 2661 |
|
| 2662 |
def main(): |
| 2663 |
argument_spec = dict( |
| 2664 |
state=dict( |
| 2665 |
default="present", |
| 2666 |
choices=["present", "started", "running", "stopped", "restarted", "rebooted", "terminated", "absent"], |
| 2667 |
), |
| 2668 |
wait=dict(default=True, type="bool"), |
| 2669 |
wait_timeout=dict(default=600, type="int"), |
| 2670 |
count=dict(type="int"), |
| 2671 |
exact_count=dict(type="int"), |
| 2672 |
image=dict( |
| 2673 |
type="dict", |
| 2674 |
options=dict( |
| 2675 |
id=dict(type="str"), |
| 2676 |
ramdisk=dict(type="str"), |
| 2677 |
kernel=dict(type="str"), |
| 2678 |
), |
| 2679 |
), |
| 2680 |
image_id=dict(type="str"), |
| 2681 |
instance_type=dict(type="str"), |
| 2682 |
user_data=dict(type="str"), |
| 2683 |
aap_callback=dict( |
| 2684 |
type="dict", |
| 2685 |
aliases=["tower_callback"], |
| 2686 |
required_if=[ |
| 2687 |
( |
| 2688 |
"windows", |
| 2689 |
False, |
| 2690 |
( |
| 2691 |
"tower_address", |
| 2692 |
"job_template_id", |
| 2693 |
"host_config_key", |
| 2694 |
), |
| 2695 |
False, |
| 2696 |
), |
| 2697 |
], |
| 2698 |
options=dict( |
| 2699 |
windows=dict(type="bool", default=False), |
| 2700 |
set_password=dict(type="str", no_log=True), |
| 2701 |
tower_address=dict(type="str"), |
| 2702 |
job_template_id=dict(type="str"), |
| 2703 |
host_config_key=dict(type="str", no_log=True), |
| 2704 |
), |
| 2705 |
), |
| 2706 |
ebs_optimized=dict(type="bool"), |
| 2707 |
vpc_subnet_id=dict(type="str", aliases=["subnet_id"]), |
| 2708 |
availability_zone=dict(type="str"), |
| 2709 |
security_groups=dict(default=[], type="list", elements="str"), |
| 2710 |
security_group=dict(type="str"), |
| 2711 |
iam_instance_profile=dict(type="str", aliases=["instance_role"]), |
| 2712 |
name=dict(type="str"), |
| 2713 |
tags=dict(type="dict", aliases=["resource_tags"]), |
| 2714 |
purge_tags=dict(type="bool", default=True), |
| 2715 |
filters=dict(type="dict", default=None), |
| 2716 |
launch_template=dict(type="dict"), |
| 2717 |
license_specifications=dict( |
| 2718 |
type="list", |
| 2719 |
elements="dict", |
| 2720 |
options=dict( |
| 2721 |
license_configuration_arn=dict(type="str", required=True), |
| 2722 |
), |
| 2723 |
), |
| 2724 |
key_name=dict(type="str"), |
| 2725 |
cpu_credit_specification=dict(type="str", choices=["standard", "unlimited"]), |
| 2726 |
cpu_options=dict( |
| 2727 |
type="dict", |
| 2728 |
options=dict( |
| 2729 |
core_count=dict(type="int", required=True), |
| 2730 |
threads_per_core=dict(type="int", choices=[1, 2], required=True), |
| 2731 |
), |
| 2732 |
), |
| 2733 |
tenancy=dict(type="str", choices=["dedicated", "default"]), |
| 2734 |
placement_group=dict(type="str"), |
| 2735 |
placement=dict( |
| 2736 |
type="dict", |
| 2737 |
options=dict( |
| 2738 |
affinity=dict(type="str"), |
| 2739 |
availability_zone=dict(type="str"), |
| 2740 |
group_name=dict(type="str"), |
| 2741 |
host_id=dict(type="str"), |
| 2742 |
host_resource_group_arn=dict(type="str"), |
| 2743 |
partition_number=dict(type="int"), |
| 2744 |
tenancy=dict(type="str", choices=["dedicated", "default", "host"]), |
| 2745 |
), |
| 2746 |
), |
| 2747 |
instance_initiated_shutdown_behavior=dict(type="str", choices=["stop", "terminate"]), |
| 2748 |
termination_protection=dict(type="bool"), |
| 2749 |
hibernation_options=dict(type="bool", default=False), |
| 2750 |
detailed_monitoring=dict(type="bool"), |
| 2751 |
instance_ids=dict(default=[], type="list", elements="str"), |
| 2752 |
network=dict(default=None, type="dict"), |
| 2753 |
volumes=dict(default=None, type="list", elements="dict"), |
| 2754 |
metadata_options=dict( |
| 2755 |
type="dict", |
| 2756 |
options=dict( |
| 2757 |
http_endpoint=dict(choices=["enabled", "disabled"], default="enabled"), |
| 2758 |
http_put_response_hop_limit=dict(type="int", default=1), |
| 2759 |
http_tokens=dict(choices=["optional", "required"], default="optional"), |
| 2760 |
http_protocol_ipv6=dict(choices=["disabled", "enabled"], default="disabled"), |
| 2761 |
instance_metadata_tags=dict(choices=["disabled", "enabled"], default="disabled"), |
| 2762 |
), |
| 2763 |
), |
| 2764 |
additional_info=dict(type="str"), |
| 2765 |
network_interfaces_ids=dict( |
| 2766 |
type="list", |
| 2767 |
elements="dict", |
| 2768 |
options=dict( |
| 2769 |
id=dict(required=True), |
| 2770 |
device_index=dict(type="int", default=0), |
| 2771 |
), |
| 2772 |
), |
| 2773 |
network_interfaces=dict( |
| 2774 |
type="list", |
| 2775 |
elements="dict", |
| 2776 |
options=dict( |
| 2777 |
assign_public_ip=dict(type="bool"), |
| 2778 |
private_ip_address=dict(), |
| 2779 |
ipv6_addresses=dict(type="list", elements="str"), |
| 2780 |
description=dict(), |
| 2781 |
private_ip_addresses=dict( |
| 2782 |
type="list", |
| 2783 |
elements="dict", |
| 2784 |
options=dict(private_ip_address=dict(required=True), primary=dict(type="bool")), |
| 2785 |
), |
| 2786 |
subnet_id=dict(), |
| 2787 |
delete_on_termination=dict(type="bool", default=True), |
| 2788 |
device_index=dict(type="int", default=0), |
| 2789 |
groups=dict(type="list", elements="str"), |
| 2790 |
), |
| 2791 |
), |
| 2792 |
source_dest_check=dict(type="bool"), |
| 2793 |
) |
| 2794 |
# running/present are synonyms |
| 2795 |
# as are terminated/absent |
| 2796 |
module = AnsibleAWSModule( |
| 2797 |
argument_spec=argument_spec, |
| 2798 |
mutually_exclusive=[ |
| 2799 |
["security_groups", "security_group"], |
| 2800 |
["availability_zone", "vpc_subnet_id"], |
| 2801 |
["aap_callback", "user_data"], |
| 2802 |
["image_id", "image"], |
| 2803 |
["exact_count", "count"], |
| 2804 |
["exact_count", "instance_ids"], |
| 2805 |
["tenancy", "placement"], |
| 2806 |
["placement_group", "placement"], |
| 2807 |
["network", "network_interfaces"], |
| 2808 |
["network", "network_interfaces_ids"], |
| 2809 |
["security_group", "network_interfaces_ids"], |
| 2810 |
["security_groups", "network_interfaces_ids"], |
| 2811 |
], |
| 2812 |
supports_check_mode=True, |
| 2813 |
) |
| 2814 |
|
| 2815 |
result = dict() |
| 2816 |
|
| 2817 |
if module.params.get("network"): |
| 2818 |
module.deprecate( |
| 2819 |
"The network parameter has been deprecated, please use network_interfaces and/or network_interfaces_ids instead.", |
| 2820 |
date="2026-12-01", |
| 2821 |
collection_name="amazon.aws", |
| 2822 |
) |
| 2823 |
if module.params["network"].get("interfaces"): |
| 2824 |
if module.params.get("security_group"): |
| 2825 |
module.fail_json(msg="Parameter network.interfaces can't be used with security_group") |
| 2826 |
if module.params.get("security_groups"): |
| 2827 |
module.fail_json(msg="Parameter network.interfaces can't be used with security_groups") |
| 2828 |
if ( |
| 2829 |
module.params["network"].get("source_dest_check") is not None |
| 2830 |
and module.params.get("source_dest_check") is not None |
| 2831 |
): |
| 2832 |
module.warn( |
| 2833 |
"the source_dest_check option has been set therefore network.source_dest_check will be ignored." |
| 2834 |
) |
| 2835 |
|
| 2836 |
if module.params.get("placement_group"): |
| 2837 |
module.deprecate( |
| 2838 |
"The placement_group parameter has been deprecated, please use placement.group_name instead.", |
| 2839 |
date="2025-12-01", |
| 2840 |
collection_name="amazon.aws", |
| 2841 |
) |
| 2842 |
|
| 2843 |
if module.params.get("tenancy"): |
| 2844 |
module.deprecate( |
| 2845 |
"The tenancy parameter has been deprecated, please use placement.tenancy instead.", |
| 2846 |
date="2025-12-01", |
| 2847 |
collection_name="amazon.aws", |
| 2848 |
) |
| 2849 |
|
| 2850 |
state = module.params.get("state") |
| 2851 |
|
| 2852 |
retry_decorator = AWSRetry.jittered_backoff( |
| 2853 |
catch_extra_error_codes=[ |
| 2854 |
"IncorrectState", |
| 2855 |
"InsufficientInstanceCapacity", |
| 2856 |
"InvalidInstanceID.NotFound", |
| 2857 |
] |
| 2858 |
) |
| 2859 |
client = module.client("ec2", retry_decorator=retry_decorator) |
| 2860 |
|
| 2861 |
filters = module.params.get("filters") |
| 2862 |
if filters is None: |
| 2863 |
filters = build_filters(client, module) |
| 2864 |
|
| 2865 |
try: |
| 2866 |
existing_matches = [] |
| 2867 |
if filters: |
| 2868 |
existing_matches = find_instances(client, module, filters=filters) |
| 2869 |
|
| 2870 |
if state in ("terminated", "absent"): |
| 2871 |
if existing_matches: |
| 2872 |
result = ensure_instance_state(client, module, state, filters) |
| 2873 |
else: |
| 2874 |
result = dict( |
| 2875 |
msg="No matching instances found", |
| 2876 |
changed=False, |
| 2877 |
) |
| 2878 |
elif module.params.get("exact_count"): |
| 2879 |
result = enforce_count(client, module, existing_matches, desired_module_state=state, filters=filters) |
| 2880 |
elif existing_matches and not module.params.get("count"): |
| 2881 |
for match in existing_matches: |
| 2882 |
warn_if_public_ip_assignment_changed(module, match) |
| 2883 |
warn_if_cpu_options_changed(module, match) |
| 2884 |
result = handle_existing(client, module, existing_matches, state, filters=filters) |
| 2885 |
else: |
| 2886 |
result = ensure_present(client, module, existing_matches=existing_matches, desired_module_state=state) |
| 2887 |
except AnsibleEC2Error as e: |
| 2888 |
if e.exception: |
| 2889 |
module.fail_json_aws(e.exception, msg=e.message) |
| 2890 |
module.fail_json(msg=e.message) |
| 2891 |
|
| 2892 |
module.exit_json(**result) |
| 2893 |
|
| 2894 |
|
| 2895 |
if __name__ == "__main__": |
| 2896 |
main() |