Debian Codegraph @

ansible_collections/community/aws/plugins/modules/application_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 ---
9 module: application_autoscaling_policy
10 version_added: 1.0.0
11 short_description: Manage Application Auto Scaling Scaling Policies
12 notes:
13 - For more details of the parameters and returns see
14 U(http://boto3.readthedocs.io/en/latest/reference/services/application-autoscaling.html#ApplicationAutoScaling.Client.put_scaling_policy)
15 description:
16 - Creates, updates or removes a Scaling Policy.
17 - Prior to release 5.0.0 this module was called C(community.aws.aws_application_scaling_policy).
18 The usage did not change.
19 author:
20 - Gustavo Maia (@gurumaia)
21 - Chen Leibovich (@chenl87)
22 options:
23 state:
24 description: Whether a policy should be C(present) or C(absent).
25 required: true
26 choices: ['absent', 'present']
27 type: str
28 policy_name:
29 description: The name of the scaling policy.
30 required: true
31 type: str
32 service_namespace:
33 description: The namespace of the AWS service.
34 required: true
35 choices: ['ecs', 'elasticmapreduce', 'ec2', 'appstream', 'dynamodb']
36 type: str
37 resource_id:
38 description: The identifier of the resource associated with the scalable target.
39 required: true
40 type: str
41 scalable_dimension:
42 description: The scalable dimension associated with the scalable target.
43 required: true
44 choices: [ 'ecs:service:DesiredCount',
45 'ec2:spot-fleet-request:TargetCapacity',
46 'elasticmapreduce:instancegroup:InstanceCount',
47 'appstream:fleet:DesiredCapacity',
48 'dynamodb:table:ReadCapacityUnits',
49 'dynamodb:table:WriteCapacityUnits',
50 'dynamodb:index:ReadCapacityUnits',
51 'dynamodb:index:WriteCapacityUnits']
52 type: str
53 policy_type:
54 description: The policy type.
55 required: true
56 choices: ['StepScaling', 'TargetTrackingScaling']
57 type: str
58 step_scaling_policy_configuration:
59 description: A step scaling policy. This parameter is required if you are creating a policy and I(policy_type=StepScaling).
60 required: false
61 type: dict
62 target_tracking_scaling_policy_configuration:
63 description:
64 - A target tracking policy. This parameter is required if you are creating a new policy and I(policy_type=TargetTrackingScaling).
65 - 'Full documentation of the suboptions can be found in the API documentation:'
66 - 'U(https://docs.aws.amazon.com/autoscaling/application/APIReference/API_TargetTrackingScalingPolicyConfiguration.html)'
67 required: false
68 type: dict
69 suboptions:
70 CustomizedMetricSpecification:
71 description: The metric to use if using a customized metric.
72 type: dict
73 DisableScaleIn:
74 description: Whether scaling-in should be disabled.
75 type: bool
76 PredefinedMetricSpecification:
77 description: The metric to use if using a predefined metric.
78 type: dict
79 ScaleInCooldown:
80 description: The time (in seconds) to wait after scaling-in before another scaling action can occur.
81 type: int
82 ScaleOutCooldown:
83 description: The time (in seconds) to wait after scaling-out before another scaling action can occur.
84 type: int
85 TargetValue:
86 description: The target value for the metric.
87 type: float
88 minimum_tasks:
89 description: The minimum value to scale to in response to a scale in event.
90 This parameter is required if you are creating a first new policy for the specified service.
91 required: false
92 type: int
93 maximum_tasks:
94 description: The maximum value to scale to in response to a scale out event.
95 This parameter is required if you are creating a first new policy for the specified service.
96 required: false
97 type: int
98 override_task_capacity:
99 description:
100 - Whether or not to override values of minimum and/or maximum tasks if it's already set.
101 - Defaults to C(false).
102 required: false
103 type: bool
104 extends_documentation_fragment:
105 - amazon.aws.common.modules
106 - amazon.aws.region.modules
107 - amazon.aws.boto3
108 """
109
110 EXAMPLES = r"""
111 # Note: These examples do not set authentication details, see the AWS Guide for details.
112
113 # Create step scaling policy for ECS Service
114 - name: scaling_policy
115 community.aws.application_autoscaling_policy:
116 state: present
117 policy_name: test_policy
118 service_namespace: ecs
119 resource_id: service/poc-pricing/test-as
120 scalable_dimension: ecs:service:DesiredCount
121 policy_type: StepScaling
122 minimum_tasks: 1
123 maximum_tasks: 6
124 step_scaling_policy_configuration:
125 AdjustmentType: ChangeInCapacity
126 StepAdjustments:
127 - MetricIntervalUpperBound: 123
128 ScalingAdjustment: 2
129 - MetricIntervalLowerBound: 123
130 ScalingAdjustment: -2
131 Cooldown: 123
132 MetricAggregationType: Average
133
134 # Create target tracking scaling policy for ECS Service
135 - name: scaling_policy
136 community.aws.application_autoscaling_policy:
137 state: present
138 policy_name: test_policy
139 service_namespace: ecs
140 resource_id: service/poc-pricing/test-as
141 scalable_dimension: ecs:service:DesiredCount
142 policy_type: TargetTrackingScaling
143 minimum_tasks: 1
144 maximum_tasks: 6
145 target_tracking_scaling_policy_configuration:
146 TargetValue: 60
147 PredefinedMetricSpecification:
148 PredefinedMetricType: ECSServiceAverageCPUUtilization
149 ScaleOutCooldown: 60
150 ScaleInCooldown: 60
151
152 # Remove scalable target for ECS Service
153 - name: scaling_policy
154 community.aws.application_autoscaling_policy:
155 state: absent
156 policy_name: test_policy
157 policy_type: StepScaling
158 service_namespace: ecs
159 resource_id: service/cluster-name/service-name
160 scalable_dimension: ecs:service:DesiredCount
161 """
162
163 RETURN = r"""
164 alarms:
165 description: List of the CloudWatch alarms associated with the scaling policy
166 returned: when state present
167 type: complex
168 contains:
169 alarm_arn:
170 description: The Amazon Resource Name (ARN) of the alarm
171 returned: when state present
172 type: str
173 alarm_name:
174 description: The name of the alarm
175 returned: when state present
176 type: str
177 service_namespace:
178 description: The namespace of the AWS service.
179 returned: when state present
180 type: str
181 sample: ecs
182 resource_id:
183 description: The identifier of the resource associated with the scalable target.
184 returned: when state present
185 type: str
186 sample: service/cluster-name/service-name
187 scalable_dimension:
188 description: The scalable dimension associated with the scalable target.
189 returned: when state present
190 type: str
191 sample: ecs:service:DesiredCount
192 policy_arn:
193 description: The Amazon Resource Name (ARN) of the scaling policy..
194 returned: when state present
195 type: str
196 policy_name:
197 description: The name of the scaling policy.
198 returned: when state present
199 type: str
200 policy_type:
201 description: The policy type.
202 returned: when state present
203 type: str
204 min_capacity:
205 description: The minimum value to scale to in response to a scale in event. Required if I(state) is C(present).
206 returned: when state present
207 type: int
208 sample: 1
209 max_capacity:
210 description: The maximum value to scale to in response to a scale out event. Required if I(state) is C(present).
211 returned: when state present
212 type: int
213 sample: 2
214 role_arn:
215 description: The ARN of an IAM role that allows Application Auto Scaling to modify the scalable target on your behalf. Required if I(state) is C(present).
216 returned: when state present
217 type: str
218 sample: arn:aws:iam::123456789012:role/roleName
219 step_scaling_policy_configuration:
220 description: The step scaling policy.
221 returned: when state present and the policy type is StepScaling
222 type: complex
223 contains:
224 adjustment_type:
225 description: The adjustment type
226 returned: when state present and the policy type is StepScaling
227 type: str
228 sample: "ChangeInCapacity, PercentChangeInCapacity, ExactCapacity"
229 cooldown:
230 description: The amount of time, in seconds, after a scaling activity completes
231 where previous trigger-related scaling activities can influence future scaling events
232 returned: when state present and the policy type is StepScaling
233 type: int
234 sample: 60
235 metric_aggregation_type:
236 description: The aggregation type for the CloudWatch metrics
237 returned: when state present and the policy type is StepScaling
238 type: str
239 sample: "Average, Minimum, Maximum"
240 step_adjustments:
241 description: A set of adjustments that enable you to scale based on the size of the alarm breach
242 returned: when state present and the policy type is StepScaling
243 type: list
244 elements: dict
245 target_tracking_scaling_policy_configuration:
246 description: The target tracking policy.
247 returned: when state present and the policy type is TargetTrackingScaling
248 type: complex
249 contains:
250 predefined_metric_specification:
251 description: A predefined metric
252 returned: when state present and the policy type is TargetTrackingScaling
253 type: complex
254 contains:
255 predefined_metric_type:
256 description: The metric type
257 returned: when state present and the policy type is TargetTrackingScaling
258 type: str
259 sample: "ECSServiceAverageCPUUtilization, ECSServiceAverageMemoryUtilization"
260 resource_label:
261 description: Identifies the resource associated with the metric type
262 returned: when metric type is ALBRequestCountPerTarget
263 type: str
264 scale_in_cooldown:
265 description: The amount of time, in seconds, after a scale in activity completes before another scale in activity can start
266 returned: when state present and the policy type is TargetTrackingScaling
267 type: int
268 sample: 60
269 scale_out_cooldown:
270 description: The amount of time, in seconds, after a scale out activity completes before another scale out activity can start
271 returned: when state present and the policy type is TargetTrackingScaling
272 type: int
273 sample: 60
274 target_value:
275 description: The target value for the metric
276 returned: when state present and the policy type is TargetTrackingScaling
277 type: int
278 sample: 70
279 creation_time:
280 description: The Unix timestamp for when the scalable target was created.
281 returned: when state present
282 type: str
283 sample: '2017-09-28T08:22:51.881000-03:00'
284 """
285
286 try:
287 import botocore
288 except ImportError:
289 pass # handled by AnsibleAWSModule
290
291 from ansible.module_utils.common.dict_transformations import _camel_to_snake
292 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
293
294 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
295
296
297 # Merge the results of the scalable target creation and policy deletion/creation
298 # There's no risk in overriding values since mutual keys have the same values in our case
299 def merge_results(scalable_target_result, policy_result):
300 changed = bool(scalable_target_result["changed"] or policy_result["changed"])
301
302 merged_response = scalable_target_result["response"].copy()
303 merged_response.update(policy_result["response"])
304
305 return {"changed": changed, "response": merged_response}
306
307
308 def delete_scaling_policy(connection, module):
309 changed = False
310 try:
311 scaling_policy = connection.describe_scaling_policies(
312 ServiceNamespace=module.params.get("service_namespace"),
313 ResourceId=module.params.get("resource_id"),
314 ScalableDimension=module.params.get("scalable_dimension"),
315 PolicyNames=[module.params.get("policy_name")],
316 MaxResults=1,
317 )
318 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
319 module.fail_json_aws(e, msg="Failed to describe scaling policies")
320
321 if scaling_policy["ScalingPolicies"]:
322 try:
323 connection.delete_scaling_policy(
324 ServiceNamespace=module.params.get("service_namespace"),
325 ResourceId=module.params.get("resource_id"),
326 ScalableDimension=module.params.get("scalable_dimension"),
327 PolicyName=module.params.get("policy_name"),
328 )
329 changed = True
330 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
331 module.fail_json_aws(e, msg="Failed to delete scaling policy")
332
333 return {"changed": changed}
334
335
336 def create_scalable_target(connection, module):
337 changed = False
338
339 try:
340 scalable_targets = connection.describe_scalable_targets(
341 ServiceNamespace=module.params.get("service_namespace"),
342 ResourceIds=[
343 module.params.get("resource_id"),
344 ],
345 ScalableDimension=module.params.get("scalable_dimension"),
346 )
347 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
348 module.fail_json_aws(e, msg="Failed to describe scalable targets")
349
350 # Scalable target registration will occur if:
351 # 1. There is no scalable target registered for this service
352 # 2. A scalable target exists, different min/max values are defined and override is set to "yes"
353 if not scalable_targets["ScalableTargets"] or (
354 module.params.get("override_task_capacity")
355 and (
356 scalable_targets["ScalableTargets"][0]["MinCapacity"] != module.params.get("minimum_tasks")
357 or scalable_targets["ScalableTargets"][0]["MaxCapacity"] != module.params.get("maximum_tasks")
358 )
359 ):
360 changed = True
361 try:
362 connection.register_scalable_target(
363 ServiceNamespace=module.params.get("service_namespace"),
364 ResourceId=module.params.get("resource_id"),
365 ScalableDimension=module.params.get("scalable_dimension"),
366 MinCapacity=module.params.get("minimum_tasks"),
367 MaxCapacity=module.params.get("maximum_tasks"),
368 )
369 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
370 module.fail_json_aws(e, msg="Failed to register scalable target")
371
372 try:
373 response = connection.describe_scalable_targets(
374 ServiceNamespace=module.params.get("service_namespace"),
375 ResourceIds=[
376 module.params.get("resource_id"),
377 ],
378 ScalableDimension=module.params.get("scalable_dimension"),
379 )
380 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
381 module.fail_json_aws(e, msg="Failed to describe scalable targets")
382
383 if response["ScalableTargets"]:
384 snaked_response = camel_dict_to_snake_dict(response["ScalableTargets"][0])
385 else:
386 snaked_response = {}
387
388 return {"changed": changed, "response": snaked_response}
389
390
391 def create_scaling_policy(connection, module):
392 try:
393 scaling_policy = connection.describe_scaling_policies(
394 ServiceNamespace=module.params.get("service_namespace"),
395 ResourceId=module.params.get("resource_id"),
396 ScalableDimension=module.params.get("scalable_dimension"),
397 PolicyNames=[module.params.get("policy_name")],
398 MaxResults=1,
399 )
400 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
401 module.fail_json_aws(e, msg="Failed to describe scaling policies")
402
403 changed = False
404
405 if scaling_policy["ScalingPolicies"]:
406 scaling_policy = scaling_policy["ScalingPolicies"][0]
407 # check if the input parameters are equal to what's already configured
408 for attr in (
409 "PolicyName",
410 "ServiceNamespace",
411 "ResourceId",
412 "ScalableDimension",
413 "PolicyType",
414 "StepScalingPolicyConfiguration",
415 "TargetTrackingScalingPolicyConfiguration",
416 ):
417 if attr in scaling_policy and scaling_policy[attr] != module.params.get(_camel_to_snake(attr)):
418 changed = True
419 scaling_policy[attr] = module.params.get(_camel_to_snake(attr))
420 else:
421 changed = True
422 scaling_policy = {
423 "PolicyName": module.params.get("policy_name"),
424 "ServiceNamespace": module.params.get("service_namespace"),
425 "ResourceId": module.params.get("resource_id"),
426 "ScalableDimension": module.params.get("scalable_dimension"),
427 "PolicyType": module.params.get("policy_type"),
428 "StepScalingPolicyConfiguration": module.params.get("step_scaling_policy_configuration"),
429 "TargetTrackingScalingPolicyConfiguration": module.params.get(
430 "target_tracking_scaling_policy_configuration"
431 ),
432 }
433
434 if changed:
435 try:
436 if module.params.get("step_scaling_policy_configuration"):
437 connection.put_scaling_policy(
438 PolicyName=scaling_policy["PolicyName"],
439 ServiceNamespace=scaling_policy["ServiceNamespace"],
440 ResourceId=scaling_policy["ResourceId"],
441 ScalableDimension=scaling_policy["ScalableDimension"],
442 PolicyType=scaling_policy["PolicyType"],
443 StepScalingPolicyConfiguration=scaling_policy["StepScalingPolicyConfiguration"],
444 )
445 elif module.params.get("target_tracking_scaling_policy_configuration"):
446 connection.put_scaling_policy(
447 PolicyName=scaling_policy["PolicyName"],
448 ServiceNamespace=scaling_policy["ServiceNamespace"],
449 ResourceId=scaling_policy["ResourceId"],
450 ScalableDimension=scaling_policy["ScalableDimension"],
451 PolicyType=scaling_policy["PolicyType"],
452 TargetTrackingScalingPolicyConfiguration=scaling_policy["TargetTrackingScalingPolicyConfiguration"],
453 )
454 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
455 module.fail_json_aws(e, msg="Failed to create scaling policy")
456
457 try:
458 response = connection.describe_scaling_policies(
459 ServiceNamespace=module.params.get("service_namespace"),
460 ResourceId=module.params.get("resource_id"),
461 ScalableDimension=module.params.get("scalable_dimension"),
462 PolicyNames=[module.params.get("policy_name")],
463 MaxResults=1,
464 )
465 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
466 module.fail_json_aws(e, msg="Failed to describe scaling policies")
467
468 if response["ScalingPolicies"]:
469 snaked_response = camel_dict_to_snake_dict(response["ScalingPolicies"][0])
470 else:
471 snaked_response = {}
472
473 return {"changed": changed, "response": snaked_response}
474
475
476 def main():
477 argument_spec = dict(
478 state=dict(type="str", required=True, choices=["present", "absent"]),
479 policy_name=dict(type="str", required=True),
480 service_namespace=dict(
481 type="str", required=True, choices=["appstream", "dynamodb", "ec2", "ecs", "elasticmapreduce"]
482 ),
483 resource_id=dict(type="str", required=True),
484 scalable_dimension=dict(
485 type="str",
486 required=True,
487 choices=[
488 "ecs:service:DesiredCount",
489 "ec2:spot-fleet-request:TargetCapacity",
490 "elasticmapreduce:instancegroup:InstanceCount",
491 "appstream:fleet:DesiredCapacity",
492 "dynamodb:table:ReadCapacityUnits",
493 "dynamodb:table:WriteCapacityUnits",
494 "dynamodb:index:ReadCapacityUnits",
495 "dynamodb:index:WriteCapacityUnits",
496 ],
497 ),
498 policy_type=dict(type="str", required=True, choices=["StepScaling", "TargetTrackingScaling"]),
499 step_scaling_policy_configuration=dict(type="dict"),
500 target_tracking_scaling_policy_configuration=dict(
501 type="dict",
502 options=dict(
503 CustomizedMetricSpecification=dict(type="dict"),
504 DisableScaleIn=dict(type="bool"),
505 PredefinedMetricSpecification=dict(type="dict"),
506 ScaleInCooldown=dict(type="int"),
507 ScaleOutCooldown=dict(type="int"),
508 TargetValue=dict(type="float"),
509 ),
510 ),
511 minimum_tasks=dict(type="int"),
512 maximum_tasks=dict(type="int"),
513 override_task_capacity=dict(type="bool"),
514 )
515
516 module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)
517
518 connection = module.client("application-autoscaling")
519
520 # Remove any target_tracking_scaling_policy_configuration suboptions that are None
521 policy_config_options = [
522 "CustomizedMetricSpecification",
523 "DisableScaleIn",
524 "PredefinedMetricSpecification",
525 "ScaleInCooldown",
526 "ScaleOutCooldown",
527 "TargetValue",
528 ]
529 if isinstance(module.params["target_tracking_scaling_policy_configuration"], dict):
530 for option in policy_config_options:
531 if module.params["target_tracking_scaling_policy_configuration"][option] is None:
532 module.params["target_tracking_scaling_policy_configuration"].pop(option)
533
534 if module.params.get("state") == "present":
535 # A scalable target must be registered prior to creating a scaling policy
536 scalable_target_result = create_scalable_target(connection, module)
537 policy_result = create_scaling_policy(connection, module)
538 # Merge the results of the scalable target creation and policy deletion/creation
539 # There's no risk in overriding values since mutual keys have the same values in our case
540 merged_result = merge_results(scalable_target_result, policy_result)
541 module.exit_json(**merged_result)
542 else:
543 policy_result = delete_scaling_policy(connection, module)
544 module.exit_json(**policy_result)
545
546
547 if __name__ == "__main__":
548 main()