| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: Ansible Project |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
--- |
| 9 |
module: autoscaling_instance_refresh |
| 10 |
version_added: 3.2.0 |
| 11 |
version_added_collection: community.aws |
| 12 |
short_description: Start or cancel an EC2 Auto Scaling Group (ASG) instance refresh in AWS |
| 13 |
description: |
| 14 |
- Start or cancel an EC2 Auto Scaling Group instance refresh in AWS. |
| 15 |
- Can be used with M(amazon.aws.autoscaling_instance_refresh_info) to track the subsequent progress. |
| 16 |
- Prior to release 5.0.0 this module was called M(community.aws.ec2_asg_instance_refresh). |
| 17 |
The usage did not change. |
| 18 |
author: |
| 19 |
- "Dan Khersonsky (@danquixote)" |
| 20 |
options: |
| 21 |
state: |
| 22 |
description: |
| 23 |
- Desired state of the ASG. |
| 24 |
type: str |
| 25 |
required: true |
| 26 |
choices: [ 'started', 'cancelled' ] |
| 27 |
name: |
| 28 |
description: |
| 29 |
- The name of the auto scaling group you are searching for. |
| 30 |
aliases: ['group_name'] |
| 31 |
type: str |
| 32 |
required: true |
| 33 |
strategy: |
| 34 |
description: |
| 35 |
- The strategy to use for the instance refresh. The only valid value is V(Rolling). |
| 36 |
- A rolling update is an update that is applied to all instances in an Auto Scaling group until all instances have been updated. |
| 37 |
- A rolling update can fail due to failed health checks or if instances are on standby or are protected from scale in. |
| 38 |
- If the rolling update process fails, any instances that were already replaced are not rolled back to their previous configuration. |
| 39 |
type: str |
| 40 |
default: 'Rolling' |
| 41 |
preferences: |
| 42 |
description: |
| 43 |
- Set of preferences associated with the instance refresh request. |
| 44 |
- If not provided, the default values are used. |
| 45 |
- For O(preferences.min_healthy_percentage), the default value is V(90). |
| 46 |
- For O(preferences.instance_warmup), the default is to use the value specified for the health check grace period for the Auto Scaling group. |
| 47 |
- Can not be specified when O(state=cancelled). |
| 48 |
required: false |
| 49 |
suboptions: |
| 50 |
min_healthy_percentage: |
| 51 |
description: |
| 52 |
- Total percent of capacity in ASG that must remain healthy during instance refresh to allow operation to continue. |
| 53 |
- It is rounded up to the nearest integer. |
| 54 |
- Value range is V(0) to V(100). |
| 55 |
type: int |
| 56 |
default: 90 |
| 57 |
instance_warmup: |
| 58 |
description: |
| 59 |
- The number of seconds until a newly launched instance is configured and ready to use. |
| 60 |
- During this time, Amazon EC2 Auto Scaling does not immediately move on to the next replacement. |
| 61 |
- The default is to use the value for the health check grace period defined for the group. |
| 62 |
type: int |
| 63 |
skip_matching: |
| 64 |
description: |
| 65 |
- Indicates whether skip matching is enabled. |
| 66 |
- If enabled V(true), then Amazon EC2 Auto Scaling skips replacing instances that match the desired configuration. |
| 67 |
type: bool |
| 68 |
version_added: 9.0.0 |
| 69 |
max_healthy_percentage: |
| 70 |
description: |
| 71 |
- Specifies the maximum percentage of the group that can be in service and healthy, or pending, |
| 72 |
to support your workload when replacing instances. |
| 73 |
- The value is expressed as a percentage of the desired capacity of the Auto Scaling group. |
| 74 |
- Value range is V(100) to V(200). |
| 75 |
- When specified, you must also specify O(preferences.min_healthy_percentage), and the difference between them cannot be greater than V(100). |
| 76 |
type: int |
| 77 |
version_added: 9.0.0 |
| 78 |
type: dict |
| 79 |
extends_documentation_fragment: |
| 80 |
- amazon.aws.common.modules |
| 81 |
- amazon.aws.region.modules |
| 82 |
- amazon.aws.boto3 |
| 83 |
""" |
| 84 |
|
| 85 |
EXAMPLES = r""" |
| 86 |
# Note: These examples do not set authentication details, see the AWS Guide for details. |
| 87 |
|
| 88 |
- name: Start a refresh |
| 89 |
amazon.aws.autoscaling_instance_refresh: |
| 90 |
name: some-asg |
| 91 |
state: started |
| 92 |
|
| 93 |
- name: Cancel a refresh |
| 94 |
amazon.aws.autoscaling_instance_refresh: |
| 95 |
name: some-asg |
| 96 |
state: cancelled |
| 97 |
|
| 98 |
- name: Start a refresh and pass preferences |
| 99 |
amazon.aws.autoscaling_instance_refresh: |
| 100 |
name: some-asg |
| 101 |
state: started |
| 102 |
preferences: |
| 103 |
min_healthy_percentage: 91 |
| 104 |
instance_warmup: 60 |
| 105 |
skip_matching: true |
| 106 |
""" |
| 107 |
|
| 108 |
RETURN = r""" |
| 109 |
instance_refreshes: |
| 110 |
description: Details of the instance refreshes for the Auto Scaling group. |
| 111 |
returned: always |
| 112 |
type: complex |
| 113 |
contains: |
| 114 |
instance_refresh_id: |
| 115 |
description: Instance refresh id. |
| 116 |
returned: success |
| 117 |
type: str |
| 118 |
sample: "08b91cf7-8fa6-48af-b6a6-d227f40f1b9b" |
| 119 |
auto_scaling_group_name: |
| 120 |
description: Name of autoscaling group. |
| 121 |
returned: success |
| 122 |
type: str |
| 123 |
sample: "public-webapp-production-1" |
| 124 |
status: |
| 125 |
description: |
| 126 |
- The current state of the group when DeleteAutoScalingGroup is in progress. |
| 127 |
- The following are the possible statuses |
| 128 |
- Pending - The request was created, but the operation has not started. |
| 129 |
- InProgress - The operation is in progress. |
| 130 |
- Successful - The operation completed successfully. |
| 131 |
- Failed - The operation failed to complete. |
| 132 |
You can troubleshoot using the status reason and the scaling activities. |
| 133 |
- Cancelling - An ongoing operation is being cancelled. |
| 134 |
Cancellation does not roll back any replacements that have already been |
| 135 |
completed, but it prevents new replacements from being started. |
| 136 |
- Cancelled - The operation is cancelled. |
| 137 |
returned: success |
| 138 |
type: str |
| 139 |
sample: "Pending" |
| 140 |
preferences: |
| 141 |
description: The preferences for an instance refresh. |
| 142 |
returned: always |
| 143 |
type: dict |
| 144 |
sample: { |
| 145 |
'AlarmSpecification': { |
| 146 |
'Alarms': [ |
| 147 |
'my-alarm', |
| 148 |
], |
| 149 |
}, |
| 150 |
'AutoRollback': True, |
| 151 |
'InstanceWarmup': 200, |
| 152 |
'MinHealthyPercentage': 90, |
| 153 |
'ScaleInProtectedInstances': 'Ignore', |
| 154 |
'SkipMatching': False, |
| 155 |
'StandbyInstances': 'Ignore', |
| 156 |
} |
| 157 |
start_time: |
| 158 |
description: The date and time this ASG was created, in ISO 8601 format. |
| 159 |
returned: success |
| 160 |
type: str |
| 161 |
sample: "2015-11-25T00:05:36.309Z" |
| 162 |
end_time: |
| 163 |
description: The date and time this ASG was created, in ISO 8601 format. |
| 164 |
returned: success |
| 165 |
type: str |
| 166 |
sample: "2015-11-25T00:05:36.309Z" |
| 167 |
percentage_complete: |
| 168 |
description: the % of completeness. |
| 169 |
returned: success |
| 170 |
type: int |
| 171 |
sample: 100 |
| 172 |
instances_to_update: |
| 173 |
description: number of instances to update. |
| 174 |
returned: success |
| 175 |
type: int |
| 176 |
sample: 5 |
| 177 |
""" |
| 178 |
|
| 179 |
from typing import Dict |
| 180 |
from typing import Optional |
| 181 |
from typing import Union |
| 182 |
|
| 183 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 184 |
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict |
| 185 |
|
| 186 |
from ansible_collections.amazon.aws.plugins.module_utils.autoscaling import AnsibleAutoScalingError |
| 187 |
from ansible_collections.amazon.aws.plugins.module_utils.autoscaling import cancel_instance_refresh |
| 188 |
from ansible_collections.amazon.aws.plugins.module_utils.autoscaling import describe_instance_refreshes |
| 189 |
from ansible_collections.amazon.aws.plugins.module_utils.autoscaling import start_instance_refresh |
| 190 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 191 |
from ansible_collections.amazon.aws.plugins.module_utils.transformation import scrub_none_parameters |
| 192 |
|
| 193 |
|
| 194 |
def validate_healthy_percentage(preferences: Dict[str, Union[bool, int]]) -> Optional[str]: |
| 195 |
min_healthy_percentage = preferences.get("min_healthy_percentage") |
| 196 |
max_healthy_percentage = preferences.get("max_healthy_percentage") |
| 197 |
|
| 198 |
if min_healthy_percentage is not None and (min_healthy_percentage < 0 or min_healthy_percentage > 100): |
| 199 |
return "The value range for the min_healthy_percentage is 0 to 100." |
| 200 |
if max_healthy_percentage is not None: |
| 201 |
if max_healthy_percentage < 100 or max_healthy_percentage > 200: |
| 202 |
return "The value range for the max_healthy_percentage is 100 to 200." |
| 203 |
if min_healthy_percentage is None: |
| 204 |
return "You must also specify min_healthy_percentage when max_healthy_percentage is specified." |
| 205 |
if (max_healthy_percentage - min_healthy_percentage) > 100: |
| 206 |
return "The difference between the max_healthy_percentage and min_healthy_percentage cannot be greater than 100." |
| 207 |
return None |
| 208 |
|
| 209 |
|
| 210 |
def start_or_cancel_instance_refresh(conn, module: AnsibleAWSModule) -> None: |
| 211 |
""" |
| 212 |
Args: |
| 213 |
conn (boto3.AutoScaling.Client): Valid Boto3 ASG client. |
| 214 |
module: AnsibleAWSModule object |
| 215 |
""" |
| 216 |
|
| 217 |
asg_state = module.params.get("state") |
| 218 |
asg_name = module.params.get("name") |
| 219 |
preferences = module.params.get("preferences") |
| 220 |
|
| 221 |
args = {} |
| 222 |
if asg_state == "started": |
| 223 |
args["Strategy"] = module.params.get("strategy") |
| 224 |
if preferences: |
| 225 |
if asg_state == "cancelled": |
| 226 |
module.fail_json(msg="can not pass preferences dict when canceling a refresh") |
| 227 |
error = validate_healthy_percentage(preferences) |
| 228 |
if error: |
| 229 |
module.fail_json(msg=error) |
| 230 |
args["Preferences"] = snake_dict_to_camel_dict(scrub_none_parameters(preferences), capitalize_first=True) |
| 231 |
cmd_invocations = { |
| 232 |
"cancelled": cancel_instance_refresh, |
| 233 |
"started": start_instance_refresh, |
| 234 |
} |
| 235 |
try: |
| 236 |
if module.check_mode: |
| 237 |
ongoing_refresh = describe_instance_refreshes(conn, auto_scaling_group_name=asg_name).get( |
| 238 |
"InstanceRefreshes", [] |
| 239 |
) |
| 240 |
if asg_state == "started": |
| 241 |
if ongoing_refresh: |
| 242 |
module.exit_json( |
| 243 |
changed=False, |
| 244 |
msg="In check_mode - Instance Refresh is already in progress, can not start new instance refresh.", |
| 245 |
) |
| 246 |
else: |
| 247 |
module.exit_json(changed=True, msg="Would have started instance refresh if not in check mode.") |
| 248 |
elif asg_state == "cancelled": |
| 249 |
if ongoing_refresh and ongoing_refresh[0].get("Status", "") in ["Cancelling", "Cancelled"]: |
| 250 |
module.exit_json( |
| 251 |
changed=False, |
| 252 |
msg="In check_mode - Instance Refresh already cancelled or is pending cancellation.", |
| 253 |
) |
| 254 |
elif not ongoing_refresh: |
| 255 |
module.exit_json(changed=False, msg="In check_mode - No active referesh found, nothing to cancel.") |
| 256 |
else: |
| 257 |
module.exit_json(changed=True, msg="Would have cancelled instance refresh if not in check mode.") |
| 258 |
instance_refresh_id = cmd_invocations[asg_state](conn, auto_scaling_group_name=asg_name, **args) |
| 259 |
response = describe_instance_refreshes( |
| 260 |
conn, auto_scaling_group_name=asg_name, instance_refresh_ids=[instance_refresh_id] |
| 261 |
) |
| 262 |
result = dict(instance_refreshes=camel_dict_to_snake_dict(response["InstanceRefreshes"][0])) |
| 263 |
module.exit_json(**result) |
| 264 |
except AnsibleAutoScalingError as e: |
| 265 |
module.fail_json_aws(e, msg=f"Failed to {asg_state.replace('ed', '')} InstanceRefresh: {e}") |
| 266 |
|
| 267 |
|
| 268 |
def main(): |
| 269 |
argument_spec = dict( |
| 270 |
state=dict( |
| 271 |
type="str", |
| 272 |
required=True, |
| 273 |
choices=["started", "cancelled"], |
| 274 |
), |
| 275 |
name=dict(required=True, aliases=["group_name"]), |
| 276 |
strategy=dict(type="str", default="Rolling", required=False), |
| 277 |
preferences=dict( |
| 278 |
type="dict", |
| 279 |
required=False, |
| 280 |
options=dict( |
| 281 |
min_healthy_percentage=dict(type="int", default=90), |
| 282 |
instance_warmup=dict(type="int"), |
| 283 |
skip_matching=dict(type="bool"), |
| 284 |
max_healthy_percentage=dict(type="int"), |
| 285 |
), |
| 286 |
), |
| 287 |
) |
| 288 |
|
| 289 |
module = AnsibleAWSModule( |
| 290 |
argument_spec=argument_spec, |
| 291 |
supports_check_mode=True, |
| 292 |
) |
| 293 |
autoscaling = module.client("autoscaling") |
| 294 |
|
| 295 |
start_or_cancel_instance_refresh(autoscaling, module) |
| 296 |
|
| 297 |
|
| 298 |
if __name__ == "__main__": |
| 299 |
main() |