Debian Codegraph @

ansible_collections/community/aws/plugins/modules/autoscaling_policy.py

raw
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 module: autoscaling_policy
9 short_description: Create or delete AWS scaling policies for Autoscaling groups
10 version_added: 1.0.0
11 description:
12 - Can create or delete scaling policies for autoscaling groups.
13 - Referenced autoscaling groups must already exist.
14 - Prior to release 5.0.0 this module was called C(community.aws.ec2_scaling_policy).
15 The usage did not change.
16 author:
17 - Zacharie Eakin (@zeekin)
18 - Will Thames (@willthames)
19 options:
20 state:
21 type: str
22 description:
23 - Register or deregister the policy.
24 choices: ['present', 'absent']
25 default: 'present'
26 name:
27 type: str
28 description:
29 - Unique name for the scaling policy.
30 required: true
31 asg_name:
32 type: str
33 description:
34 - Name of the associated autoscaling group.
35 - Required if I(state) is C(present).
36 adjustment_type:
37 type: str
38 description:
39 - The type of change in capacity of the autoscaling group.
40 - Required if I(state) is C(present).
41 choices:
42 - ChangeInCapacity
43 - ExactCapacity
44 - PercentChangeInCapacity
45 scaling_adjustment:
46 type: int
47 description:
48 - The amount by which the autoscaling group is adjusted by the policy.
49 - A negative number has the effect of scaling down the ASG.
50 - Units are numbers of instances for C(ExactCapacity) or C(ChangeInCapacity) or percent
51 of existing instances for C(PercentChangeInCapacity).
52 - Required when I(policy_type) is C(SimpleScaling).
53 min_adjustment_step:
54 type: int
55 description:
56 - Minimum amount of adjustment when policy is triggered.
57 - Only used when I(adjustment_type) is C(PercentChangeInCapacity).
58 cooldown:
59 type: int
60 description:
61 - The minimum period of time (in seconds) between which autoscaling actions can take place.
62 - Only used when I(policy_type) is C(SimpleScaling).
63 policy_type:
64 type: str
65 description:
66 - Auto scaling adjustment policy.
67 choices:
68 - StepScaling
69 - SimpleScaling
70 - TargetTrackingScaling
71 default: SimpleScaling
72 metric_aggregation:
73 type: str
74 description:
75 - The aggregation type for the CloudWatch metrics.
76 - Only used when I(policy_type) is not C(SimpleScaling).
77 choices:
78 - Minimum
79 - Maximum
80 - Average
81 default: Average
82 step_adjustments:
83 type: list
84 description:
85 - List of dicts containing I(lower_bound), I(upper_bound) and I(scaling_adjustment).
86 - Intervals must not overlap or have a gap between them.
87 - At most, one item can have an undefined I(lower_bound).
88 If any item has a negative lower_bound, then there must be a step adjustment with an undefined I(lower_bound).
89 - At most, one item can have an undefined I(upper_bound).
90 If any item has a positive upper_bound, then there must be a step adjustment with an undefined I(upper_bound).
91 - The bounds are the amount over the alarm threshold at which the adjustment will trigger.
92 This means that for an alarm threshold of 50, triggering at 75 requires a lower bound of 25.
93 See U(http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_StepAdjustment.html).
94 elements: dict
95 suboptions:
96 lower_bound:
97 type: int
98 description:
99 - The lower bound for the difference between the alarm threshold and
100 the CloudWatch metric.
101 upper_bound:
102 type: int
103 description:
104 - The upper bound for the difference between the alarm threshold and
105 the CloudWatch metric.
106 scaling_adjustment:
107 type: int
108 description:
109 - The amount by which to scale.
110 required: true
111 target_tracking_config:
112 type: dict
113 description:
114 - Allows you to specify a I(target_tracking_config) for autoscaling policies in AWS.
115 - I(target_tracking_config) can accept nested dicts for I(customized_metric_spec) or I(predefined_metric_spec).
116 Each specification aligns with their boto3 equivalent.
117 - Required when I(TargetTrackingScaling) policy is specified.
118 version_added: 4.1.0
119 suboptions:
120 customized_metric_spec:
121 type: dict
122 description:
123 - Specify a dict will be passed in as a call for C(TargetTrackingConfiguration).
124 suboptions:
125 metric_name:
126 type: str
127 description:
128 - The name of the metric.
129 required: true
130 namespace:
131 type: str
132 description:
133 - The namespace of the metric.
134 required: true
135 statistic:
136 type: str
137 description:
138 - The statistic of the metric.
139 required: true
140 choices:
141 - Average
142 - Minimum
143 - Maximum
144 - SampleCount
145 - Sum
146 dimensions:
147 type: list
148 description:
149 - The dimensions of the metric. The element of the list should be a dict.
150 elements: dict
151 unit:
152 type: str
153 description:
154 - The unit of the metric. Reference AmazonCloudWatch API for valid Units.
155 predefined_metric_spec:
156 type: dict
157 description:
158 - Specify a dict will be passed in as a call for I(TargetTrackingConfiguration).
159 suboptions:
160 predefined_metric_type:
161 type: str
162 required: true
163 description:
164 - Required if C(predefined_metric_spec) is used.
165 choices:
166 - ASGAverageCPUUtilization
167 - ASGAverageNetworkIn
168 - ASGAverageNetworkOut
169 - ALBRequestCountPerTarget
170 resource_label:
171 type: str
172 description:
173 - Uniquely identifies a specific ALB target group from which to determine the average request count served by your Auto Scaling group.
174 - You can't specify a resource label unless the target group is attached to the Auto Scaling group.
175 target_value:
176 type: float
177 description:
178 - Specify a float number for target utilization.
179 - Required when I(target_tracking_config) is specified.
180 required: true
181 disable_scalein:
182 type: bool
183 description:
184 - Indicate whether scaling in by the target tracking scaling policy is disabled.
185 estimated_instance_warmup:
186 type: int
187 description:
188 - The estimated time, in seconds, until a newly launched instance can contribute to the CloudWatch metrics.
189 extends_documentation_fragment:
190 - amazon.aws.common.modules
191 - amazon.aws.region.modules
192 - amazon.aws.boto3
193 """
194
195 EXAMPLES = r"""
196 - name: Simple Scale Down policy
197 community.aws.autoscaling_policy:
198 state: present
199 region: US-XXX
200 name: "scaledown-policy"
201 adjustment_type: "ChangeInCapacity"
202 asg_name: "application-asg"
203 scaling_adjustment: -1
204 min_adjustment_step: 1
205 cooldown: 300
206
207 # For an alarm with a breach threshold of 20, the
208 # following creates a stepped policy:
209 # From 20-40 (0-20 above threshold), increase by 50% of existing capacity
210 # From 41-infinity, increase by 100% of existing capacity
211 - community.aws.autoscaling_policy:
212 state: present
213 region: US-XXX
214 name: "step-scale-up-policy"
215 policy_type: StepScaling
216 metric_aggregation: Maximum
217 step_adjustments:
218 - upper_bound: 20
219 scaling_adjustment: 50
220 - lower_bound: 20
221 scaling_adjustment: 100
222 adjustment_type: "PercentChangeInCapacity"
223 asg_name: "application-asg"
224
225 - name: create TargetTracking predefined policy
226 community.aws.autoscaling_policy:
227 name: "predefined-policy-1"
228 policy_type: TargetTrackingScaling
229 target_tracking_config:
230 predefined_metric_spec:
231 predefined_metric_type: ASGAverageCPUUtilization
232 target_value: 98.0
233 asg_name: "asg-test-1"
234 register: result
235
236 - name: create TargetTracking predefined policy with resource_label
237 community.aws.autoscaling_policy:
238 name: "predefined-policy-1"
239 policy_type: TargetTrackingScaling
240 target_tracking_config:
241 predefined_metric_spec:
242 predefined_metric_type: ALBRequestCountPerTarget
243 resource_label: app/my-alb/778d41231d141a0f/targetgroup/my-alb-target-group/942f017f100becff
244 target_value: 98.0
245 asg_name: "asg-test-1"
246 register: result
247
248 - name: create TargetTrackingScaling custom policy
249 community.aws.autoscaling_policy:
250 name: "custom-policy-1"
251 policy_type: TargetTrackingScaling
252 target_tracking_config:
253 customized_metric_spec:
254 metric_name: metric_1
255 namespace: namespace_1
256 statistic: Minimum
257 unit: Gigabits
258 dimensions: [{'Name': 'dimension1', 'Value': 'value1'}]
259 disable_scalein: true
260 target_value: 98.0
261 asg_name: asg-test-1
262 register: result
263 """
264
265 RETURN = r"""
266 adjustment_type:
267 description: Scaling policy adjustment type.
268 returned: always
269 type: str
270 sample: PercentChangeInCapacity
271 alarms:
272 description: Cloudwatch alarms related to the policy.
273 returned: always
274 type: complex
275 contains:
276 alarm_name:
277 description: Name of the Cloudwatch alarm.
278 returned: always
279 type: str
280 sample: cpu-very-high
281 alarm_arn:
282 description: ARN of the Cloudwatch alarm.
283 returned: always
284 type: str
285 sample: arn:aws:cloudwatch:us-east-2:1234567890:alarm:cpu-very-high
286 arn:
287 description: ARN of the scaling policy. Provided for backward compatibility, value is the same as I(policy_arn).
288 returned: always
289 type: str
290 sample: arn:aws:autoscaling:us-east-2:123456789012:scalingPolicy:59e37526-bd27-42cf-adca-5cd3d90bc3b9:autoScalingGroupName/app-asg:policyName/app-policy
291 as_name:
292 description: Auto Scaling Group name. Provided for backward compatibility, value is the same as I(auto_scaling_group_name).
293 returned: always
294 type: str
295 sample: app-asg
296 auto_scaling_group_name:
297 description: Name of Auto Scaling Group.
298 returned: always
299 type: str
300 sample: app-asg
301 metric_aggregation_type:
302 description: Method used to aggregate metrics.
303 returned: when I(policy_type) is C(StepScaling)
304 type: str
305 sample: Maximum
306 name:
307 description: Name of the scaling policy. Provided for backward compatibility, value is the same as I(policy_name).
308 returned: always
309 type: str
310 sample: app-policy
311 policy_arn:
312 description: ARN of scaling policy.
313 returned: always
314 type: str
315 sample: arn:aws:autoscaling:us-east-2:123456789012:scalingPolicy:59e37526-bd27-42cf-adca-5cd3d90bc3b9:autoScalingGroupName/app-asg:policyName/app-policy
316 policy_name:
317 description: Name of scaling policy.
318 returned: always
319 type: str
320 sample: app-policy
321 policy_type:
322 description: Type of auto scaling policy.
323 returned: always
324 type: str
325 sample: StepScaling
326 scaling_adjustment:
327 description: Adjustment to make when alarm is triggered.
328 returned: When I(policy_type) is C(SimpleScaling)
329 type: int
330 sample: 1
331 step_adjustments:
332 description: List of step adjustments.
333 returned: always
334 type: complex
335 contains:
336 metric_interval_lower_bound:
337 description: Lower bound for metric interval.
338 returned: if step has a lower bound
339 type: float
340 sample: 20.0
341 metric_interval_upper_bound:
342 description: Upper bound for metric interval.
343 returned: if step has an upper bound
344 type: float
345 sample: 40.0
346 scaling_adjustment:
347 description: Adjustment to make if this step is reached.
348 returned: always
349 type: int
350 sample: 50
351 """
352
353 try:
354 import botocore
355 except ImportError:
356 pass # caught by imported AnsibleAWSModule
357
358 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
359
360 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
361
362 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
363
364
365 def build_target_specification(target_tracking_config):
366 # Initialize an empty dict() for building TargetTrackingConfiguration policies,
367 # which will be returned
368 targetTrackingConfig = dict()
369
370 if target_tracking_config.get("target_value"):
371 targetTrackingConfig["TargetValue"] = target_tracking_config["target_value"]
372
373 if target_tracking_config.get("disable_scalein"):
374 targetTrackingConfig["DisableScaleIn"] = target_tracking_config["disable_scalein"]
375 else:
376 # Accounting for boto3 response
377 targetTrackingConfig["DisableScaleIn"] = False
378
379 if target_tracking_config["predefined_metric_spec"] is not None:
380 # Build spec for predefined_metric_spec
381 targetTrackingConfig["PredefinedMetricSpecification"] = dict()
382 if target_tracking_config["predefined_metric_spec"].get("predefined_metric_type"):
383 targetTrackingConfig["PredefinedMetricSpecification"]["PredefinedMetricType"] = target_tracking_config[
384 "predefined_metric_spec"
385 ]["predefined_metric_type"]
386
387 if target_tracking_config["predefined_metric_spec"].get("resource_label"):
388 targetTrackingConfig["PredefinedMetricSpecification"]["ResourceLabel"] = target_tracking_config[
389 "predefined_metric_spec"
390 ]["resource_label"]
391
392 elif target_tracking_config["customized_metric_spec"] is not None:
393 # Build spec for customized_metric_spec
394 targetTrackingConfig["CustomizedMetricSpecification"] = dict()
395 if target_tracking_config["customized_metric_spec"].get("metric_name"):
396 targetTrackingConfig["CustomizedMetricSpecification"]["MetricName"] = target_tracking_config[
397 "customized_metric_spec"
398 ]["metric_name"]
399
400 if target_tracking_config["customized_metric_spec"].get("namespace"):
401 targetTrackingConfig["CustomizedMetricSpecification"]["Namespace"] = target_tracking_config[
402 "customized_metric_spec"
403 ]["namespace"]
404
405 if target_tracking_config["customized_metric_spec"].get("dimensions"):
406 targetTrackingConfig["CustomizedMetricSpecification"]["Dimensions"] = target_tracking_config[
407 "customized_metric_spec"
408 ]["dimensions"]
409
410 if target_tracking_config["customized_metric_spec"].get("statistic"):
411 targetTrackingConfig["CustomizedMetricSpecification"]["Statistic"] = target_tracking_config[
412 "customized_metric_spec"
413 ]["statistic"]
414
415 if target_tracking_config["customized_metric_spec"].get("unit"):
416 targetTrackingConfig["CustomizedMetricSpecification"]["Unit"] = target_tracking_config[
417 "customized_metric_spec"
418 ]["unit"]
419
420 return targetTrackingConfig
421
422
423 def create_scaling_policy(connection, module):
424 changed = False
425 asg_name = module.params["asg_name"]
426 policy_type = module.params["policy_type"]
427 policy_name = module.params["name"]
428
429 if policy_type == "TargetTrackingScaling":
430 params = dict(PolicyName=policy_name, PolicyType=policy_type, AutoScalingGroupName=asg_name)
431 else:
432 params = dict(
433 PolicyName=policy_name,
434 PolicyType=policy_type,
435 AutoScalingGroupName=asg_name,
436 AdjustmentType=module.params["adjustment_type"],
437 )
438
439 # min_adjustment_step attribute is only relevant if the adjustment_type
440 # is set to percentage change in capacity, so it is a special case
441 if module.params["adjustment_type"] == "PercentChangeInCapacity":
442 if module.params["min_adjustment_step"]:
443 params["MinAdjustmentMagnitude"] = module.params["min_adjustment_step"]
444
445 if policy_type == "SimpleScaling":
446 # can't use required_if because it doesn't allow multiple criteria -
447 # it's only required if policy is SimpleScaling and state is present
448 if not module.params["scaling_adjustment"]:
449 module.fail_json(
450 msg="scaling_adjustment is required when policy_type is SimpleScaling and state is present"
451 )
452 params["ScalingAdjustment"] = module.params["scaling_adjustment"]
453 if module.params["cooldown"]:
454 params["Cooldown"] = module.params["cooldown"]
455
456 elif policy_type == "StepScaling":
457 if not module.params["step_adjustments"]:
458 module.fail_json(msg="step_adjustments is required when policy_type is StepScaling and state is present")
459 params["StepAdjustments"] = []
460 for step_adjustment in module.params["step_adjustments"]:
461 step_adjust_params = dict(ScalingAdjustment=step_adjustment["scaling_adjustment"])
462 if step_adjustment.get("lower_bound"):
463 step_adjust_params["MetricIntervalLowerBound"] = step_adjustment["lower_bound"]
464 if step_adjustment.get("upper_bound"):
465 step_adjust_params["MetricIntervalUpperBound"] = step_adjustment["upper_bound"]
466 params["StepAdjustments"].append(step_adjust_params)
467 if module.params["metric_aggregation"]:
468 params["MetricAggregationType"] = module.params["metric_aggregation"]
469 if module.params["estimated_instance_warmup"]:
470 params["EstimatedInstanceWarmup"] = module.params["estimated_instance_warmup"]
471
472 elif policy_type == "TargetTrackingScaling":
473 if not module.params["target_tracking_config"]:
474 module.fail_json(
475 msg="target_tracking_config is required when policy_type is TargetTrackingScaling and state is present"
476 )
477 else:
478 params["TargetTrackingConfiguration"] = build_target_specification(
479 module.params.get("target_tracking_config")
480 )
481 if module.params["estimated_instance_warmup"]:
482 params["EstimatedInstanceWarmup"] = module.params["estimated_instance_warmup"]
483
484 # Ensure idempotency with policies
485 try:
486 policies = connection.describe_policies(
487 aws_retry=True, AutoScalingGroupName=asg_name, PolicyNames=[policy_name]
488 )["ScalingPolicies"]
489 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
490 module.fail_json_aws(e, msg=f"Failed to obtain autoscaling policy {policy_name}")
491
492 before = after = {}
493 if not policies:
494 changed = True
495 else:
496 policy = policies[0]
497 for key, old_value in params.items():
498 if old_value != policy.get(key):
499 changed = True
500 before[key] = old_value
501 after[key] = policy.get(key)
502
503 if changed:
504 try:
505 connection.put_scaling_policy(aws_retry=True, **params)
506 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
507 module.fail_json_aws(e, msg="Failed to create autoscaling policy")
508
509 try:
510 policies = connection.describe_policies(
511 aws_retry=True, AutoScalingGroupName=asg_name, PolicyNames=[policy_name]
512 )["ScalingPolicies"]
513 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
514 module.fail_json_aws(e, msg=f"Failed to obtain autoscaling policy {policy_name}")
515
516 policy = camel_dict_to_snake_dict(policies[0])
517 # Backward compatible return values
518 policy["arn"] = policy["policy_arn"]
519 policy["as_name"] = policy["auto_scaling_group_name"]
520 policy["name"] = policy["policy_name"]
521
522 if before and after:
523 module.exit_json(changed=changed, diff=dict(before=before, after=after), **policy)
524 else:
525 module.exit_json(changed=changed, **policy)
526
527
528 def delete_scaling_policy(connection, module):
529 policy_name = module.params.get("name")
530
531 try:
532 policy = connection.describe_policies(aws_retry=True, PolicyNames=[policy_name])
533 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
534 module.fail_json_aws(e, msg=f"Failed to obtain autoscaling policy {policy_name}")
535
536 if policy["ScalingPolicies"]:
537 try:
538 connection.delete_policy(
539 aws_retry=True,
540 AutoScalingGroupName=policy["ScalingPolicies"][0]["AutoScalingGroupName"],
541 PolicyName=policy_name,
542 )
543 module.exit_json(changed=True)
544 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
545 module.fail_json_aws(e, msg="Failed to delete autoscaling policy")
546
547 module.exit_json(changed=False)
548
549
550 def main():
551 step_adjustment_spec = dict(
552 lower_bound=dict(type="int"), upper_bound=dict(type="int"), scaling_adjustment=dict(type="int", required=True)
553 )
554
555 predefined_metric_spec = dict(
556 predefined_metric_type=dict(
557 type="str",
558 choices=[
559 "ASGAverageCPUUtilization",
560 "ASGAverageNetworkIn",
561 "ASGAverageNetworkOut",
562 "ALBRequestCountPerTarget",
563 ],
564 required=True,
565 ),
566 resource_label=dict(type="str"),
567 )
568 customized_metric_spec = dict(
569 metric_name=dict(type="str", required=True),
570 namespace=dict(type="str", required=True),
571 statistic=dict(type="str", required=True, choices=["Average", "Minimum", "Maximum", "SampleCount", "Sum"]),
572 dimensions=dict(type="list", elements="dict"),
573 unit=dict(type="str"),
574 )
575
576 target_tracking_spec = dict(
577 disable_scalein=dict(type="bool"),
578 target_value=dict(type="float", required=True),
579 predefined_metric_spec=dict(type="dict", options=predefined_metric_spec),
580 customized_metric_spec=dict(type="dict", options=customized_metric_spec),
581 )
582
583 argument_spec = dict(
584 name=dict(required=True),
585 adjustment_type=dict(choices=["ChangeInCapacity", "ExactCapacity", "PercentChangeInCapacity"]),
586 asg_name=dict(),
587 scaling_adjustment=dict(type="int"),
588 min_adjustment_step=dict(type="int"),
589 cooldown=dict(type="int"),
590 state=dict(default="present", choices=["present", "absent"]),
591 metric_aggregation=dict(default="Average", choices=["Minimum", "Maximum", "Average"]),
592 policy_type=dict(default="SimpleScaling", choices=["SimpleScaling", "StepScaling", "TargetTrackingScaling"]),
593 target_tracking_config=dict(type="dict", options=target_tracking_spec),
594 step_adjustments=dict(type="list", options=step_adjustment_spec, elements="dict"),
595 estimated_instance_warmup=dict(type="int"),
596 )
597
598 module = AnsibleAWSModule(argument_spec=argument_spec, required_if=[["state", "present", ["asg_name"]]])
599
600 connection = module.client("autoscaling", retry_decorator=AWSRetry.jittered_backoff())
601 state = module.params.get("state")
602
603 if state == "present":
604 create_scaling_policy(connection, module)
605 elif state == "absent":
606 delete_scaling_policy(connection, module)
607
608
609 if __name__ == "__main__":
610 main()