
    VhZ                         d Z dZdZ	 ddlZddlmZ ddlmZ ddl	m
Z d Zd	 Zd
 Zd Zedk(  r e        yy# e$ r Y 3w xY w)a  
module: autoscaling_policy
short_description: Create or delete AWS scaling policies for Autoscaling groups
version_added: 1.0.0
description:
  - Can create or delete scaling policies for autoscaling groups.
  - Referenced autoscaling groups must already exist.
  - Prior to release 5.0.0 this module was called C(community.aws.ec2_scaling_policy).
    The usage did not change.
author:
  - Zacharie Eakin (@zeekin)
  - Will Thames (@willthames)
options:
  state:
    type: str
    description:
      - Register or deregister the policy.
    choices: ['present', 'absent']
    default: 'present'
  name:
    type: str
    description:
      - Unique name for the scaling policy.
    required: true
  asg_name:
    type: str
    description:
      - Name of the associated autoscaling group.
      - Required if I(state) is C(present).
  adjustment_type:
    type: str
    description:
      - The type of change in capacity of the autoscaling group.
      - Required if I(state) is C(present).
    choices:
      - ChangeInCapacity
      - ExactCapacity
      - PercentChangeInCapacity
  scaling_adjustment:
    type: int
    description:
      - The amount by which the autoscaling group is adjusted by the policy.
      - A negative number has the effect of scaling down the ASG.
      - Units are numbers of instances for C(ExactCapacity) or C(ChangeInCapacity) or percent
        of existing instances for C(PercentChangeInCapacity).
      - Required when I(policy_type) is C(SimpleScaling).
  min_adjustment_step:
    type: int
    description:
      - Minimum amount of adjustment when policy is triggered.
      - Only used when I(adjustment_type) is C(PercentChangeInCapacity).
  cooldown:
    type: int
    description:
      - The minimum period of time (in seconds) between which autoscaling actions can take place.
      - Only used when I(policy_type) is C(SimpleScaling).
  policy_type:
    type: str
    description:
      - Auto scaling adjustment policy.
    choices:
      - StepScaling
      - SimpleScaling
      - TargetTrackingScaling
    default: SimpleScaling
  metric_aggregation:
    type: str
    description:
      - The aggregation type for the CloudWatch metrics.
      - Only used when I(policy_type) is not C(SimpleScaling).
    choices:
      - Minimum
      - Maximum
      - Average
    default: Average
  step_adjustments:
    type: list
    description:
      - List of dicts containing I(lower_bound), I(upper_bound) and I(scaling_adjustment).
      - Intervals must not overlap or have a gap between them.
      - At most, one item can have an undefined I(lower_bound).
        If any item has a negative lower_bound, then there must be a step adjustment with an undefined I(lower_bound).
      - At most, one item can have an undefined I(upper_bound).
        If any item has a positive upper_bound, then there must be a step adjustment with an undefined I(upper_bound).
      - The bounds are the amount over the alarm threshold at which the adjustment will trigger.
        This means that for an alarm threshold of 50, triggering at 75 requires a lower bound of 25.
        See U(http://docs.aws.amazon.com/AutoScaling/latest/APIReference/API_StepAdjustment.html).
    elements: dict
    suboptions:
      lower_bound:
        type: int
        description:
          - The lower bound for the difference between the alarm threshold and
            the CloudWatch metric.
      upper_bound:
        type: int
        description:
          - The upper bound for the difference between the alarm threshold and
            the CloudWatch metric.
      scaling_adjustment:
        type: int
        description:
          - The amount by which to scale.
        required: true
  target_tracking_config:
    type: dict
    description:
      - Allows you to specify a I(target_tracking_config) for autoscaling policies in AWS.
      - I(target_tracking_config) can accept nested dicts for I(customized_metric_spec) or I(predefined_metric_spec).
        Each specification aligns with their boto3 equivalent.
      - Required when I(TargetTrackingScaling) policy is specified.
    version_added: 4.1.0
    suboptions:
      customized_metric_spec:
        type: dict
        description:
          - Specify a dict will be passed in as a call for C(TargetTrackingConfiguration).
        suboptions:
            metric_name:
              type: str
              description:
                - The name of the metric.
              required: true
            namespace:
              type: str
              description:
                - The namespace of the metric.
              required: true
            statistic:
              type: str
              description:
                - The statistic of the metric.
              required: true
              choices:
                - Average
                - Minimum
                - Maximum
                - SampleCount
                - Sum
            dimensions:
              type: list
              description:
                - The dimensions of the metric. The element of the list should be a dict.
              elements: dict
            unit:
              type: str
              description:
                - The unit of the metric. Reference AmazonCloudWatch API for valid Units.
      predefined_metric_spec:
        type: dict
        description:
          - Specify a dict will be passed in as a call for I(TargetTrackingConfiguration).
        suboptions:
          predefined_metric_type:
            type: str
            required: true
            description:
              - Required if C(predefined_metric_spec) is used.
            choices:
              - ASGAverageCPUUtilization
              - ASGAverageNetworkIn
              - ASGAverageNetworkOut
              - ALBRequestCountPerTarget
          resource_label:
            type: str
            description:
              - Uniquely identifies a specific ALB target group from which to determine the average request count served by your Auto Scaling group.
              - You can't specify a resource label unless the target group is attached to the Auto Scaling group.
      target_value:
        type: float
        description:
          - Specify a float number for target utilization.
          - Required when I(target_tracking_config) is specified.
        required: true
      disable_scalein:
        type: bool
        description:
          - Indicate whether scaling in by the target tracking scaling policy is disabled.
  estimated_instance_warmup:
    type: int
    description:
      - The estimated time, in seconds, until a newly launched instance can contribute to the CloudWatch metrics.
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.boto3
a|  
- name: Simple Scale Down policy
  community.aws.autoscaling_policy:
    state: present
    region: US-XXX
    name: "scaledown-policy"
    adjustment_type: "ChangeInCapacity"
    asg_name: "application-asg"
    scaling_adjustment: -1
    min_adjustment_step: 1
    cooldown: 300

# For an alarm with a breach threshold of 20, the
# following creates a stepped policy:
# From 20-40 (0-20 above threshold), increase by 50% of existing capacity
# From 41-infinity, increase by 100% of existing capacity
- community.aws.autoscaling_policy:
    state: present
    region: US-XXX
    name: "step-scale-up-policy"
    policy_type: StepScaling
    metric_aggregation: Maximum
    step_adjustments:
      - upper_bound: 20
        scaling_adjustment: 50
      - lower_bound: 20
        scaling_adjustment: 100
    adjustment_type: "PercentChangeInCapacity"
    asg_name: "application-asg"

- name: create TargetTracking predefined policy
  community.aws.autoscaling_policy:
    name: "predefined-policy-1"
    policy_type: TargetTrackingScaling
    target_tracking_config:
      predefined_metric_spec:
        predefined_metric_type: ASGAverageCPUUtilization
      target_value: 98.0
    asg_name: "asg-test-1"
  register: result

- name: create TargetTracking predefined policy with resource_label
  community.aws.autoscaling_policy:
    name: "predefined-policy-1"
    policy_type: TargetTrackingScaling
    target_tracking_config:
      predefined_metric_spec:
        predefined_metric_type: ALBRequestCountPerTarget
        resource_label: app/my-alb/778d41231d141a0f/targetgroup/my-alb-target-group/942f017f100becff
      target_value: 98.0
    asg_name: "asg-test-1"
  register: result

- name: create TargetTrackingScaling custom policy
  community.aws.autoscaling_policy:
    name: "custom-policy-1"
    policy_type: TargetTrackingScaling
    target_tracking_config:
      customized_metric_spec:
        metric_name: metric_1
        namespace: namespace_1
        statistic: Minimum
        unit: Gigabits
        dimensions: [{'Name': 'dimension1', 'Value': 'value1'}]
      disable_scalein: true
      target_value: 98.0
    asg_name: asg-test-1
  register: result
al
  
adjustment_type:
  description: Scaling policy adjustment type.
  returned: always
  type: str
  sample: PercentChangeInCapacity
alarms:
  description: Cloudwatch alarms related to the policy.
  returned: always
  type: complex
  contains:
    alarm_name:
      description: Name of the Cloudwatch alarm.
      returned: always
      type: str
      sample: cpu-very-high
    alarm_arn:
      description: ARN of the Cloudwatch alarm.
      returned: always
      type: str
      sample: arn:aws:cloudwatch:us-east-2:1234567890:alarm:cpu-very-high
arn:
  description: ARN of the scaling policy. Provided for backward compatibility, value is the same as I(policy_arn).
  returned: always
  type: str
  sample: arn:aws:autoscaling:us-east-2:123456789012:scalingPolicy:59e37526-bd27-42cf-adca-5cd3d90bc3b9:autoScalingGroupName/app-asg:policyName/app-policy
as_name:
  description: Auto Scaling Group name. Provided for backward compatibility, value is the same as I(auto_scaling_group_name).
  returned: always
  type: str
  sample: app-asg
auto_scaling_group_name:
  description: Name of Auto Scaling Group.
  returned: always
  type: str
  sample: app-asg
metric_aggregation_type:
  description: Method used to aggregate metrics.
  returned: when I(policy_type) is C(StepScaling)
  type: str
  sample: Maximum
name:
  description: Name of the scaling policy. Provided for backward compatibility, value is the same as I(policy_name).
  returned: always
  type: str
  sample: app-policy
policy_arn:
  description: ARN of scaling policy.
  returned: always
  type: str
  sample: arn:aws:autoscaling:us-east-2:123456789012:scalingPolicy:59e37526-bd27-42cf-adca-5cd3d90bc3b9:autoScalingGroupName/app-asg:policyName/app-policy
policy_name:
  description: Name of scaling policy.
  returned: always
  type: str
  sample: app-policy
policy_type:
  description: Type of auto scaling policy.
  returned: always
  type: str
  sample: StepScaling
scaling_adjustment:
  description: Adjustment to make when alarm is triggered.
  returned: When I(policy_type) is C(SimpleScaling)
  type: int
  sample: 1
step_adjustments:
  description: List of step adjustments.
  returned: always
  type: complex
  contains:
    metric_interval_lower_bound:
      description: Lower bound for metric interval.
      returned: if step has a lower bound
      type: float
      sample: 20.0
    metric_interval_upper_bound:
      description: Upper bound for metric interval.
      returned: if step has an upper bound
      type: float
      sample: 40.0
    scaling_adjustment:
      description: Adjustment to make if this step is reached.
      returned: always
      type: int
      sample: 50
    N)camel_dict_to_snake_dict)AWSRetry)AnsibleCommunityAWSModulec                    t               }| j                  d      r| d   |d<   | j                  d      r	| d   |d<   nd|d<   | d   St               |d<   | d   j                  d      r| d   d   |d   d	<   | d   j                  d
      r| d   d
   |d   d<   |S | d   t               |d<   | d   j                  d      r| d   d   |d   d<   | d   j                  d      r| d   d   |d   d<   | d   j                  d      r| d   d   |d   d<   | d   j                  d      r| d   d   |d   d<   | d   j                  d      r| d   d   |d   d<   |S )Ntarget_valueTargetValuedisable_scaleinDisableScaleInFpredefined_metric_specPredefinedMetricSpecificationpredefined_metric_typePredefinedMetricTyperesource_labelResourceLabelcustomized_metric_specCustomizedMetricSpecificationmetric_name
MetricName	namespace	Namespace
dimensions
Dimensions	statistic	StatisticunitUnit)dictget)target_tracking_configtargetTrackingConfigs     t/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/aws/plugins/modules/autoscaling_policy.pybuild_target_specificationr"   m  s.     6!!.1.D^.T]+!!"341GHY1Z-. 27-.67C@D<=!":;??@XY\r(]&]( !@ABXY "":;??@PQUk(VV  !@A/R@  9 
  8	9	E@D<=!":;??NRh(SS !@A,O "":;??LQg(RR !@A+N "":;??MRh(SS !@A,O "":;??LQg(RR !@A+N "":;??GLb(MM !@A&I      c                    d}|j                   d   }|j                   d   }|j                   d   }|dk(  rt        |||      }nt        ||||j                   d         }|j                   d   d	k(  r!|j                   d
   r|j                   d
   |d<   |dk(  rW|j                   d   s|j                  d       |j                   d   |d<   |j                   d   rZ|j                   d   |d<   nF|dk(  r|j                   d   s|j                  d       g |d<   |j                   d   D ]W  }t        |d         }|j                  d      r|d   |d<   |j                  d      r|d   |d<   |d   j	                  |       Y |j                   d   r|j                   d   |d<   |j                   d   r|j                   d   |d<   no|dk(  rj|j                   d    s|j                  d!       n't        |j                   j                  d             |d"<   |j                   d   r|j                   d   |d<   	 | j                  d#||g$      d%   }	i x}}	sd#}nM|	d'   }|j                         D ]5  \  }}||j                  |      k7  sd#}|||<   |j                  |      ||<   7 |r.	  | j                  d2d(d#i| 	 | j                  d#||g$      d%   }	t        |	d'         }|d*   |d+<   |d,   |d-<   |d.   |d<   |r#|r! |j                  d2|t        ||/      d0| y  |j                  d2d1|i| y # t        j                  j                  t        j                  j                  f$ r!}
|j                  |
d&|        Y d }
~
9d }
~
ww xY w# t        j                  j                  t        j                  j                  f$ r}
|j                  |
d)       Y d }
~
$d }
~
ww xY w# t        j                  j                  t        j                  j                  f$ r!}
|j                  |
d&|        Y d }
~
fd }
~
ww xY w)3NFasg_namepolicy_typenameTargetTrackingScaling)
PolicyName
PolicyTypeAutoScalingGroupNameadjustment_type)r)   r*   r+   AdjustmentTypePercentChangeInCapacitymin_adjustment_stepMinAdjustmentMagnitudeSimpleScalingscaling_adjustmentzUscaling_adjustment is required when policy_type is SimpleScaling and state is presentmsgScalingAdjustmentcooldownCooldownStepScalingstep_adjustmentszQstep_adjustments is required when policy_type is StepScaling and state is presentStepAdjustments)r5   lower_boundMetricIntervalLowerBoundupper_boundMetricIntervalUpperBoundmetric_aggregationMetricAggregationTypeestimated_instance_warmupEstimatedInstanceWarmupr   zatarget_tracking_config is required when policy_type is TargetTrackingScaling and state is presentTargetTrackingConfigurationT)	aws_retryr+   PolicyNamesScalingPolicies$Failed to obtain autoscaling policy r   rD   z#Failed to create autoscaling policy
policy_arnarnauto_scaling_group_nameas_namepolicy_name)beforeafter)changeddiffrO    )paramsr   	fail_jsonr   appendr"   describe_policiesbotocore
exceptionsClientErrorBotoCoreErrorfail_json_awsitemsput_scaling_policyr   	exit_json)
connectionmodulerO   r%   r&   rL   rR   step_adjustmentstep_adjust_paramspolicieserM   rN   policykey	old_values                   r!   create_scaling_policyrg     s   G}}Z(H--.K--'K--[cd""!)!==):;	
 }}&'+DD==.//5}}=R/SF+,o% }}12k   '-mm4H&I"#==$!'z!:F:		%}}/0!tu$& !%}}-?@ 	AO!%H\8]!^""=1APQ^A_"#=>""=1APQ^A_"#=>$%,,-?@	A ==-..4mm<P.QF*+==4506>Y0ZF,-	/	/}}56w   5O!!":;5F01 ==4506>Y0ZF,-Z//} 0 

 FU!$lln 	-NCFJJsO+'s#ZZ_c
		- 	O)J))CDCFC	^!33XK= 4 !H &hqk2F<(F5M89F9M*F6N%Zt6/OZSYZ33F3I ++X-@-@-N-NO ZQ&J;-$XYYZ" ##//1D1D1R1RS 	O  (M NN	O ##//1D1D1R1RS 	^  *N{m(\ ]]	^sH   6L4 'N <O' 47N+NN7O$OO$'7P?P::P?c                 T   |j                   j                  d      }	 | j                  d|g      }d   r0	 | j                  d|d   d   d   |	       |j                  d
       |j                  d
       y # t        j                  j
                  t        j                  j                  f$ r }|j                  |d|        Y d }~d }~ww xY w# t        j                  j
                  t        j                  j                  f$ r}|j                  |d       Y d }~d }~ww xY w)Nr'   T)rD   rE   rG   r3   rF   r   r+   )rD   r+   r)   )rO   z#Failed to delete autoscaling policyF)
rR   r   rU   rV   rW   rX   rY   rZ   delete_policyr]   )r^   r_   rL   rd   rc   s        r!   delete_scaling_policyrj     s-   --##F+KZ--;--X  	O$$%+,=%>q%ABX%Y& % 
 T* U# ++X-@-@-N-NO ZQ&J;-$XYYZ ##//1D1D1R1RS 	O  (M NN	Os.   A9 /C 97C0CC7D'
D""D'c                     t        t        d      t        d      t        dd            } t        t        dg dd      t        d      	      }t        t        dd      t        dd      t        ddg d
      t        dd      t        d            }t        t        d      t        dd      t        d|      t        d|            }t        t        d      t        g d      t               t        d      t        d      t        d      t        dddg      t        dg d      t        dg d      t        d|      t        d| d      t        d            }t        |d dd!ggg"      }|j                  d#t        j                         $      }|j
                  j                  d       }|dk(  rt        ||       y |dk(  rt        ||       y y )%Nint)typeT)rm   required)r;   r=   r2   str)ASGAverageCPUUtilizationASGAverageNetworkInASGAverageNetworkOutALBRequestCountPerTarget)rm   choicesrn   )r   r   )AverageMinimumMaximumSampleCountSum)rm   rn   rt   listr   )rm   elements)r   r   r   r   r   boolfloat)rm   options)r	   r   r   r   )rn   )ChangeInCapacityExactCapacityr.   )rt   presentabsent)defaultrt   ru   )rv   rw   ru   r1   )r1   r8   r(   )rm   r~   r{   )r'   r,   r%   r2   r/   r6   stater?   r&   r   r9   rA   r   r%   )argument_specrequired_ifautoscaling)retry_decorator)	r   AnsibleAWSModuleclientr   jittered_backoffrR   r   rg   rj   )step_adjustment_specr   r   target_tracking_specr   r_   r^   r   s           r!   mainr   &  s   e$$E2BW[afquWv "# 	 
 ' "ed3ED1ED:qrVf5u  &)w6#9OP#9OP	 4 %efU+ e,5!9y(.CD	;\]:st#9MN63GRXY"&E"2M MR[^h]iHjGklF}h>W>W>YZJMMg&E	j&1	(	j&1 
r#   __main__)DOCUMENTATIONEXAMPLESRETURNrV   ImportError0ansible.module_utils.common.dict_transformationsr   ;ansible_collections.amazon.aws.plugins.module_utils.retriesr   >ansible_collections.community.aws.plugins.module_utils.modulesr   r   r"   rg   rj   r   __name__rQ   r#   r!   <module>r      su   zxDLV
p	 V P x7 tf4R$,82v zF }  		s   8 A A 