| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: Contributors to the Ansible project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
--- |
| 9 |
module: autoscaling_group |
| 10 |
version_added: 5.0.0 |
| 11 |
short_description: Create or delete AWS AutoScaling Groups (ASGs) |
| 12 |
description: |
| 13 |
- Can create or delete AWS AutoScaling Groups. |
| 14 |
- Can be used with the M(community.aws.autoscaling_launch_config) module to manage Launch Configurations. |
| 15 |
- Prior to release 5.0.0 this module was called M(community.aws.ec2_asg). |
| 16 |
The usage did not change. |
| 17 |
- This module was originally added to C(community.aws) in release 1.0.0. |
| 18 |
author: |
| 19 |
- "Gareth Rushgrove (@garethr)" |
| 20 |
options: |
| 21 |
state: |
| 22 |
description: |
| 23 |
- Register or deregister the instance. |
| 24 |
choices: ['present', 'absent'] |
| 25 |
default: present |
| 26 |
type: str |
| 27 |
name: |
| 28 |
description: |
| 29 |
- Unique name for group to be created or deleted. |
| 30 |
aliases: ['group_name'] |
| 31 |
required: true |
| 32 |
type: str |
| 33 |
load_balancers: |
| 34 |
description: |
| 35 |
- List of ELB names to use for the group. Use for classic load balancers. |
| 36 |
type: list |
| 37 |
elements: str |
| 38 |
target_group_arns: |
| 39 |
description: |
| 40 |
- List of target group ARNs to use for the group. Use for application load balancers. |
| 41 |
type: list |
| 42 |
elements: str |
| 43 |
availability_zones: |
| 44 |
description: |
| 45 |
- List of availability zone names in which to create the group. |
| 46 |
- Defaults to all the availability zones in the region if O(vpc_zone_identifier) is not set. |
| 47 |
type: list |
| 48 |
elements: str |
| 49 |
launch_config_name: |
| 50 |
description: |
| 51 |
- Name of the Launch configuration to use for the group. See the M(community.aws.autoscaling_launch_config) module for managing these. |
| 52 |
- Exactly one of O(launch_config_name) or O(launch_template) must be provided when creating a new AutoScaling Group. |
| 53 |
- B(Note) Amazon has deprecated support for AutoScaling Launch Configurations in favour of EC2 Launch Templates. See |
| 54 |
U(https://docs.aws.amazon.com/autoscaling/ec2/userguide/launch-configurations.html) for more information |
| 55 |
type: str |
| 56 |
launch_template: |
| 57 |
description: |
| 58 |
- Dictionary describing the Launch Template to use. |
| 59 |
- Exactly one of O(launch_config_name) or O(launch_template) must be provided when creating a new AutoScaling Group. |
| 60 |
suboptions: |
| 61 |
version: |
| 62 |
description: |
| 63 |
- The version number of the launch template to use. |
| 64 |
- Defaults to latest version if not provided. |
| 65 |
type: str |
| 66 |
launch_template_name: |
| 67 |
description: |
| 68 |
- The name of the launch template. Only one of O(launch_template.launch_template_name) or O(launch_template.launch_template_id) is required. |
| 69 |
type: str |
| 70 |
launch_template_id: |
| 71 |
description: |
| 72 |
- The id of the launch template. Only one of O(launch_template.launch_template_name) or O(launch_template.launch_template_id) is required. |
| 73 |
type: str |
| 74 |
type: dict |
| 75 |
min_size: |
| 76 |
description: |
| 77 |
- Minimum number of instances in group, if unspecified then the current group value will be used. |
| 78 |
type: int |
| 79 |
max_size: |
| 80 |
description: |
| 81 |
- Maximum number of instances in group, if unspecified then the current group value will be used. |
| 82 |
type: int |
| 83 |
max_instance_lifetime: |
| 84 |
description: |
| 85 |
- The maximum amount of time, in seconds, that an instance can be in service. |
| 86 |
- Maximum instance lifetime must be equal to V(0), between V(604800) and V(31536000) seconds (inclusive), or not specified. |
| 87 |
- Value of V(0) removes lifetime restriction. |
| 88 |
type: int |
| 89 |
mixed_instances_policy: |
| 90 |
description: |
| 91 |
- A mixed instance policy to use for the ASG. |
| 92 |
- Only used when the ASG is configured to use a Launch Template (O(launch_template)). |
| 93 |
- 'See also U(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-autoscalinggroup-mixedinstancespolicy.html)' |
| 94 |
required: false |
| 95 |
suboptions: |
| 96 |
instance_types: |
| 97 |
description: |
| 98 |
- A list of instance types. |
| 99 |
type: list |
| 100 |
elements: str |
| 101 |
required: false |
| 102 |
instances_distribution: |
| 103 |
description: |
| 104 |
- >- |
| 105 |
Specifies the distribution of On-Demand Instances and Spot Instances, the maximum price |
| 106 |
to pay for Spot Instances, and how the Auto Scaling group allocates instance types |
| 107 |
to fulfill On-Demand and Spot capacity. |
| 108 |
- 'See also U(https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_InstancesDistribution.html)' |
| 109 |
required: false |
| 110 |
type: dict |
| 111 |
version_added: 1.5.0 |
| 112 |
version_added_collection: community.aws |
| 113 |
suboptions: |
| 114 |
on_demand_allocation_strategy: |
| 115 |
description: |
| 116 |
- Indicates how to allocate instance types to fulfill On-Demand capacity. |
| 117 |
type: str |
| 118 |
required: false |
| 119 |
version_added: 1.5.0 |
| 120 |
version_added_collection: community.aws |
| 121 |
on_demand_base_capacity: |
| 122 |
description: |
| 123 |
- >- |
| 124 |
The minimum amount of the Auto Scaling group's capacity that must be fulfilled by On-Demand |
| 125 |
Instances. This base portion is provisioned first as your group scales. |
| 126 |
- >- |
| 127 |
Default if not set is V(0). If you leave it set to V(0), On-Demand Instances are launched as a |
| 128 |
percentage of the Auto Scaling group's desired capacity, per the |
| 129 |
O(mixed_instances_policy.instances_distribution.on_demand_percentage_above_base_capacity) setting. |
| 130 |
type: int |
| 131 |
required: false |
| 132 |
version_added: 1.5.0 |
| 133 |
version_added_collection: community.aws |
| 134 |
on_demand_percentage_above_base_capacity: |
| 135 |
description: |
| 136 |
- Controls the percentages of On-Demand Instances and Spot Instances for your additional capacity beyond |
| 137 |
O(mixed_instances_policy.instances_distribution.on_demand_base_capacity). |
| 138 |
- Default if not set is V(100). If you leave it set to V(100), the percentages are 100% for On-Demand Instances and 0% for Spot Instances. |
| 139 |
- 'Valid range: V(0) to V(100).' |
| 140 |
type: int |
| 141 |
required: false |
| 142 |
version_added: 1.5.0 |
| 143 |
version_added_collection: community.aws |
| 144 |
spot_allocation_strategy: |
| 145 |
description: |
| 146 |
- Indicates how to allocate instances across Spot Instance pools. |
| 147 |
type: str |
| 148 |
required: false |
| 149 |
version_added: 1.5.0 |
| 150 |
version_added_collection: community.aws |
| 151 |
spot_instance_pools: |
| 152 |
description: |
| 153 |
- >- |
| 154 |
The number of Spot Instance pools across which to allocate your Spot Instances. The Spot pools are determined from |
| 155 |
the different instance types in the Overrides array of LaunchTemplate. Default if not set is V(2). |
| 156 |
- Used only when the Spot allocation strategy is lowest-price. |
| 157 |
- 'Valid Range: Minimum value of V(1). Maximum value of V(20).' |
| 158 |
type: int |
| 159 |
required: false |
| 160 |
version_added: 1.5.0 |
| 161 |
version_added_collection: community.aws |
| 162 |
spot_max_price: |
| 163 |
description: |
| 164 |
- The maximum price per unit hour that you are willing to pay for a Spot Instance. |
| 165 |
- If you leave the value of this parameter blank (which is the default), the maximum Spot price is set at the On-Demand price. |
| 166 |
- To remove a value that you previously set, include the parameter but leave the value blank. |
| 167 |
type: str |
| 168 |
required: false |
| 169 |
version_added: 1.5.0 |
| 170 |
version_added_collection: community.aws |
| 171 |
type: dict |
| 172 |
placement_group: |
| 173 |
description: |
| 174 |
- Physical location of your cluster placement group created in Amazon EC2. |
| 175 |
type: str |
| 176 |
desired_capacity: |
| 177 |
description: |
| 178 |
- Desired number of instances in group, if unspecified then the current group value will be used. |
| 179 |
type: int |
| 180 |
replace_all_instances: |
| 181 |
description: |
| 182 |
- Support for the O(replace_all_instances) parameter has been deprecated and will be removed |
| 183 |
in release 14.0.0. |
| 184 |
The M(amazon.aws.autoscaling_instance_refresh) module can be used to perform an automated |
| 185 |
replacement of instances. |
| 186 |
- In a rolling fashion, replace all instances that used the old launch configuration with one from the new launch configuration. |
| 187 |
It increases the ASG size by O(replace_batch_size), waits for the new instances to be up and running. |
| 188 |
After that, it terminates a batch of old instances, waits for the replacements, and repeats, until all old instances are replaced. |
| 189 |
Once that's done the ASG size is reduced back to the expected size. |
| 190 |
default: false |
| 191 |
type: bool |
| 192 |
replace_batch_size: |
| 193 |
description: |
| 194 |
- Support for the O(replace_all_instances) and O(replace_batch_size) parameters has been |
| 195 |
deprecated and will be removed in release 14.0.0. |
| 196 |
The M(amazon.aws.autoscaling_instance_refresh) module can be used to perform an automated |
| 197 |
replacement of instances. |
| 198 |
- Number of instances you'd like to replace at a time. Used with O(replace_all_instances). |
| 199 |
required: false |
| 200 |
default: 1 |
| 201 |
type: int |
| 202 |
replace_instances: |
| 203 |
description: |
| 204 |
- Support for the O(replace_instances) parameter has been deprecated and will be removed in |
| 205 |
release 14.0.0. |
| 206 |
The M(amazon.aws.autoscaling_instance) module can be used to terminate instances attached |
| 207 |
to an AutoScaling Group. |
| 208 |
- List of instance ids belonging to the named AutoScalingGroup that you would like to terminate and be replaced with instances |
| 209 |
matching the current launch configuration. |
| 210 |
type: list |
| 211 |
elements: str |
| 212 |
default: [] |
| 213 |
detach_instances: |
| 214 |
description: |
| 215 |
- Support for the O(detach_instances) parameter has been deprecated and will be removed in |
| 216 |
release 14.0.0. |
| 217 |
The M(amazon.aws.autoscaling_instance) module can be used to attach instances to and detach |
| 218 |
and detach instances from an AutoScaling Group. |
| 219 |
- Removes one or more instances from the specified AutoScalingGroup. |
| 220 |
- If O(decrement_desired_capacity) flag is not set, new instance(s) are launched to replace the detached instance(s). |
| 221 |
- If a Classic Load Balancer is attached to the AutoScalingGroup, the instances are also deregistered from the load balancer. |
| 222 |
- If there are target groups attached to the AutoScalingGroup, the instances are also deregistered from the target groups. |
| 223 |
type: list |
| 224 |
elements: str |
| 225 |
default: [] |
| 226 |
version_added: 3.2.0 |
| 227 |
version_added_collection: community.aws |
| 228 |
decrement_desired_capacity: |
| 229 |
description: |
| 230 |
- Support for the O(detach_instances) and O(decrement_desired_capacity) parameters has been |
| 231 |
deprecated and will be removed in release 14.0.0. |
| 232 |
The M(amazon.aws.autoscaling_instance) module can be used to attach instances to and detach |
| 233 |
and detach instances from an AutoScaling Group. |
| 234 |
- Indicates whether the AutoScalingGroup decrements the desired capacity value by the number of instances detached. |
| 235 |
default: false |
| 236 |
type: bool |
| 237 |
version_added: 3.2.0 |
| 238 |
version_added_collection: community.aws |
| 239 |
lc_check: |
| 240 |
description: |
| 241 |
- Support for the O(detach_instances) and O(lc_check) parameters has been deprecated and will |
| 242 |
be removed in release 14.0.0. |
| 243 |
The M(amazon.aws.autoscaling_instance) module can be used to attach instances to and detach |
| 244 |
and detach instances from an AutoScaling Group. |
| 245 |
- Check to make sure instances that are being replaced with O(replace_instances) do not already have the current launch config. |
| 246 |
default: true |
| 247 |
type: bool |
| 248 |
lt_check: |
| 249 |
description: |
| 250 |
- Support for the O(detach_instances) and O(lt_check) parameters has been deprecated and will |
| 251 |
be removed in release 14.0.0. |
| 252 |
The M(amazon.aws.autoscaling_instance) module can be used to attach instances to and detach |
| 253 |
and detach instances from an AutoScaling Group. |
| 254 |
- Check to make sure instances that are being replaced with O(replace_instances) do not already have the current |
| 255 |
O(launch_template) or O(launch_template) O(launch_template.version). |
| 256 |
default: true |
| 257 |
type: bool |
| 258 |
vpc_zone_identifier: |
| 259 |
description: |
| 260 |
- List of VPC subnets to use |
| 261 |
type: list |
| 262 |
elements: str |
| 263 |
protected_from_scale_in: |
| 264 |
description: |
| 265 |
- If V(true), new instances will have scale-in protection enabled when added to the AutoScaling Group. |
| 266 |
- Defaults to V(false) when creating a new AutoScaling Group. |
| 267 |
type: bool |
| 268 |
version_added: 11.1.0 |
| 269 |
tags: |
| 270 |
description: |
| 271 |
- A list of tags to add to the Auto Scale Group. |
| 272 |
- Optional key is V(propagate_at_launch), which defaults to V(true). |
| 273 |
- When V(propagate_at_launch) is V(true) the tags will be propagated to the Instances created. |
| 274 |
type: list |
| 275 |
elements: dict |
| 276 |
default: [] |
| 277 |
purge_tags: |
| 278 |
description: |
| 279 |
- If V(true), existing tags will be purged from the resource to match exactly what is defined by O(tags) parameter. |
| 280 |
- If the O(tags) parameter is not set then tags will not be modified. |
| 281 |
default: false |
| 282 |
type: bool |
| 283 |
version_added: 3.2.0 |
| 284 |
version_added_collection: community.aws |
| 285 |
health_check_period: |
| 286 |
description: |
| 287 |
- Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health. |
| 288 |
required: false |
| 289 |
default: 300 |
| 290 |
type: int |
| 291 |
health_check_type: |
| 292 |
description: |
| 293 |
- The service you want the health status from, Amazon EC2 or Elastic Load Balancer. |
| 294 |
required: false |
| 295 |
default: EC2 |
| 296 |
choices: ['EC2', 'ELB'] |
| 297 |
type: str |
| 298 |
default_cooldown: |
| 299 |
description: |
| 300 |
- The number of seconds after a scaling activity completes before another can begin. |
| 301 |
default: 300 |
| 302 |
type: int |
| 303 |
wait_timeout: |
| 304 |
description: |
| 305 |
- How long to wait for instances to become viable when replaced. If you experience the error "Waited too long for ELB instances to be healthy", |
| 306 |
try increasing this value. |
| 307 |
default: 300 |
| 308 |
type: int |
| 309 |
wait_for_instances: |
| 310 |
description: |
| 311 |
- Wait for the ASG instances to be in a ready state before exiting. If instances are behind an ELB, it will wait until the ELB determines all |
| 312 |
instances have a lifecycle_state of "InService" and a health_status of "Healthy". |
| 313 |
default: true |
| 314 |
type: bool |
| 315 |
termination_policies: |
| 316 |
description: |
| 317 |
- An ordered list of criteria used for selecting instances to be removed from the Auto Scaling group when reducing capacity. |
| 318 |
- Using O(termination_policies=Default) when modifying an existing AutoScalingGroup will result in the existing policy being retained |
| 319 |
instead of changed to V(Default). |
| 320 |
- 'Valid values include: V(Default), V(OldestInstance), V(NewestInstance), V(OldestLaunchConfiguration), V(ClosestToNextInstanceHour)' |
| 321 |
- 'Full documentation of valid values can be found in the AWS documentation:' |
| 322 |
- 'U(https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html#custom-termination-policy)' |
| 323 |
default: Default |
| 324 |
type: list |
| 325 |
elements: str |
| 326 |
notification_topic: |
| 327 |
description: |
| 328 |
- A SNS topic ARN to send auto scaling notifications to. |
| 329 |
type: str |
| 330 |
notification_types: |
| 331 |
description: |
| 332 |
- A list of auto scaling events to trigger notifications on. |
| 333 |
default: |
| 334 |
- 'autoscaling:EC2_INSTANCE_LAUNCH' |
| 335 |
- 'autoscaling:EC2_INSTANCE_LAUNCH_ERROR' |
| 336 |
- 'autoscaling:EC2_INSTANCE_TERMINATE' |
| 337 |
- 'autoscaling:EC2_INSTANCE_TERMINATE_ERROR' |
| 338 |
required: false |
| 339 |
type: list |
| 340 |
elements: str |
| 341 |
suspend_processes: |
| 342 |
description: |
| 343 |
- A list of scaling processes to suspend. |
| 344 |
- 'Valid values include:' |
| 345 |
- V(Launch), V(Terminate), V(HealthCheck), V(ReplaceUnhealthy), V(AZRebalance), V(AlarmNotification), V(ScheduledActions), V(AddToLoadBalancer) |
| 346 |
- 'Full documentation of valid values can be found in the AWS documentation:' |
| 347 |
- 'U(https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html)' |
| 348 |
default: [] |
| 349 |
type: list |
| 350 |
elements: str |
| 351 |
metrics_collection: |
| 352 |
description: |
| 353 |
- Enable ASG metrics collection. |
| 354 |
type: bool |
| 355 |
default: false |
| 356 |
metrics_granularity: |
| 357 |
description: |
| 358 |
- When O(metrics_collection=true) this will determine the granularity of metrics collected by CloudWatch. |
| 359 |
default: "1Minute" |
| 360 |
type: str |
| 361 |
metrics_list: |
| 362 |
description: |
| 363 |
- List of autoscaling metrics to collect when O(metrics_collection=true). |
| 364 |
default: |
| 365 |
- 'GroupMinSize' |
| 366 |
- 'GroupMaxSize' |
| 367 |
- 'GroupDesiredCapacity' |
| 368 |
- 'GroupInServiceInstances' |
| 369 |
- 'GroupPendingInstances' |
| 370 |
- 'GroupStandbyInstances' |
| 371 |
- 'GroupTerminatingInstances' |
| 372 |
- 'GroupTotalInstances' |
| 373 |
type: list |
| 374 |
elements: str |
| 375 |
extends_documentation_fragment: |
| 376 |
- amazon.aws.common.modules |
| 377 |
- amazon.aws.region.modules |
| 378 |
- amazon.aws.boto3 |
| 379 |
""" |
| 380 |
|
| 381 |
EXAMPLES = r""" |
| 382 |
# Basic configuration with Launch Template |
| 383 |
|
| 384 |
- name: Create an autoscaling group using launch template |
| 385 |
amazon.aws.autoscaling_group: |
| 386 |
name: example_asg |
| 387 |
load_balancers: ['lb1', 'lb2'] |
| 388 |
availability_zones: ['eu-west-1a', 'eu-west-1b'] |
| 389 |
launch_template: |
| 390 |
launch_template_name: 'template-1' |
| 391 |
min_size: 1 |
| 392 |
max_size: 10 |
| 393 |
desired_capacity: 5 |
| 394 |
vpc_zone_identifier: ['subnet-abcd1234', 'subnet-1a2b3c4d'] |
| 395 |
tags: |
| 396 |
- environment: production |
| 397 |
propagate_at_launch: false |
| 398 |
|
| 399 |
# Rolling ASG Updates |
| 400 |
|
| 401 |
# Below is an example of how to assign a new launch template to an ASG and replace old instances. |
| 402 |
# By setting max_healthy_percentage to a value over 100 the old rolling-replacement behaviour of |
| 403 |
# scaling up before scaling in can be maintained. |
| 404 |
|
| 405 |
- name: Update autoscaling group with new template - instances are not replaced |
| 406 |
amazon.aws.autoscaling_group: |
| 407 |
name: example_asg |
| 408 |
launch_template: |
| 409 |
launch_template_name: template-2 |
| 410 |
health_check_period: 60 |
| 411 |
health_check_type: ELB |
| 412 |
min_size: 2 |
| 413 |
max_size: 13 |
| 414 |
desired_capacity: 6 |
| 415 |
region: us-east-1 |
| 416 |
|
| 417 |
- name: Replace 2 instances based on EC2 Instance ID by marking them for termination |
| 418 |
amazon.aws.autoscaling_instance: |
| 419 |
group_name: example_asg |
| 420 |
state: terminated |
| 421 |
instance_ids: |
| 422 |
- i-b345231 |
| 423 |
- i-24c2931 |
| 424 |
decrement_desired_capacity: false |
| 425 |
wait: true |
| 426 |
|
| 427 |
- name: Trigger rolling replacement of all instances that do not match the current configuration. |
| 428 |
amazon.aws.autoscaling_instance_refresh: |
| 429 |
group_name: example_asg |
| 430 |
state: started |
| 431 |
strategy: Rolling |
| 432 |
preferences: |
| 433 |
skip_matching: true |
| 434 |
max_healthy_percentage: 125 # scale out before terminating instances during replacement |
| 435 |
|
| 436 |
# Basic Configuration with Launch Template |
| 437 |
|
| 438 |
- name: Example autoscaling group creation with a launch template |
| 439 |
amazon.aws.autoscaling_group: |
| 440 |
name: example_with_template |
| 441 |
load_balancers: ['lb1', 'lb2'] |
| 442 |
availability_zones: ['eu-west-1a', 'eu-west-1b'] |
| 443 |
launch_template: |
| 444 |
version: '1' |
| 445 |
launch_template_name: 'lt-example' |
| 446 |
launch_template_id: 'lt-123456' |
| 447 |
min_size: 1 |
| 448 |
max_size: 10 |
| 449 |
desired_capacity: 5 |
| 450 |
vpc_zone_identifier: ['subnet-abcd1234', 'subnet-1a2b3c4d'] |
| 451 |
tags: |
| 452 |
- environment: production |
| 453 |
propagate_at_launch: false |
| 454 |
|
| 455 |
# Basic Configuration with Launch Template using mixed instance policy |
| 456 |
|
| 457 |
- name: Example autoscaling group creation with a mixed instance policy |
| 458 |
amazon.aws.autoscaling_group: |
| 459 |
name: example_with_policy |
| 460 |
load_balancers: ['lb1', 'lb2'] |
| 461 |
availability_zones: ['eu-west-1a', 'eu-west-1b'] |
| 462 |
launch_template: |
| 463 |
version: '1' |
| 464 |
launch_template_name: 'lt-example' |
| 465 |
launch_template_id: 'lt-123456' |
| 466 |
mixed_instances_policy: |
| 467 |
instance_types: |
| 468 |
- t3a.large |
| 469 |
- t3.large |
| 470 |
- t2.large |
| 471 |
instances_distribution: |
| 472 |
on_demand_percentage_above_base_capacity: 0 |
| 473 |
spot_allocation_strategy: capacity-optimized |
| 474 |
min_size: 1 |
| 475 |
max_size: 10 |
| 476 |
desired_capacity: 5 |
| 477 |
vpc_zone_identifier: ['subnet-abcd1234', 'subnet-1a2b3c4d'] |
| 478 |
tags: |
| 479 |
- environment: production |
| 480 |
propagate_at_launch: false |
| 481 |
""" |
| 482 |
|
| 483 |
RETURN = r""" |
| 484 |
--- |
| 485 |
auto_scaling_group_name: |
| 486 |
description: The unique name of the auto scaling group |
| 487 |
returned: success |
| 488 |
type: str |
| 489 |
sample: "myasg" |
| 490 |
auto_scaling_group_arn: |
| 491 |
description: The unique ARN of the autoscaling group |
| 492 |
returned: success |
| 493 |
type: str |
| 494 |
sample: "arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:6a09ad6d-eeee-1234-b987-ee123ced01ad:autoScalingGroupName/myasg" |
| 495 |
availability_zones: |
| 496 |
description: The availability zones for the auto scaling group |
| 497 |
returned: success |
| 498 |
type: list |
| 499 |
sample: [ |
| 500 |
"us-east-1d" |
| 501 |
] |
| 502 |
created_time: |
| 503 |
description: Timestamp of create time of the auto scaling group |
| 504 |
returned: success |
| 505 |
type: str |
| 506 |
sample: "2017-11-08T14:41:48.272000+00:00" |
| 507 |
default_cooldown: |
| 508 |
description: The default cooldown time in seconds. |
| 509 |
returned: success |
| 510 |
type: int |
| 511 |
sample: 300 |
| 512 |
desired_capacity: |
| 513 |
description: The number of EC2 instances that should be running in this group. |
| 514 |
returned: success |
| 515 |
type: int |
| 516 |
sample: 3 |
| 517 |
healthcheck_period: |
| 518 |
description: Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health. |
| 519 |
returned: success |
| 520 |
type: int |
| 521 |
sample: 30 |
| 522 |
healthcheck_type: |
| 523 |
description: The service you want the health status from, one of "EC2" or "ELB". |
| 524 |
returned: success |
| 525 |
type: str |
| 526 |
sample: "ELB" |
| 527 |
healthy_instances: |
| 528 |
description: Number of instances in a healthy state |
| 529 |
returned: success |
| 530 |
type: int |
| 531 |
sample: 5 |
| 532 |
in_service_instances: |
| 533 |
description: Number of instances in service |
| 534 |
returned: success |
| 535 |
type: int |
| 536 |
sample: 3 |
| 537 |
instance_facts: |
| 538 |
description: Dictionary of EC2 instances and their status as it relates to the ASG. |
| 539 |
returned: success |
| 540 |
type: dict |
| 541 |
sample: { |
| 542 |
"i-0123456789012": { |
| 543 |
"health_status": "Healthy", |
| 544 |
"launch_config_name": "public-webapp-production-1", |
| 545 |
"lifecycle_state": "InService" |
| 546 |
} |
| 547 |
} |
| 548 |
instances: |
| 549 |
description: list of instance IDs in the ASG |
| 550 |
returned: success |
| 551 |
type: list |
| 552 |
sample: [ |
| 553 |
"i-0123456789012" |
| 554 |
] |
| 555 |
launch_config_name: |
| 556 |
description: > |
| 557 |
Name of launch configuration associated with the ASG. Same as launch_configuration_name, |
| 558 |
provided for compatibility with M(amazon.aws.autoscaling_group) module. |
| 559 |
returned: success |
| 560 |
type: str |
| 561 |
sample: "public-webapp-production-1" |
| 562 |
load_balancers: |
| 563 |
description: List of load balancers names attached to the ASG. |
| 564 |
returned: success |
| 565 |
type: list |
| 566 |
sample: ["elb-webapp-prod"] |
| 567 |
max_instance_lifetime: |
| 568 |
description: The maximum amount of time, in seconds, that an instance can be in service. |
| 569 |
returned: success |
| 570 |
type: int |
| 571 |
sample: 604800 |
| 572 |
max_size: |
| 573 |
description: Maximum size of group |
| 574 |
returned: success |
| 575 |
type: int |
| 576 |
sample: 3 |
| 577 |
min_size: |
| 578 |
description: Minimum size of group |
| 579 |
returned: success |
| 580 |
type: int |
| 581 |
sample: 1 |
| 582 |
mixed_instances_policy: |
| 583 |
description: Returns the list of instance types if a mixed instances policy is set. |
| 584 |
returned: success |
| 585 |
type: list |
| 586 |
sample: ["t3.micro", "t3a.micro"] |
| 587 |
mixed_instances_policy_full: |
| 588 |
description: Returns the full dictionary representation of the mixed instances policy if a mixed instances policy is set. |
| 589 |
returned: success |
| 590 |
type: dict |
| 591 |
sample: { |
| 592 |
"instances_distribution": { |
| 593 |
"on_demand_allocation_strategy": "prioritized", |
| 594 |
"on_demand_base_capacity": 0, |
| 595 |
"on_demand_percentage_above_base_capacity": 0, |
| 596 |
"spot_allocation_strategy": "capacity-optimized" |
| 597 |
}, |
| 598 |
"launch_template": { |
| 599 |
"launch_template_specification": { |
| 600 |
"launch_template_id": "lt-53c2425cffa544c23", |
| 601 |
"launch_template_name": "random-LaunchTemplate", |
| 602 |
"version": "2" |
| 603 |
}, |
| 604 |
"overrides": [ |
| 605 |
{ |
| 606 |
"instance_type": "m5.xlarge" |
| 607 |
}, |
| 608 |
{ |
| 609 |
"instance_type": "m5a.xlarge" |
| 610 |
}, |
| 611 |
] |
| 612 |
} |
| 613 |
} |
| 614 |
pending_instances: |
| 615 |
description: Number of instances in pending state |
| 616 |
returned: success |
| 617 |
type: int |
| 618 |
sample: 1 |
| 619 |
tags: |
| 620 |
description: List of tags for the ASG, and whether or not each tag propagates to instances at launch. |
| 621 |
returned: success |
| 622 |
type: list |
| 623 |
sample: [ |
| 624 |
{ |
| 625 |
"key": "Name", |
| 626 |
"value": "public-webapp-production-1", |
| 627 |
"resource_id": "public-webapp-production-1", |
| 628 |
"resource_type": "auto-scaling-group", |
| 629 |
"propagate_at_launch": "true" |
| 630 |
}, |
| 631 |
{ |
| 632 |
"key": "env", |
| 633 |
"value": "production", |
| 634 |
"resource_id": "public-webapp-production-1", |
| 635 |
"resource_type": "auto-scaling-group", |
| 636 |
"propagate_at_launch": "true" |
| 637 |
} |
| 638 |
] |
| 639 |
target_group_arns: |
| 640 |
description: List of ARNs of the target groups that the ASG populates |
| 641 |
returned: success |
| 642 |
type: list |
| 643 |
sample: [ |
| 644 |
"arn:aws:elasticloadbalancing:ap-southeast-2:123456789012:targetgroup/target-group-host-hello/1a2b3c4d5e6f1a2b", |
| 645 |
"arn:aws:elasticloadbalancing:ap-southeast-2:123456789012:targetgroup/target-group-path-world/abcd1234abcd1234" |
| 646 |
] |
| 647 |
target_group_names: |
| 648 |
description: List of names of the target groups that the ASG populates |
| 649 |
returned: success |
| 650 |
type: list |
| 651 |
sample: [ |
| 652 |
"target-group-host-hello", |
| 653 |
"target-group-path-world" |
| 654 |
] |
| 655 |
termination_policies: |
| 656 |
description: A list of termination policies for the group. |
| 657 |
returned: success |
| 658 |
type: list |
| 659 |
sample: ["Default"] |
| 660 |
unhealthy_instances: |
| 661 |
description: Number of instances in an unhealthy state |
| 662 |
returned: success |
| 663 |
type: int |
| 664 |
sample: 0 |
| 665 |
viable_instances: |
| 666 |
description: Number of instances in a viable state |
| 667 |
returned: success |
| 668 |
type: int |
| 669 |
sample: 1 |
| 670 |
vpc_zone_identifier: |
| 671 |
description: VPC zone ID / subnet id for the auto scaling group |
| 672 |
returned: success |
| 673 |
type: str |
| 674 |
sample: "subnet-a31ef45f" |
| 675 |
metrics_collection: |
| 676 |
description: List of enabled AutosSalingGroup metrics |
| 677 |
returned: success |
| 678 |
type: list |
| 679 |
sample: [ |
| 680 |
{ |
| 681 |
"Granularity": "1Minute", |
| 682 |
"Metric": "GroupInServiceInstances" |
| 683 |
} |
| 684 |
] |
| 685 |
""" |
| 686 |
|
| 687 |
import time |
| 688 |
|
| 689 |
try: |
| 690 |
import botocore |
| 691 |
except ImportError: |
| 692 |
pass # Handled by AnsibleAWSModule |
| 693 |
|
| 694 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 695 |
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict |
| 696 |
from ansible.module_utils.common.text.converters import to_native |
| 697 |
|
| 698 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code |
| 699 |
from ansible_collections.amazon.aws.plugins.module_utils.elb_utils import describe_target_groups |
| 700 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 701 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 702 |
from ansible_collections.amazon.aws.plugins.module_utils.transformation import scrub_none_parameters |
| 703 |
|
| 704 |
backoff_params = dict(retries=10, delay=3, backoff=1.5) |
| 705 |
|
| 706 |
|
| 707 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 708 |
def describe_autoscaling_groups(connection, group_name): |
| 709 |
pg = connection.get_paginator("describe_auto_scaling_groups") |
| 710 |
return pg.paginate(AutoScalingGroupNames=[group_name]).build_full_result().get("AutoScalingGroups", []) |
| 711 |
|
| 712 |
|
| 713 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 714 |
def deregister_lb_instances(connection, lb_name, instance_id): |
| 715 |
connection.deregister_instances_from_load_balancer( |
| 716 |
LoadBalancerName=lb_name, Instances=[dict(InstanceId=instance_id)] |
| 717 |
) |
| 718 |
|
| 719 |
|
| 720 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 721 |
def describe_instance_health(connection, lb_name, instances): |
| 722 |
params = dict(LoadBalancerName=lb_name) |
| 723 |
if instances: |
| 724 |
params.update(Instances=instances) |
| 725 |
return connection.describe_instance_health(**params) |
| 726 |
|
| 727 |
|
| 728 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 729 |
def describe_target_health(connection, target_group_arn, instances): |
| 730 |
return connection.describe_target_health(TargetGroupArn=target_group_arn, Targets=instances) |
| 731 |
|
| 732 |
|
| 733 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 734 |
def suspend_asg_processes(connection, asg_name, processes): |
| 735 |
connection.suspend_processes(AutoScalingGroupName=asg_name, ScalingProcesses=processes) |
| 736 |
|
| 737 |
|
| 738 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 739 |
def resume_asg_processes(connection, asg_name, processes): |
| 740 |
connection.resume_processes(AutoScalingGroupName=asg_name, ScalingProcesses=processes) |
| 741 |
|
| 742 |
|
| 743 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 744 |
def describe_launch_configurations(connection, launch_config_name): |
| 745 |
pg = connection.get_paginator("describe_launch_configurations") |
| 746 |
return pg.paginate(LaunchConfigurationNames=[launch_config_name]).build_full_result() |
| 747 |
|
| 748 |
|
| 749 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 750 |
def describe_launch_templates(connection, launch_template): |
| 751 |
if launch_template["launch_template_id"] is not None: |
| 752 |
try: |
| 753 |
lt = connection.describe_launch_templates(LaunchTemplateIds=[launch_template["launch_template_id"]]) |
| 754 |
return lt |
| 755 |
except is_boto3_error_code("InvalidLaunchTemplateName.NotFoundException"): |
| 756 |
module.fail_json(msg=f"No launch template found matching: {launch_template}") |
| 757 |
else: |
| 758 |
try: |
| 759 |
lt = connection.describe_launch_templates(LaunchTemplateNames=[launch_template["launch_template_name"]]) |
| 760 |
return lt |
| 761 |
except is_boto3_error_code("InvalidLaunchTemplateName.NotFoundException"): |
| 762 |
module.fail_json(msg=f"No launch template found matching: {launch_template}") |
| 763 |
|
| 764 |
|
| 765 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 766 |
def create_asg(connection, **params): |
| 767 |
connection.create_auto_scaling_group(**params) |
| 768 |
|
| 769 |
|
| 770 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 771 |
def put_notification_config(connection, asg_name, topic_arn, notification_types): |
| 772 |
connection.put_notification_configuration( |
| 773 |
AutoScalingGroupName=asg_name, TopicARN=topic_arn, NotificationTypes=notification_types |
| 774 |
) |
| 775 |
|
| 776 |
|
| 777 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 778 |
def del_notification_config(connection, asg_name, topic_arn): |
| 779 |
connection.delete_notification_configuration(AutoScalingGroupName=asg_name, TopicARN=topic_arn) |
| 780 |
|
| 781 |
|
| 782 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 783 |
def attach_load_balancers(connection, asg_name, load_balancers): |
| 784 |
connection.attach_load_balancers(AutoScalingGroupName=asg_name, LoadBalancerNames=load_balancers) |
| 785 |
|
| 786 |
|
| 787 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 788 |
def detach_load_balancers(connection, asg_name, load_balancers): |
| 789 |
connection.detach_load_balancers(AutoScalingGroupName=asg_name, LoadBalancerNames=load_balancers) |
| 790 |
|
| 791 |
|
| 792 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 793 |
def attach_lb_target_groups(connection, asg_name, target_group_arns): |
| 794 |
connection.attach_load_balancer_target_groups(AutoScalingGroupName=asg_name, TargetGroupARNs=target_group_arns) |
| 795 |
|
| 796 |
|
| 797 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 798 |
def detach_lb_target_groups(connection, asg_name, target_group_arns): |
| 799 |
connection.detach_load_balancer_target_groups(AutoScalingGroupName=asg_name, TargetGroupARNs=target_group_arns) |
| 800 |
|
| 801 |
|
| 802 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 803 |
def update_asg(connection, **params): |
| 804 |
connection.update_auto_scaling_group(**params) |
| 805 |
|
| 806 |
|
| 807 |
@AWSRetry.jittered_backoff(catch_extra_error_codes=["ScalingActivityInProgress"], **backoff_params) |
| 808 |
def delete_asg(connection, asg_name, force_delete): |
| 809 |
connection.delete_auto_scaling_group(AutoScalingGroupName=asg_name, ForceDelete=force_delete) |
| 810 |
|
| 811 |
|
| 812 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 813 |
def terminate_asg_instance(connection, instance_id, decrement_capacity): |
| 814 |
connection.terminate_instance_in_auto_scaling_group( |
| 815 |
InstanceId=instance_id, ShouldDecrementDesiredCapacity=decrement_capacity |
| 816 |
) |
| 817 |
|
| 818 |
|
| 819 |
@AWSRetry.jittered_backoff(**backoff_params) |
| 820 |
def detach_asg_instances(connection, instance_ids, as_group_name, decrement_capacity): |
| 821 |
connection.detach_instances( |
| 822 |
InstanceIds=instance_ids, AutoScalingGroupName=as_group_name, ShouldDecrementDesiredCapacity=decrement_capacity |
| 823 |
) |
| 824 |
|
| 825 |
|
| 826 |
def enforce_required_arguments_for_create(): |
| 827 |
"""As many arguments are not required for autoscale group deletion |
| 828 |
they cannot be mandatory arguments for the module, so we enforce |
| 829 |
them here""" |
| 830 |
missing_args = [] |
| 831 |
if module.params.get("launch_config_name") is None and module.params.get("launch_template") is None: |
| 832 |
module.fail_json(msg="Missing either launch_config_name or launch_template for autoscaling group create") |
| 833 |
for arg in ("min_size", "max_size"): |
| 834 |
if module.params[arg] is None: |
| 835 |
missing_args.append(arg) |
| 836 |
if missing_args: |
| 837 |
module.fail_json(msg=f"Missing required arguments for autoscaling group create: {','.join(missing_args)}") |
| 838 |
|
| 839 |
|
| 840 |
def get_properties(autoscaling_group): |
| 841 |
properties = dict( |
| 842 |
healthy_instances=0, |
| 843 |
in_service_instances=0, |
| 844 |
unhealthy_instances=0, |
| 845 |
pending_instances=0, |
| 846 |
viable_instances=0, |
| 847 |
terminating_instances=0, |
| 848 |
) |
| 849 |
instance_facts = dict() |
| 850 |
autoscaling_group_instances = autoscaling_group.get("Instances") |
| 851 |
|
| 852 |
if autoscaling_group_instances: |
| 853 |
properties["instances"] = [i["InstanceId"] for i in autoscaling_group_instances] |
| 854 |
for i in autoscaling_group_instances: |
| 855 |
instance_facts[i["InstanceId"]] = { |
| 856 |
"health_status": i["HealthStatus"], |
| 857 |
"lifecycle_state": i["LifecycleState"], |
| 858 |
} |
| 859 |
if "LaunchConfigurationName" in i: |
| 860 |
instance_facts[i["InstanceId"]]["launch_config_name"] = i["LaunchConfigurationName"] |
| 861 |
elif "LaunchTemplate" in i: |
| 862 |
instance_facts[i["InstanceId"]]["launch_template"] = i["LaunchTemplate"] |
| 863 |
|
| 864 |
if i["HealthStatus"] == "Healthy" and i["LifecycleState"] == "InService": |
| 865 |
properties["viable_instances"] += 1 |
| 866 |
|
| 867 |
if i["HealthStatus"] == "Healthy": |
| 868 |
properties["healthy_instances"] += 1 |
| 869 |
else: |
| 870 |
properties["unhealthy_instances"] += 1 |
| 871 |
|
| 872 |
if i["LifecycleState"] == "InService": |
| 873 |
properties["in_service_instances"] += 1 |
| 874 |
if i["LifecycleState"] == "Terminating": |
| 875 |
properties["terminating_instances"] += 1 |
| 876 |
if i["LifecycleState"] == "Pending": |
| 877 |
properties["pending_instances"] += 1 |
| 878 |
else: |
| 879 |
properties["instances"] = [] |
| 880 |
|
| 881 |
properties["auto_scaling_group_name"] = autoscaling_group.get("AutoScalingGroupName") |
| 882 |
properties["auto_scaling_group_arn"] = autoscaling_group.get("AutoScalingGroupARN") |
| 883 |
properties["availability_zones"] = autoscaling_group.get("AvailabilityZones") |
| 884 |
properties["created_time"] = autoscaling_group.get("CreatedTime") |
| 885 |
properties["instance_facts"] = instance_facts |
| 886 |
properties["load_balancers"] = autoscaling_group.get("LoadBalancerNames") |
| 887 |
if "LaunchConfigurationName" in autoscaling_group: |
| 888 |
properties["launch_config_name"] = autoscaling_group.get("LaunchConfigurationName") |
| 889 |
else: |
| 890 |
properties["launch_template"] = autoscaling_group.get("LaunchTemplate") |
| 891 |
properties["tags"] = autoscaling_group.get("Tags") |
| 892 |
properties["max_instance_lifetime"] = autoscaling_group.get("MaxInstanceLifetime") |
| 893 |
properties["min_size"] = autoscaling_group.get("MinSize") |
| 894 |
properties["max_size"] = autoscaling_group.get("MaxSize") |
| 895 |
properties["desired_capacity"] = autoscaling_group.get("DesiredCapacity") |
| 896 |
properties["default_cooldown"] = autoscaling_group.get("DefaultCooldown") |
| 897 |
properties["healthcheck_grace_period"] = autoscaling_group.get("HealthCheckGracePeriod") |
| 898 |
properties["healthcheck_type"] = autoscaling_group.get("HealthCheckType") |
| 899 |
properties["termination_policies"] = autoscaling_group.get("TerminationPolicies") |
| 900 |
properties["target_group_arns"] = autoscaling_group.get("TargetGroupARNs") |
| 901 |
properties["vpc_zone_identifier"] = autoscaling_group.get("VPCZoneIdentifier") |
| 902 |
properties["protected_from_scale_in"] = autoscaling_group.get("NewInstancesProtectedFromScaleIn") |
| 903 |
raw_mixed_instance_object = autoscaling_group.get("MixedInstancesPolicy") |
| 904 |
if raw_mixed_instance_object: |
| 905 |
properties["mixed_instances_policy_full"] = camel_dict_to_snake_dict(raw_mixed_instance_object) |
| 906 |
properties["mixed_instances_policy"] = [ |
| 907 |
x["InstanceType"] for x in raw_mixed_instance_object.get("LaunchTemplate").get("Overrides") |
| 908 |
] |
| 909 |
|
| 910 |
metrics = autoscaling_group.get("EnabledMetrics") |
| 911 |
if metrics: |
| 912 |
metrics.sort(key=lambda x: x["Metric"]) |
| 913 |
properties["metrics_collection"] = metrics |
| 914 |
|
| 915 |
if properties["target_group_arns"]: |
| 916 |
elbv2_connection = module.client("elbv2") |
| 917 |
# Limit of 20 similar to https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeLoadBalancers.html |
| 918 |
tg_chunk_size = 20 |
| 919 |
properties["target_group_names"] = [] |
| 920 |
tg_chunks = [ |
| 921 |
properties["target_group_arns"][i: i + tg_chunk_size] |
| 922 |
for i in range(0, len(properties["target_group_arns"]), tg_chunk_size) |
| 923 |
] # fmt: skip |
| 924 |
for chunk in tg_chunks: |
| 925 |
properties["target_group_names"].extend( |
| 926 |
[tg["TargetGroupName"] for tg in describe_target_groups(elbv2_connection, TargetGroupArns=chunk)] |
| 927 |
) |
| 928 |
else: |
| 929 |
properties["target_group_names"] = [] |
| 930 |
|
| 931 |
return properties |
| 932 |
|
| 933 |
|
| 934 |
def get_launch_object(connection, ec2_connection): |
| 935 |
launch_object = dict() |
| 936 |
launch_config_name = module.params.get("launch_config_name") |
| 937 |
launch_template = module.params.get("launch_template") |
| 938 |
mixed_instances_policy = module.params.get("mixed_instances_policy") |
| 939 |
if launch_config_name is None and launch_template is None: |
| 940 |
return launch_object |
| 941 |
elif launch_config_name: |
| 942 |
try: |
| 943 |
launch_configs = describe_launch_configurations(connection, launch_config_name) |
| 944 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 945 |
module.fail_json_aws(e, msg="Failed to describe launch configurations") |
| 946 |
if len(launch_configs["LaunchConfigurations"]) == 0: |
| 947 |
module.fail_json(msg=f"No launch config found with name {launch_config_name}") |
| 948 |
launch_object = { |
| 949 |
"LaunchConfigurationName": launch_configs["LaunchConfigurations"][0]["LaunchConfigurationName"] |
| 950 |
} |
| 951 |
return launch_object |
| 952 |
elif launch_template: |
| 953 |
lt = describe_launch_templates(ec2_connection, launch_template)["LaunchTemplates"][0] |
| 954 |
if launch_template["version"] is not None: |
| 955 |
launch_object = { |
| 956 |
"LaunchTemplate": {"LaunchTemplateId": lt["LaunchTemplateId"], "Version": launch_template["version"]} |
| 957 |
} |
| 958 |
else: |
| 959 |
launch_object = { |
| 960 |
"LaunchTemplate": { |
| 961 |
"LaunchTemplateId": lt["LaunchTemplateId"], |
| 962 |
"Version": str(lt["LatestVersionNumber"]), |
| 963 |
} |
| 964 |
} |
| 965 |
|
| 966 |
if mixed_instances_policy: |
| 967 |
instance_types = mixed_instances_policy.get("instance_types", []) |
| 968 |
instances_distribution = mixed_instances_policy.get("instances_distribution", {}) |
| 969 |
policy = {"LaunchTemplate": {"LaunchTemplateSpecification": launch_object["LaunchTemplate"]}} |
| 970 |
if instance_types: |
| 971 |
policy["LaunchTemplate"]["Overrides"] = [] |
| 972 |
for instance_type in instance_types: |
| 973 |
instance_type_dict = {"InstanceType": instance_type} |
| 974 |
policy["LaunchTemplate"]["Overrides"].append(instance_type_dict) |
| 975 |
if instances_distribution: |
| 976 |
instances_distribution_params = scrub_none_parameters(instances_distribution) |
| 977 |
policy["InstancesDistribution"] = snake_dict_to_camel_dict( |
| 978 |
instances_distribution_params, capitalize_first=True |
| 979 |
) |
| 980 |
launch_object["MixedInstancesPolicy"] = policy |
| 981 |
return launch_object |
| 982 |
|
| 983 |
|
| 984 |
def elb_dreg(asg_connection, group_name, instance_id): |
| 985 |
as_group = describe_autoscaling_groups(asg_connection, group_name)[0] |
| 986 |
wait_timeout = module.params.get("wait_timeout") |
| 987 |
count = 1 |
| 988 |
if as_group["LoadBalancerNames"] and as_group["HealthCheckType"] == "ELB": |
| 989 |
elb_connection = module.client("elb") |
| 990 |
else: |
| 991 |
return |
| 992 |
|
| 993 |
for lb in as_group["LoadBalancerNames"]: |
| 994 |
deregister_lb_instances(elb_connection, lb, instance_id) |
| 995 |
module.debug(f"De-registering {instance_id} from ELB {lb}") |
| 996 |
|
| 997 |
wait_timeout = time.time() + wait_timeout |
| 998 |
while wait_timeout > time.time() and count > 0: |
| 999 |
count = 0 |
| 1000 |
for lb in as_group["LoadBalancerNames"]: |
| 1001 |
lb_instances = describe_instance_health(elb_connection, lb, []) |
| 1002 |
for i in lb_instances["InstanceStates"]: |
| 1003 |
if i["InstanceId"] == instance_id and i["State"] == "InService": |
| 1004 |
count += 1 |
| 1005 |
module.debug(f"{i['InstanceId']}: {i['State']}, {i['Description']}") |
| 1006 |
time.sleep(10) |
| 1007 |
|
| 1008 |
if wait_timeout <= time.time(): |
| 1009 |
# waiting took too long |
| 1010 |
module.fail_json(msg=f"Waited too long for instance to deregister. {time.asctime()}") |
| 1011 |
|
| 1012 |
|
| 1013 |
def elb_healthy(asg_connection, elb_connection, group_name): |
| 1014 |
healthy_instances = set() |
| 1015 |
as_group = describe_autoscaling_groups(asg_connection, group_name)[0] |
| 1016 |
props = get_properties(as_group) |
| 1017 |
# get healthy, inservice instances from ASG |
| 1018 |
instances = [] |
| 1019 |
for instance, settings in props["instance_facts"].items(): |
| 1020 |
if settings["lifecycle_state"] == "InService" and settings["health_status"] == "Healthy": |
| 1021 |
instances.append(dict(InstanceId=instance)) |
| 1022 |
module.debug(f"ASG considers the following instances InService and Healthy: {instances}") |
| 1023 |
module.debug("ELB instance status:") |
| 1024 |
lb_instances = list() |
| 1025 |
for lb in as_group.get("LoadBalancerNames"): |
| 1026 |
# we catch a race condition that sometimes happens if the instance exists in the ASG |
| 1027 |
# but has not yet show up in the ELB |
| 1028 |
try: |
| 1029 |
lb_instances = describe_instance_health(elb_connection, lb, instances) |
| 1030 |
except is_boto3_error_code("InvalidInstance"): |
| 1031 |
return None |
| 1032 |
except ( |
| 1033 |
botocore.exceptions.ClientError, |
| 1034 |
botocore.exceptions.BotoCoreError, |
| 1035 |
) as e: # pylint: disable=duplicate-except |
| 1036 |
module.fail_json_aws(e, msg="Failed to get load balancer.") |
| 1037 |
|
| 1038 |
for i in lb_instances.get("InstanceStates"): |
| 1039 |
if i["State"] == "InService": |
| 1040 |
healthy_instances.add(i["InstanceId"]) |
| 1041 |
module.debug(f"ELB Health State {i['InstanceId']}: {i['State']}") |
| 1042 |
return len(healthy_instances) |
| 1043 |
|
| 1044 |
|
| 1045 |
def tg_healthy(asg_connection, elbv2_connection, group_name): |
| 1046 |
healthy_instances = set() |
| 1047 |
as_group = describe_autoscaling_groups(asg_connection, group_name)[0] |
| 1048 |
props = get_properties(as_group) |
| 1049 |
# get healthy, inservice instances from ASG |
| 1050 |
instances = [] |
| 1051 |
for instance, settings in props["instance_facts"].items(): |
| 1052 |
if settings["lifecycle_state"] == "InService" and settings["health_status"] == "Healthy": |
| 1053 |
instances.append(dict(Id=instance)) |
| 1054 |
module.debug(f"ASG considers the following instances InService and Healthy: {instances}") |
| 1055 |
module.debug("Target Group instance status:") |
| 1056 |
tg_instances = list() |
| 1057 |
for tg in as_group.get("TargetGroupARNs"): |
| 1058 |
# we catch a race condition that sometimes happens if the instance exists in the ASG |
| 1059 |
# but has not yet show up in the ELB |
| 1060 |
try: |
| 1061 |
tg_instances = describe_target_health(elbv2_connection, tg, instances) |
| 1062 |
except is_boto3_error_code("InvalidInstance"): |
| 1063 |
return None |
| 1064 |
except ( |
| 1065 |
botocore.exceptions.ClientError, |
| 1066 |
botocore.exceptions.BotoCoreError, |
| 1067 |
) as e: # pylint: disable=duplicate-except |
| 1068 |
module.fail_json_aws(e, msg="Failed to get target group.") |
| 1069 |
|
| 1070 |
for i in tg_instances.get("TargetHealthDescriptions"): |
| 1071 |
if i["TargetHealth"]["State"] == "healthy": |
| 1072 |
healthy_instances.add(i["Target"]["Id"]) |
| 1073 |
module.debug(f"Target Group Health State {i['Target']['Id']}: {i['TargetHealth']['State']}") |
| 1074 |
return len(healthy_instances) |
| 1075 |
|
| 1076 |
|
| 1077 |
def wait_for_elb(asg_connection, group_name): |
| 1078 |
wait_timeout = module.params.get("wait_timeout") |
| 1079 |
|
| 1080 |
# if the health_check_type is ELB, we want to query the ELBs directly for instance |
| 1081 |
# status as to avoid health_check_grace period that is awarded to ASG instances |
| 1082 |
as_group = describe_autoscaling_groups(asg_connection, group_name)[0] |
| 1083 |
|
| 1084 |
if as_group.get("LoadBalancerNames") and as_group.get("HealthCheckType") == "ELB": |
| 1085 |
module.debug("Waiting for ELB to consider instances healthy.") |
| 1086 |
elb_connection = module.client("elb") |
| 1087 |
|
| 1088 |
wait_timeout = time.time() + wait_timeout |
| 1089 |
healthy_instances = elb_healthy(asg_connection, elb_connection, group_name) |
| 1090 |
|
| 1091 |
while healthy_instances < as_group.get("MinSize") and wait_timeout > time.time(): |
| 1092 |
healthy_instances = elb_healthy(asg_connection, elb_connection, group_name) |
| 1093 |
module.debug(f"ELB thinks {healthy_instances} instances are healthy.") |
| 1094 |
time.sleep(10) |
| 1095 |
if wait_timeout <= time.time(): |
| 1096 |
# waiting took too long |
| 1097 |
module.fail_json(msg=f"Waited too long for ELB instances to be healthy. {time.asctime()}") |
| 1098 |
module.debug(f"Waiting complete. ELB thinks {healthy_instances} instances are healthy.") |
| 1099 |
|
| 1100 |
|
| 1101 |
def wait_for_target_group(asg_connection, group_name): |
| 1102 |
wait_timeout = module.params.get("wait_timeout") |
| 1103 |
|
| 1104 |
# if the health_check_type is ELB, we want to query the ELBs directly for instance |
| 1105 |
# status as to avoid health_check_grace period that is awarded to ASG instances |
| 1106 |
as_group = describe_autoscaling_groups(asg_connection, group_name)[0] |
| 1107 |
|
| 1108 |
if as_group.get("TargetGroupARNs") and as_group.get("HealthCheckType") == "ELB": |
| 1109 |
module.debug("Waiting for Target Group to consider instances healthy.") |
| 1110 |
elbv2_connection = module.client("elbv2") |
| 1111 |
|
| 1112 |
wait_timeout = time.time() + wait_timeout |
| 1113 |
healthy_instances = tg_healthy(asg_connection, elbv2_connection, group_name) |
| 1114 |
|
| 1115 |
while healthy_instances < as_group.get("MinSize") and wait_timeout > time.time(): |
| 1116 |
healthy_instances = tg_healthy(asg_connection, elbv2_connection, group_name) |
| 1117 |
module.debug(f"Target Group thinks {healthy_instances} instances are healthy.") |
| 1118 |
time.sleep(10) |
| 1119 |
if wait_timeout <= time.time(): |
| 1120 |
# waiting took too long |
| 1121 |
module.fail_json(msg=f"Waited too long for ELB instances to be healthy. {time.asctime()}") |
| 1122 |
module.debug(f"Waiting complete. Target Group thinks {healthy_instances} instances are healthy.") |
| 1123 |
|
| 1124 |
|
| 1125 |
def suspend_processes(ec2_connection, as_group): |
| 1126 |
processes_to_suspend = set(module.params.get("suspend_processes")) |
| 1127 |
|
| 1128 |
try: |
| 1129 |
suspended_processes = set([p["ProcessName"] for p in as_group["SuspendedProcesses"]]) |
| 1130 |
except AttributeError: |
| 1131 |
# New ASG being created, no suspended_processes defined yet |
| 1132 |
suspended_processes = set() |
| 1133 |
|
| 1134 |
if processes_to_suspend == suspended_processes: |
| 1135 |
return False |
| 1136 |
|
| 1137 |
resume_processes = list(suspended_processes - processes_to_suspend) |
| 1138 |
if resume_processes: |
| 1139 |
resume_asg_processes(ec2_connection, module.params.get("name"), resume_processes) |
| 1140 |
|
| 1141 |
if processes_to_suspend: |
| 1142 |
suspend_asg_processes(ec2_connection, module.params.get("name"), list(processes_to_suspend)) |
| 1143 |
|
| 1144 |
return True |
| 1145 |
|
| 1146 |
|
| 1147 |
def create_autoscaling_group(connection): |
| 1148 |
group_name = module.params.get("name") |
| 1149 |
load_balancers = module.params["load_balancers"] |
| 1150 |
target_group_arns = module.params["target_group_arns"] |
| 1151 |
availability_zones = module.params["availability_zones"] |
| 1152 |
launch_template = module.params.get("launch_template") |
| 1153 |
min_size = module.params["min_size"] |
| 1154 |
max_size = module.params["max_size"] |
| 1155 |
max_instance_lifetime = module.params.get("max_instance_lifetime") |
| 1156 |
placement_group = module.params.get("placement_group") |
| 1157 |
desired_capacity = module.params.get("desired_capacity") |
| 1158 |
vpc_zone_identifier = module.params.get("vpc_zone_identifier") |
| 1159 |
set_tags = module.params.get("tags") |
| 1160 |
purge_tags = module.params.get("purge_tags") |
| 1161 |
protected_from_scale_in = module.params.get("protected_from_scale_in") |
| 1162 |
health_check_period = module.params.get("health_check_period") |
| 1163 |
health_check_type = module.params.get("health_check_type") |
| 1164 |
default_cooldown = module.params.get("default_cooldown") |
| 1165 |
wait_for_instances = module.params.get("wait_for_instances") |
| 1166 |
wait_timeout = module.params.get("wait_timeout") |
| 1167 |
termination_policies = module.params.get("termination_policies") |
| 1168 |
notification_topic = module.params.get("notification_topic") |
| 1169 |
notification_types = module.params.get("notification_types") |
| 1170 |
metrics_collection = module.params.get("metrics_collection") |
| 1171 |
metrics_granularity = module.params.get("metrics_granularity") |
| 1172 |
metrics_list = module.params.get("metrics_list") |
| 1173 |
|
| 1174 |
try: |
| 1175 |
as_groups = describe_autoscaling_groups(connection, group_name) |
| 1176 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1177 |
module.fail_json_aws(e, msg="Failed to describe auto scaling groups.") |
| 1178 |
|
| 1179 |
ec2_connection = module.client("ec2") |
| 1180 |
|
| 1181 |
if vpc_zone_identifier: |
| 1182 |
vpc_zone_identifier = ",".join(vpc_zone_identifier) |
| 1183 |
|
| 1184 |
asg_tags = [] |
| 1185 |
for tag in set_tags: |
| 1186 |
for k, v in tag.items(): |
| 1187 |
if k != "propagate_at_launch": |
| 1188 |
asg_tags.append( |
| 1189 |
dict( |
| 1190 |
Key=k, |
| 1191 |
Value=to_native(v), |
| 1192 |
PropagateAtLaunch=bool(tag.get("propagate_at_launch", True)), |
| 1193 |
ResourceType="auto-scaling-group", |
| 1194 |
ResourceId=group_name, |
| 1195 |
) |
| 1196 |
) |
| 1197 |
if not as_groups: |
| 1198 |
if module.check_mode: |
| 1199 |
module.exit_json(changed=True, msg="Would have created AutoScalingGroup if not in check_mode.") |
| 1200 |
|
| 1201 |
if not vpc_zone_identifier and not availability_zones: |
| 1202 |
availability_zones = module.params["availability_zones"] = [ |
| 1203 |
zone["ZoneName"] for zone in ec2_connection.describe_availability_zones()["AvailabilityZones"] |
| 1204 |
] |
| 1205 |
|
| 1206 |
enforce_required_arguments_for_create() |
| 1207 |
|
| 1208 |
if desired_capacity is None: |
| 1209 |
desired_capacity = min_size |
| 1210 |
ag = dict( |
| 1211 |
AutoScalingGroupName=group_name, |
| 1212 |
MinSize=min_size, |
| 1213 |
MaxSize=max_size, |
| 1214 |
DesiredCapacity=desired_capacity, |
| 1215 |
Tags=asg_tags, |
| 1216 |
HealthCheckGracePeriod=health_check_period, |
| 1217 |
HealthCheckType=health_check_type, |
| 1218 |
DefaultCooldown=default_cooldown, |
| 1219 |
TerminationPolicies=termination_policies, |
| 1220 |
) |
| 1221 |
if vpc_zone_identifier: |
| 1222 |
ag["VPCZoneIdentifier"] = vpc_zone_identifier |
| 1223 |
if availability_zones: |
| 1224 |
ag["AvailabilityZones"] = availability_zones |
| 1225 |
if placement_group: |
| 1226 |
ag["PlacementGroup"] = placement_group |
| 1227 |
if load_balancers: |
| 1228 |
ag["LoadBalancerNames"] = load_balancers |
| 1229 |
if target_group_arns: |
| 1230 |
ag["TargetGroupARNs"] = target_group_arns |
| 1231 |
if max_instance_lifetime: |
| 1232 |
ag["MaxInstanceLifetime"] = max_instance_lifetime |
| 1233 |
if protected_from_scale_in is None: |
| 1234 |
ag["NewInstancesProtectedFromScaleIn"] = False |
| 1235 |
else: |
| 1236 |
ag["NewInstancesProtectedFromScaleIn"] = bool(protected_from_scale_in) |
| 1237 |
launch_object = get_launch_object(connection, ec2_connection) |
| 1238 |
if "LaunchConfigurationName" in launch_object: |
| 1239 |
ag["LaunchConfigurationName"] = launch_object["LaunchConfigurationName"] |
| 1240 |
elif "LaunchTemplate" in launch_object: |
| 1241 |
if "MixedInstancesPolicy" in launch_object: |
| 1242 |
ag["MixedInstancesPolicy"] = launch_object["MixedInstancesPolicy"] |
| 1243 |
else: |
| 1244 |
ag["LaunchTemplate"] = launch_object["LaunchTemplate"] |
| 1245 |
else: |
| 1246 |
module.fail_json(msg="Missing LaunchConfigurationName or LaunchTemplate") |
| 1247 |
|
| 1248 |
try: |
| 1249 |
create_asg(connection, **ag) |
| 1250 |
if metrics_collection: |
| 1251 |
connection.enable_metrics_collection( |
| 1252 |
AutoScalingGroupName=group_name, Granularity=metrics_granularity, Metrics=metrics_list |
| 1253 |
) |
| 1254 |
|
| 1255 |
all_ag = describe_autoscaling_groups(connection, group_name) |
| 1256 |
if len(all_ag) == 0: |
| 1257 |
module.fail_json(msg=f"No auto scaling group found with the name {group_name}") |
| 1258 |
as_group = all_ag[0] |
| 1259 |
suspend_processes(connection, as_group) |
| 1260 |
if wait_for_instances: |
| 1261 |
wait_for_new_inst(connection, group_name, wait_timeout, desired_capacity, "viable_instances") |
| 1262 |
if load_balancers: |
| 1263 |
wait_for_elb(connection, group_name) |
| 1264 |
# Wait for target group health if target group(s)defined |
| 1265 |
if target_group_arns: |
| 1266 |
wait_for_target_group(connection, group_name) |
| 1267 |
if notification_topic: |
| 1268 |
put_notification_config(connection, group_name, notification_topic, notification_types) |
| 1269 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1270 |
asg_properties = get_properties(as_group) |
| 1271 |
changed = True |
| 1272 |
return changed, asg_properties |
| 1273 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1274 |
module.fail_json_aws(e, msg="Failed to create Autoscaling Group.") |
| 1275 |
else: |
| 1276 |
if module.check_mode: |
| 1277 |
module.exit_json(changed=True, msg="Would have modified AutoScalingGroup if required if not in check_mode.") |
| 1278 |
|
| 1279 |
as_group = as_groups[0] |
| 1280 |
initial_asg_properties = get_properties(as_group) |
| 1281 |
changed = False |
| 1282 |
|
| 1283 |
if suspend_processes(connection, as_group): |
| 1284 |
changed = True |
| 1285 |
|
| 1286 |
# process tag changes |
| 1287 |
have_tags = as_group.get("Tags") |
| 1288 |
want_tags = asg_tags |
| 1289 |
if purge_tags and not want_tags and have_tags: |
| 1290 |
connection.delete_tags(Tags=list(have_tags)) |
| 1291 |
|
| 1292 |
if len(set_tags) > 0: |
| 1293 |
if have_tags: |
| 1294 |
have_tags.sort(key=lambda x: x["Key"]) |
| 1295 |
if want_tags: |
| 1296 |
want_tags.sort(key=lambda x: x["Key"]) |
| 1297 |
dead_tags = [] |
| 1298 |
have_tag_keyvals = [x["Key"] for x in have_tags] |
| 1299 |
want_tag_keyvals = [x["Key"] for x in want_tags] |
| 1300 |
|
| 1301 |
for dead_tag in set(have_tag_keyvals).difference(want_tag_keyvals): |
| 1302 |
changed = True |
| 1303 |
if purge_tags: |
| 1304 |
dead_tags.append( |
| 1305 |
dict( |
| 1306 |
ResourceId=as_group["AutoScalingGroupName"], ResourceType="auto-scaling-group", Key=dead_tag |
| 1307 |
) |
| 1308 |
) |
| 1309 |
have_tags = [have_tag for have_tag in have_tags if have_tag["Key"] != dead_tag] |
| 1310 |
|
| 1311 |
if dead_tags: |
| 1312 |
connection.delete_tags(Tags=dead_tags) |
| 1313 |
|
| 1314 |
zipped = zip(have_tags, want_tags) |
| 1315 |
if len(have_tags) != len(want_tags) or not all(x == y for x, y in zipped): |
| 1316 |
changed = True |
| 1317 |
connection.create_or_update_tags(Tags=asg_tags) |
| 1318 |
|
| 1319 |
# Handle load balancer attachments/detachments |
| 1320 |
# Attach load balancers if they are specified but none currently exist |
| 1321 |
if load_balancers and not as_group["LoadBalancerNames"]: |
| 1322 |
changed = True |
| 1323 |
try: |
| 1324 |
attach_load_balancers(connection, group_name, load_balancers) |
| 1325 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1326 |
module.fail_json_aws(e, msg="Failed to update Autoscaling Group.") |
| 1327 |
|
| 1328 |
# Update load balancers if they are specified and one or more already exists |
| 1329 |
elif as_group["LoadBalancerNames"]: |
| 1330 |
change_load_balancers = load_balancers is not None |
| 1331 |
# Get differences |
| 1332 |
if not load_balancers: |
| 1333 |
load_balancers = list() |
| 1334 |
wanted_elbs = set(load_balancers) |
| 1335 |
|
| 1336 |
has_elbs = set(as_group["LoadBalancerNames"]) |
| 1337 |
# check if all requested are already existing |
| 1338 |
if has_elbs - wanted_elbs and change_load_balancers: |
| 1339 |
# if wanted contains less than existing, then we need to delete some |
| 1340 |
elbs_to_detach = has_elbs.difference(wanted_elbs) |
| 1341 |
if elbs_to_detach: |
| 1342 |
changed = True |
| 1343 |
try: |
| 1344 |
detach_load_balancers(connection, group_name, list(elbs_to_detach)) |
| 1345 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1346 |
module.fail_json_aws(e, msg=f"Failed to detach load balancers {elbs_to_detach}") |
| 1347 |
if wanted_elbs - has_elbs: |
| 1348 |
# if has contains less than wanted, then we need to add some |
| 1349 |
elbs_to_attach = wanted_elbs.difference(has_elbs) |
| 1350 |
if elbs_to_attach: |
| 1351 |
changed = True |
| 1352 |
try: |
| 1353 |
attach_load_balancers(connection, group_name, list(elbs_to_attach)) |
| 1354 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1355 |
module.fail_json_aws(e, msg=f"Failed to attach load balancers {elbs_to_attach}") |
| 1356 |
|
| 1357 |
# Handle target group attachments/detachments |
| 1358 |
# Attach target groups if they are specified but none currently exist |
| 1359 |
if target_group_arns and not as_group["TargetGroupARNs"]: |
| 1360 |
changed = True |
| 1361 |
try: |
| 1362 |
attach_lb_target_groups(connection, group_name, target_group_arns) |
| 1363 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1364 |
module.fail_json_aws(e, msg="Failed to update Autoscaling Group.") |
| 1365 |
# Update target groups if they are specified and one or more already exists |
| 1366 |
elif target_group_arns is not None and as_group["TargetGroupARNs"]: |
| 1367 |
# Get differences |
| 1368 |
wanted_tgs = set(target_group_arns) |
| 1369 |
has_tgs = set(as_group["TargetGroupARNs"]) |
| 1370 |
|
| 1371 |
tgs_to_detach = has_tgs.difference(wanted_tgs) |
| 1372 |
if tgs_to_detach: |
| 1373 |
changed = True |
| 1374 |
try: |
| 1375 |
detach_lb_target_groups(connection, group_name, list(tgs_to_detach)) |
| 1376 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1377 |
module.fail_json_aws(e, msg=f"Failed to detach load balancer target groups {tgs_to_detach}") |
| 1378 |
|
| 1379 |
tgs_to_attach = wanted_tgs.difference(has_tgs) |
| 1380 |
if tgs_to_attach: |
| 1381 |
changed = True |
| 1382 |
try: |
| 1383 |
attach_lb_target_groups(connection, group_name, list(tgs_to_attach)) |
| 1384 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError): |
| 1385 |
module.fail_json(msg=f"Failed to attach load balancer target groups {tgs_to_attach}") |
| 1386 |
|
| 1387 |
# check for attributes that aren't required for updating an existing ASG |
| 1388 |
# check if min_size/max_size/desired capacity have been specified and if not use ASG values |
| 1389 |
if min_size is None: |
| 1390 |
min_size = as_group["MinSize"] |
| 1391 |
if max_size is None: |
| 1392 |
max_size = as_group["MaxSize"] |
| 1393 |
if desired_capacity is None: |
| 1394 |
desired_capacity = as_group["DesiredCapacity"] |
| 1395 |
if protected_from_scale_in is None: |
| 1396 |
protected_from_scale_in = as_group["NewInstancesProtectedFromScaleIn"] |
| 1397 |
ag = dict( |
| 1398 |
AutoScalingGroupName=group_name, |
| 1399 |
MinSize=min_size, |
| 1400 |
MaxSize=max_size, |
| 1401 |
DesiredCapacity=desired_capacity, |
| 1402 |
NewInstancesProtectedFromScaleIn=protected_from_scale_in, |
| 1403 |
HealthCheckGracePeriod=health_check_period, |
| 1404 |
HealthCheckType=health_check_type, |
| 1405 |
DefaultCooldown=default_cooldown, |
| 1406 |
TerminationPolicies=termination_policies, |
| 1407 |
) |
| 1408 |
|
| 1409 |
# Get the launch object (config or template) if one is provided in args or use the existing one attached to ASG if not. |
| 1410 |
launch_object = get_launch_object(connection, ec2_connection) |
| 1411 |
if "LaunchConfigurationName" in launch_object: |
| 1412 |
ag["LaunchConfigurationName"] = launch_object["LaunchConfigurationName"] |
| 1413 |
elif "LaunchTemplate" in launch_object: |
| 1414 |
if "MixedInstancesPolicy" in launch_object: |
| 1415 |
ag["MixedInstancesPolicy"] = launch_object["MixedInstancesPolicy"] |
| 1416 |
else: |
| 1417 |
ag["LaunchTemplate"] = launch_object["LaunchTemplate"] |
| 1418 |
else: |
| 1419 |
try: |
| 1420 |
ag["LaunchConfigurationName"] = as_group["LaunchConfigurationName"] |
| 1421 |
except KeyError: |
| 1422 |
launch_template = as_group["LaunchTemplate"] |
| 1423 |
# Prefer LaunchTemplateId over Name as it's more specific. Only one can be used for update_asg. |
| 1424 |
ag["LaunchTemplate"] = { |
| 1425 |
"LaunchTemplateId": launch_template["LaunchTemplateId"], |
| 1426 |
"Version": launch_template["Version"], |
| 1427 |
} |
| 1428 |
|
| 1429 |
if availability_zones: |
| 1430 |
ag["AvailabilityZones"] = availability_zones |
| 1431 |
if vpc_zone_identifier: |
| 1432 |
ag["VPCZoneIdentifier"] = vpc_zone_identifier |
| 1433 |
if max_instance_lifetime is not None: |
| 1434 |
ag["MaxInstanceLifetime"] = max_instance_lifetime |
| 1435 |
|
| 1436 |
try: |
| 1437 |
update_asg(connection, **ag) |
| 1438 |
|
| 1439 |
if metrics_collection: |
| 1440 |
connection.enable_metrics_collection( |
| 1441 |
AutoScalingGroupName=group_name, Granularity=metrics_granularity, Metrics=metrics_list |
| 1442 |
) |
| 1443 |
else: |
| 1444 |
connection.disable_metrics_collection(AutoScalingGroupName=group_name, Metrics=metrics_list) |
| 1445 |
|
| 1446 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1447 |
module.fail_json_aws(e, msg="Failed to update autoscaling group") |
| 1448 |
|
| 1449 |
if notification_topic: |
| 1450 |
try: |
| 1451 |
put_notification_config(connection, group_name, notification_topic, notification_types) |
| 1452 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1453 |
module.fail_json_aws(e, msg="Failed to update Autoscaling Group notifications.") |
| 1454 |
if wait_for_instances: |
| 1455 |
wait_for_new_inst(connection, group_name, wait_timeout, desired_capacity, "viable_instances") |
| 1456 |
# Wait for ELB health if ELB(s)defined |
| 1457 |
if load_balancers: |
| 1458 |
module.debug("\tWAITING FOR ELB HEALTH") |
| 1459 |
wait_for_elb(connection, group_name) |
| 1460 |
# Wait for target group health if target group(s)defined |
| 1461 |
|
| 1462 |
if target_group_arns: |
| 1463 |
module.debug("\tWAITING FOR TG HEALTH") |
| 1464 |
wait_for_target_group(connection, group_name) |
| 1465 |
|
| 1466 |
try: |
| 1467 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1468 |
asg_properties = get_properties(as_group) |
| 1469 |
if asg_properties != initial_asg_properties: |
| 1470 |
changed = True |
| 1471 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1472 |
module.fail_json_aws(e, msg="Failed to read existing Autoscaling Groups.") |
| 1473 |
return changed, asg_properties |
| 1474 |
|
| 1475 |
|
| 1476 |
def delete_autoscaling_group(connection): |
| 1477 |
group_name = module.params.get("name") |
| 1478 |
notification_topic = module.params.get("notification_topic") |
| 1479 |
wait_for_instances = module.params.get("wait_for_instances") |
| 1480 |
wait_timeout = module.params.get("wait_timeout") |
| 1481 |
|
| 1482 |
if notification_topic: |
| 1483 |
del_notification_config(connection, group_name, notification_topic) |
| 1484 |
groups = describe_autoscaling_groups(connection, group_name) |
| 1485 |
if groups: |
| 1486 |
if module.check_mode: |
| 1487 |
module.exit_json(changed=True, msg="Would have deleted AutoScalingGroup if not in check_mode.") |
| 1488 |
wait_timeout = time.time() + wait_timeout |
| 1489 |
if not wait_for_instances: |
| 1490 |
delete_asg(connection, group_name, force_delete=True) |
| 1491 |
else: |
| 1492 |
updated_params = dict(AutoScalingGroupName=group_name, MinSize=0, MaxSize=0, DesiredCapacity=0) |
| 1493 |
update_asg(connection, **updated_params) |
| 1494 |
instances = True |
| 1495 |
while instances and wait_for_instances and wait_timeout >= time.time(): |
| 1496 |
tmp_groups = describe_autoscaling_groups(connection, group_name) |
| 1497 |
if tmp_groups: |
| 1498 |
tmp_group = tmp_groups[0] |
| 1499 |
if not tmp_group.get("Instances"): |
| 1500 |
instances = False |
| 1501 |
time.sleep(10) |
| 1502 |
|
| 1503 |
if wait_timeout <= time.time(): |
| 1504 |
# waiting took too long |
| 1505 |
module.fail_json(msg=f"Waited too long for old instances to terminate. {time.asctime()}") |
| 1506 |
|
| 1507 |
delete_asg(connection, group_name, force_delete=False) |
| 1508 |
while describe_autoscaling_groups(connection, group_name) and wait_timeout >= time.time(): |
| 1509 |
time.sleep(5) |
| 1510 |
if wait_timeout <= time.time(): |
| 1511 |
# waiting took too long |
| 1512 |
module.fail_json(msg=f"Waited too long for ASG to delete. {time.asctime()}") |
| 1513 |
return True |
| 1514 |
|
| 1515 |
return False |
| 1516 |
|
| 1517 |
|
| 1518 |
def get_chunks(objects, chunk_size): |
| 1519 |
for i in range(0, len(objects), chunk_size): |
| 1520 |
yield objects[i:i + chunk_size] # fmt: skip |
| 1521 |
|
| 1522 |
|
| 1523 |
def update_size(connection, group, max_size, min_size, dc, protected_from_scale_in): |
| 1524 |
module.debug("setting ASG sizes") |
| 1525 |
module.debug( |
| 1526 |
f"minimum size: {min_size}, desired_capacity: {dc}, max size: {max_size}, protected from scale in: {protected_from_scale_in}" |
| 1527 |
) |
| 1528 |
updated_group = dict() |
| 1529 |
updated_group["AutoScalingGroupName"] = group["AutoScalingGroupName"] |
| 1530 |
updated_group["MinSize"] = min_size |
| 1531 |
updated_group["MaxSize"] = max_size |
| 1532 |
updated_group["DesiredCapacity"] = dc |
| 1533 |
if protected_from_scale_in is not None: |
| 1534 |
updated_group["NewInstancesProtectedFromScaleIn"] = bool(protected_from_scale_in) |
| 1535 |
update_asg(connection, **updated_group) |
| 1536 |
|
| 1537 |
|
| 1538 |
def replace(connection): |
| 1539 |
batch_size = module.params.get("replace_batch_size") |
| 1540 |
wait_timeout = module.params.get("wait_timeout") |
| 1541 |
wait_for_instances = module.params.get("wait_for_instances") |
| 1542 |
group_name = module.params.get("name") |
| 1543 |
max_size = module.params.get("max_size") |
| 1544 |
min_size = module.params.get("min_size") |
| 1545 |
protected_from_scale_in = module.params.get("protected_from_scale_in") |
| 1546 |
desired_capacity = module.params.get("desired_capacity") |
| 1547 |
launch_config_name = module.params.get("launch_config_name") |
| 1548 |
|
| 1549 |
# Required to maintain the default value being set to 'true' |
| 1550 |
if launch_config_name: |
| 1551 |
lc_check = module.params.get("lc_check") |
| 1552 |
else: |
| 1553 |
lc_check = False |
| 1554 |
# Mirror above behavior for Launch Templates |
| 1555 |
launch_template = module.params.get("launch_template") |
| 1556 |
if launch_template: |
| 1557 |
lt_check = module.params.get("lt_check") |
| 1558 |
else: |
| 1559 |
lt_check = False |
| 1560 |
replace_instances = module.params.get("replace_instances") |
| 1561 |
replace_all_instances = module.params.get("replace_all_instances") |
| 1562 |
|
| 1563 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1564 |
if desired_capacity is None: |
| 1565 |
desired_capacity = as_group["DesiredCapacity"] |
| 1566 |
|
| 1567 |
if wait_for_instances: |
| 1568 |
wait_for_new_inst(connection, group_name, wait_timeout, as_group["MinSize"], "viable_instances") |
| 1569 |
|
| 1570 |
props = get_properties(as_group) |
| 1571 |
instances = props["instances"] |
| 1572 |
if replace_all_instances: |
| 1573 |
# If replacing all instances, then set replace_instances to current set |
| 1574 |
# This allows replace_instances and replace_all_instances to behave same |
| 1575 |
replace_instances = instances |
| 1576 |
if replace_instances: |
| 1577 |
instances = replace_instances |
| 1578 |
|
| 1579 |
# check to see if instances are replaceable if checking launch configs |
| 1580 |
if launch_config_name: |
| 1581 |
new_instances, old_instances = get_instances_by_launch_config(props, lc_check, instances) |
| 1582 |
elif launch_template: |
| 1583 |
new_instances, old_instances = get_instances_by_launch_template(props, lt_check, instances) |
| 1584 |
|
| 1585 |
num_new_inst_needed = desired_capacity - len(new_instances) |
| 1586 |
|
| 1587 |
if lc_check or lt_check: |
| 1588 |
if num_new_inst_needed == 0 and old_instances: |
| 1589 |
module.debug("No new instances needed, but old instances are present. Removing old instances") |
| 1590 |
terminate_batch(connection, old_instances, instances, True) |
| 1591 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1592 |
props = get_properties(as_group) |
| 1593 |
changed = True |
| 1594 |
return changed, props |
| 1595 |
|
| 1596 |
# we don't want to spin up extra instances if not necessary |
| 1597 |
if num_new_inst_needed < batch_size: |
| 1598 |
module.debug(f"Overriding batch size to {num_new_inst_needed}") |
| 1599 |
batch_size = num_new_inst_needed |
| 1600 |
|
| 1601 |
if not old_instances: |
| 1602 |
changed = False |
| 1603 |
return changed, props |
| 1604 |
|
| 1605 |
# check if min_size/max_size/desired capacity have been specified and if not use ASG values |
| 1606 |
if min_size is None: |
| 1607 |
min_size = as_group["MinSize"] |
| 1608 |
if max_size is None: |
| 1609 |
max_size = as_group["MaxSize"] |
| 1610 |
|
| 1611 |
# set temporary settings and wait for them to be reached |
| 1612 |
# This should get overwritten if the number of instances left is less than the batch size. |
| 1613 |
|
| 1614 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1615 |
update_size( |
| 1616 |
connection, |
| 1617 |
as_group, |
| 1618 |
max_size + batch_size, |
| 1619 |
min_size + batch_size, |
| 1620 |
desired_capacity + batch_size, |
| 1621 |
protected_from_scale_in, |
| 1622 |
) |
| 1623 |
|
| 1624 |
if wait_for_instances: |
| 1625 |
wait_for_new_inst(connection, group_name, wait_timeout, as_group["MinSize"] + batch_size, "viable_instances") |
| 1626 |
wait_for_elb(connection, group_name) |
| 1627 |
wait_for_target_group(connection, group_name) |
| 1628 |
|
| 1629 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1630 |
props = get_properties(as_group) |
| 1631 |
instances = props["instances"] |
| 1632 |
if replace_instances: |
| 1633 |
instances = replace_instances |
| 1634 |
|
| 1635 |
module.debug("beginning main loop") |
| 1636 |
for i in get_chunks(instances, batch_size): |
| 1637 |
# break out of this loop if we have enough new instances |
| 1638 |
break_early, desired_size, term_instances = terminate_batch(connection, i, instances, False) |
| 1639 |
|
| 1640 |
if wait_for_instances: |
| 1641 |
wait_for_term_inst(connection, term_instances) |
| 1642 |
wait_for_new_inst(connection, group_name, wait_timeout, desired_size, "viable_instances") |
| 1643 |
wait_for_elb(connection, group_name) |
| 1644 |
wait_for_target_group(connection, group_name) |
| 1645 |
|
| 1646 |
if break_early: |
| 1647 |
module.debug("breaking loop") |
| 1648 |
break |
| 1649 |
|
| 1650 |
update_size(connection, as_group, max_size, min_size, desired_capacity, protected_from_scale_in) |
| 1651 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1652 |
asg_properties = get_properties(as_group) |
| 1653 |
module.debug("Rolling update complete.") |
| 1654 |
changed = True |
| 1655 |
return changed, asg_properties |
| 1656 |
|
| 1657 |
|
| 1658 |
def detach(connection): |
| 1659 |
group_name = module.params.get("name") |
| 1660 |
detach_instances = module.params.get("detach_instances") |
| 1661 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1662 |
decrement_desired_capacity = module.params.get("decrement_desired_capacity") |
| 1663 |
min_size = module.params.get("min_size") |
| 1664 |
props = get_properties(as_group) |
| 1665 |
instances = props["instances"] |
| 1666 |
|
| 1667 |
# check if provided instance exists in asg, create list of instances to detach which exist in asg |
| 1668 |
instances_to_detach = [] |
| 1669 |
for instance_id in detach_instances: |
| 1670 |
if instance_id in instances: |
| 1671 |
instances_to_detach.append(instance_id) |
| 1672 |
|
| 1673 |
# check if setting decrement_desired_capacity will make desired_capacity smaller |
| 1674 |
# than the currently set minimum size in ASG configuration |
| 1675 |
if decrement_desired_capacity: |
| 1676 |
decremented_desired_capacity = len(instances) - len(instances_to_detach) |
| 1677 |
if min_size and min_size > decremented_desired_capacity: |
| 1678 |
module.fail_json( |
| 1679 |
msg=( |
| 1680 |
"Detaching instance(s) with 'decrement_desired_capacity' flag set reduces number of instances to" |
| 1681 |
f" {decremented_desired_capacity} which is below current min_size {min_size}, please update" |
| 1682 |
" AutoScalingGroup Sizes properly." |
| 1683 |
) |
| 1684 |
) |
| 1685 |
|
| 1686 |
if instances_to_detach: |
| 1687 |
try: |
| 1688 |
detach_asg_instances(connection, instances_to_detach, group_name, decrement_desired_capacity) |
| 1689 |
except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e: |
| 1690 |
module.fail_json_aws(e, msg="Failed to detach instances from AutoScaling Group") |
| 1691 |
|
| 1692 |
asg_properties = get_properties(as_group) |
| 1693 |
return True, asg_properties |
| 1694 |
|
| 1695 |
|
| 1696 |
def get_instances_by_launch_config(props, lc_check, initial_instances): |
| 1697 |
new_instances = [] |
| 1698 |
old_instances = [] |
| 1699 |
# old instances are those that have the old launch config |
| 1700 |
if lc_check: |
| 1701 |
for i in props["instances"]: |
| 1702 |
# Check if migrating from launch_template to launch_config first |
| 1703 |
if "launch_template" in props["instance_facts"][i]: |
| 1704 |
old_instances.append(i) |
| 1705 |
elif props["instance_facts"][i].get("launch_config_name") == props["launch_config_name"]: |
| 1706 |
new_instances.append(i) |
| 1707 |
else: |
| 1708 |
old_instances.append(i) |
| 1709 |
|
| 1710 |
else: |
| 1711 |
module.debug(f"Comparing initial instances with current: {(*initial_instances,)}") |
| 1712 |
for i in props["instances"]: |
| 1713 |
if i not in initial_instances: |
| 1714 |
new_instances.append(i) |
| 1715 |
else: |
| 1716 |
old_instances.append(i) |
| 1717 |
|
| 1718 |
module.debug(f"New instances: {len(new_instances)}, {(*new_instances,)}") |
| 1719 |
module.debug(f"Old instances: {len(old_instances)}, {(*old_instances,)}") |
| 1720 |
|
| 1721 |
return new_instances, old_instances |
| 1722 |
|
| 1723 |
|
| 1724 |
def get_instances_by_launch_template(props, lt_check, initial_instances): |
| 1725 |
new_instances = [] |
| 1726 |
old_instances = [] |
| 1727 |
# old instances are those that have the old launch template or version of the same launch template |
| 1728 |
if lt_check: |
| 1729 |
for i in props["instances"]: |
| 1730 |
# Check if migrating from launch_config_name to launch_template_name first |
| 1731 |
if "launch_config_name" in props["instance_facts"][i]: |
| 1732 |
old_instances.append(i) |
| 1733 |
elif props["instance_facts"][i].get("launch_template") == props["launch_template"]: |
| 1734 |
new_instances.append(i) |
| 1735 |
else: |
| 1736 |
old_instances.append(i) |
| 1737 |
else: |
| 1738 |
module.debug(f"Comparing initial instances with current: {(*initial_instances,)}") |
| 1739 |
for i in props["instances"]: |
| 1740 |
if i not in initial_instances: |
| 1741 |
new_instances.append(i) |
| 1742 |
else: |
| 1743 |
old_instances.append(i) |
| 1744 |
|
| 1745 |
module.debug(f"New instances: {len(new_instances)}, {(*new_instances,)}") |
| 1746 |
module.debug(f"Old instances: {len(old_instances)}, {(*old_instances,)}") |
| 1747 |
|
| 1748 |
return new_instances, old_instances |
| 1749 |
|
| 1750 |
|
| 1751 |
def list_purgeable_instances(props, lc_check, lt_check, replace_instances, initial_instances): |
| 1752 |
instances_to_terminate = [] |
| 1753 |
instances = (inst_id for inst_id in replace_instances if inst_id in props["instances"]) |
| 1754 |
# check to make sure instances given are actually in the given ASG |
| 1755 |
# and they have a non-current launch config |
| 1756 |
if "launch_config_name" in module.params: |
| 1757 |
if lc_check: |
| 1758 |
for i in instances: |
| 1759 |
if ( |
| 1760 |
"launch_template" in props["instance_facts"][i] |
| 1761 |
or props["instance_facts"][i]["launch_config_name"] != props["launch_config_name"] |
| 1762 |
): |
| 1763 |
instances_to_terminate.append(i) |
| 1764 |
else: |
| 1765 |
for i in instances: |
| 1766 |
if i in initial_instances: |
| 1767 |
instances_to_terminate.append(i) |
| 1768 |
elif "launch_template" in module.params: |
| 1769 |
if lt_check: |
| 1770 |
for i in instances: |
| 1771 |
if ( |
| 1772 |
"launch_config_name" in props["instance_facts"][i] |
| 1773 |
or props["instance_facts"][i]["launch_template"] != props["launch_template"] |
| 1774 |
): |
| 1775 |
instances_to_terminate.append(i) |
| 1776 |
else: |
| 1777 |
for i in instances: |
| 1778 |
if i in initial_instances: |
| 1779 |
instances_to_terminate.append(i) |
| 1780 |
|
| 1781 |
return instances_to_terminate |
| 1782 |
|
| 1783 |
|
| 1784 |
def terminate_batch(connection, replace_instances, initial_instances, leftovers=False): |
| 1785 |
batch_size = module.params.get("replace_batch_size") |
| 1786 |
min_size = module.params.get("min_size") |
| 1787 |
desired_capacity = module.params.get("desired_capacity") |
| 1788 |
group_name = module.params.get("name") |
| 1789 |
lc_check = module.params.get("lc_check") |
| 1790 |
lt_check = module.params.get("lt_check") |
| 1791 |
decrement_capacity = False |
| 1792 |
break_loop = False |
| 1793 |
|
| 1794 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1795 |
if desired_capacity is None: |
| 1796 |
desired_capacity = as_group["DesiredCapacity"] |
| 1797 |
|
| 1798 |
props = get_properties(as_group) |
| 1799 |
desired_size = as_group["MinSize"] |
| 1800 |
if module.params.get("launch_config_name"): |
| 1801 |
new_instances, old_instances = get_instances_by_launch_config(props, lc_check, initial_instances) |
| 1802 |
else: |
| 1803 |
new_instances, old_instances = get_instances_by_launch_template(props, lt_check, initial_instances) |
| 1804 |
num_new_inst_needed = desired_capacity - len(new_instances) |
| 1805 |
|
| 1806 |
# check to make sure instances given are actually in the given ASG |
| 1807 |
# and they have a non-current launch config |
| 1808 |
instances_to_terminate = list_purgeable_instances(props, lc_check, lt_check, replace_instances, initial_instances) |
| 1809 |
|
| 1810 |
module.debug(f"new instances needed: {num_new_inst_needed}") |
| 1811 |
module.debug(f"new instances: {(*new_instances,)}") |
| 1812 |
module.debug(f"old instances: {(*old_instances,)}") |
| 1813 |
module.debug(f"batch instances: {(*instances_to_terminate,)}") |
| 1814 |
|
| 1815 |
if num_new_inst_needed == 0: |
| 1816 |
decrement_capacity = True |
| 1817 |
if as_group["MinSize"] != min_size: |
| 1818 |
if min_size is None: |
| 1819 |
min_size = as_group["MinSize"] |
| 1820 |
updated_params = dict(AutoScalingGroupName=as_group["AutoScalingGroupName"], MinSize=min_size) |
| 1821 |
update_asg(connection, **updated_params) |
| 1822 |
module.debug(f"Updating minimum size back to original of {min_size}") |
| 1823 |
# if are some leftover old instances, but we are already at capacity with new ones |
| 1824 |
# we don't want to decrement capacity |
| 1825 |
if leftovers: |
| 1826 |
decrement_capacity = False |
| 1827 |
break_loop = True |
| 1828 |
instances_to_terminate = old_instances |
| 1829 |
desired_size = min_size |
| 1830 |
module.debug("No new instances needed") |
| 1831 |
|
| 1832 |
if num_new_inst_needed < batch_size and num_new_inst_needed != 0: |
| 1833 |
instances_to_terminate = instances_to_terminate[:num_new_inst_needed] |
| 1834 |
decrement_capacity = False |
| 1835 |
break_loop = False |
| 1836 |
module.debug(f"{num_new_inst_needed} new instances needed") |
| 1837 |
|
| 1838 |
module.debug(f"decrementing capacity: {decrement_capacity}") |
| 1839 |
|
| 1840 |
for instance_id in instances_to_terminate: |
| 1841 |
elb_dreg(connection, group_name, instance_id) |
| 1842 |
module.debug(f"terminating instance: {instance_id}") |
| 1843 |
terminate_asg_instance(connection, instance_id, decrement_capacity) |
| 1844 |
|
| 1845 |
# we wait to make sure the machines we marked as Unhealthy are |
| 1846 |
# no longer in the list |
| 1847 |
|
| 1848 |
return break_loop, desired_size, instances_to_terminate |
| 1849 |
|
| 1850 |
|
| 1851 |
def wait_for_term_inst(connection, term_instances): |
| 1852 |
wait_timeout = module.params.get("wait_timeout") |
| 1853 |
group_name = module.params.get("name") |
| 1854 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1855 |
count = 1 |
| 1856 |
wait_timeout = time.time() + wait_timeout |
| 1857 |
while wait_timeout > time.time() and count > 0: |
| 1858 |
module.debug("waiting for instances to terminate") |
| 1859 |
count = 0 |
| 1860 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1861 |
props = get_properties(as_group) |
| 1862 |
instance_facts = props["instance_facts"] |
| 1863 |
instances = (i for i in instance_facts if i in term_instances) |
| 1864 |
for i in instances: |
| 1865 |
lifecycle = instance_facts[i]["lifecycle_state"] |
| 1866 |
health = instance_facts[i]["health_status"] |
| 1867 |
module.debug(f"Instance {i} has state of {lifecycle},{health}") |
| 1868 |
if lifecycle.startswith("Terminating") or health == "Unhealthy": |
| 1869 |
count += 1 |
| 1870 |
time.sleep(10) |
| 1871 |
|
| 1872 |
if wait_timeout <= time.time(): |
| 1873 |
# waiting took too long |
| 1874 |
module.fail_json(msg=f"Waited too long for old instances to terminate. {time.asctime()}") |
| 1875 |
|
| 1876 |
|
| 1877 |
def wait_for_new_inst(connection, group_name, wait_timeout, desired_size, prop): |
| 1878 |
# make sure we have the latest stats after that last loop. |
| 1879 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1880 |
props = get_properties(as_group) |
| 1881 |
module.debug(f"Waiting for {prop} = {desired_size}, currently {props[prop]}") |
| 1882 |
# now we make sure that we have enough instances in a viable state |
| 1883 |
wait_timeout = time.time() + wait_timeout |
| 1884 |
while wait_timeout > time.time() and desired_size > props[prop]: |
| 1885 |
module.debug(f"Waiting for {prop} = {desired_size}, currently {props[prop]}") |
| 1886 |
time.sleep(10) |
| 1887 |
as_group = describe_autoscaling_groups(connection, group_name)[0] |
| 1888 |
props = get_properties(as_group) |
| 1889 |
if wait_timeout <= time.time(): |
| 1890 |
# waiting took too long |
| 1891 |
module.fail_json(msg=f"Waited too long for new instances to become viable. {time.asctime()}") |
| 1892 |
module.debug(f"Reached {prop}: {desired_size}") |
| 1893 |
return props |
| 1894 |
|
| 1895 |
|
| 1896 |
def asg_exists(connection): |
| 1897 |
group_name = module.params.get("name") |
| 1898 |
as_group = describe_autoscaling_groups(connection, group_name) |
| 1899 |
return bool(len(as_group)) |
| 1900 |
|
| 1901 |
|
| 1902 |
def main(): |
| 1903 |
argument_spec = dict( |
| 1904 |
name=dict(required=True, type="str", aliases=["group_name"]), |
| 1905 |
load_balancers=dict(type="list", elements="str"), |
| 1906 |
target_group_arns=dict(type="list", elements="str"), |
| 1907 |
availability_zones=dict(type="list", elements="str"), |
| 1908 |
launch_config_name=dict(type="str"), |
| 1909 |
launch_template=dict( |
| 1910 |
type="dict", |
| 1911 |
default=None, |
| 1912 |
options=dict( |
| 1913 |
version=dict(type="str"), |
| 1914 |
launch_template_name=dict(type="str"), |
| 1915 |
launch_template_id=dict(type="str"), |
| 1916 |
), |
| 1917 |
), |
| 1918 |
min_size=dict(type="int"), |
| 1919 |
max_size=dict(type="int"), |
| 1920 |
max_instance_lifetime=dict(type="int"), |
| 1921 |
mixed_instances_policy=dict( |
| 1922 |
type="dict", |
| 1923 |
default=None, |
| 1924 |
options=dict( |
| 1925 |
instance_types=dict(type="list", elements="str"), |
| 1926 |
instances_distribution=dict( |
| 1927 |
type="dict", |
| 1928 |
default=None, |
| 1929 |
options=dict( |
| 1930 |
on_demand_allocation_strategy=dict(type="str"), |
| 1931 |
on_demand_base_capacity=dict(type="int"), |
| 1932 |
on_demand_percentage_above_base_capacity=dict(type="int"), |
| 1933 |
spot_allocation_strategy=dict(type="str"), |
| 1934 |
spot_instance_pools=dict(type="int"), |
| 1935 |
spot_max_price=dict(type="str"), |
| 1936 |
), |
| 1937 |
), |
| 1938 |
), |
| 1939 |
), |
| 1940 |
placement_group=dict(type="str"), |
| 1941 |
protected_from_scale_in=dict(type="bool", default=None), |
| 1942 |
desired_capacity=dict(type="int"), |
| 1943 |
vpc_zone_identifier=dict(type="list", elements="str"), |
| 1944 |
replace_batch_size=dict( |
| 1945 |
removed_in_version="14.0.0", |
| 1946 |
removed_from_collection="amazon.aws", |
| 1947 |
type="int", |
| 1948 |
default=1, |
| 1949 |
), |
| 1950 |
replace_all_instances=dict( |
| 1951 |
removed_in_version="14.0.0", |
| 1952 |
removed_from_collection="amazon.aws", |
| 1953 |
type="bool", |
| 1954 |
default=False, |
| 1955 |
), |
| 1956 |
replace_instances=dict( |
| 1957 |
removed_in_version="14.0.0", |
| 1958 |
removed_from_collection="amazon.aws", |
| 1959 |
type="list", |
| 1960 |
default=[], |
| 1961 |
elements="str", |
| 1962 |
), |
| 1963 |
detach_instances=dict( |
| 1964 |
removed_in_version="14.0.0", |
| 1965 |
removed_from_collection="amazon.aws", |
| 1966 |
type="list", |
| 1967 |
default=[], |
| 1968 |
elements="str", |
| 1969 |
), |
| 1970 |
decrement_desired_capacity=dict( |
| 1971 |
removed_in_version="14.0.0", |
| 1972 |
removed_from_collection="amazon.aws", |
| 1973 |
type="bool", |
| 1974 |
default=False, |
| 1975 |
), |
| 1976 |
lc_check=dict( |
| 1977 |
removed_in_version="14.0.0", |
| 1978 |
removed_from_collection="amazon.aws", |
| 1979 |
type="bool", |
| 1980 |
default=True, |
| 1981 |
), |
| 1982 |
lt_check=dict( |
| 1983 |
removed_in_version="14.0.0", |
| 1984 |
removed_from_collection="amazon.aws", |
| 1985 |
type="bool", |
| 1986 |
default=True, |
| 1987 |
), |
| 1988 |
wait_timeout=dict(type="int", default=300), |
| 1989 |
state=dict(default="present", choices=["present", "absent"]), |
| 1990 |
tags=dict(type="list", default=[], elements="dict"), |
| 1991 |
purge_tags=dict(type="bool", default=False), |
| 1992 |
health_check_period=dict(type="int", default=300), |
| 1993 |
health_check_type=dict(default="EC2", choices=["EC2", "ELB"]), |
| 1994 |
default_cooldown=dict(type="int", default=300), |
| 1995 |
wait_for_instances=dict(type="bool", default=True), |
| 1996 |
termination_policies=dict(type="list", default="Default", elements="str"), |
| 1997 |
notification_topic=dict(type="str", default=None), |
| 1998 |
notification_types=dict( |
| 1999 |
type="list", |
| 2000 |
default=[ |
| 2001 |
"autoscaling:EC2_INSTANCE_LAUNCH", |
| 2002 |
"autoscaling:EC2_INSTANCE_LAUNCH_ERROR", |
| 2003 |
"autoscaling:EC2_INSTANCE_TERMINATE", |
| 2004 |
"autoscaling:EC2_INSTANCE_TERMINATE_ERROR", |
| 2005 |
], |
| 2006 |
elements="str", |
| 2007 |
), |
| 2008 |
suspend_processes=dict(type="list", default=[], elements="str"), |
| 2009 |
metrics_collection=dict(type="bool", default=False), |
| 2010 |
metrics_granularity=dict(type="str", default="1Minute"), |
| 2011 |
metrics_list=dict( |
| 2012 |
type="list", |
| 2013 |
default=[ |
| 2014 |
"GroupMinSize", |
| 2015 |
"GroupMaxSize", |
| 2016 |
"GroupDesiredCapacity", |
| 2017 |
"GroupInServiceInstances", |
| 2018 |
"GroupPendingInstances", |
| 2019 |
"GroupStandbyInstances", |
| 2020 |
"GroupTerminatingInstances", |
| 2021 |
"GroupTotalInstances", |
| 2022 |
], |
| 2023 |
elements="str", |
| 2024 |
), |
| 2025 |
) |
| 2026 |
|
| 2027 |
global module |
| 2028 |
module = AnsibleAWSModule( |
| 2029 |
argument_spec=argument_spec, |
| 2030 |
supports_check_mode=True, |
| 2031 |
mutually_exclusive=[ |
| 2032 |
["replace_all_instances", "replace_instances"], |
| 2033 |
["replace_all_instances", "detach_instances"], |
| 2034 |
["launch_config_name", "launch_template"], |
| 2035 |
], |
| 2036 |
) |
| 2037 |
|
| 2038 |
state = module.params.get("state") |
| 2039 |
replace_instances = module.params.get("replace_instances") |
| 2040 |
replace_all_instances = module.params.get("replace_all_instances") |
| 2041 |
detach_instances = module.params.get("detach_instances") |
| 2042 |
|
| 2043 |
connection = module.client("autoscaling") |
| 2044 |
changed = create_changed = replace_changed = detach_changed = False |
| 2045 |
exists = asg_exists(connection) |
| 2046 |
|
| 2047 |
if state == "present": |
| 2048 |
create_changed, asg_properties = create_autoscaling_group(connection) |
| 2049 |
elif state == "absent": |
| 2050 |
changed = delete_autoscaling_group(connection) |
| 2051 |
module.exit_json(changed=changed) |
| 2052 |
|
| 2053 |
# Only replace instances if asg existed at start of call |
| 2054 |
if ( |
| 2055 |
exists |
| 2056 |
and (replace_all_instances or replace_instances) |
| 2057 |
and (module.params.get("launch_config_name") or module.params.get("launch_template")) |
| 2058 |
): |
| 2059 |
replace_changed, asg_properties = replace(connection) |
| 2060 |
|
| 2061 |
# Only detach instances if asg existed at start of call |
| 2062 |
if ( |
| 2063 |
exists |
| 2064 |
and (detach_instances) |
| 2065 |
and (module.params.get("launch_config_name") or module.params.get("launch_template")) |
| 2066 |
): |
| 2067 |
detach_changed, asg_properties = detach(connection) |
| 2068 |
|
| 2069 |
if create_changed or replace_changed or detach_changed: |
| 2070 |
changed = True |
| 2071 |
|
| 2072 |
module.exit_json(changed=changed, **asg_properties) |
| 2073 |
|
| 2074 |
|
| 2075 |
if __name__ == "__main__": |
| 2076 |
main() |