
    Vh1U                       d Z dZdZddlZ	 ddlZddlmZ ddlm	Z	 ddlm
Z
 ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ  eddd      Z ej.                  d>i ed        Z ej.                  d>i ed        Z ej.                  d>i ed        Z ej.                  d>i ed        Z ej.                  d>i ed        Z ej.                  d>i ed        Z ej.                  d>i ed        Z ej.                  d>i ed        Z ej.                  d>i ed        Z  ej.                  d>i ed        Z! ej.                  d>i ed        Z" ej.                  d>i ed        Z# ej.                  d>i ed        Z$ ej.                  d>i ed        Z% ej.                  d>i ed        Z& ej.                  d>i ed         Z' ej.                  d>d!d"gied#        Z( ej.                  d>i ed$        Z) ej.                  d>i ed%        Z*d& Z+d' Z,d( Z-d) Z.d* Z/d+ Z0d, Z1d- Z2d. Z3d/ Z4d0 Z5d1 Z6d2 Z7d3 Z8d4 Z9d5 Z:d6 Z;d7 Z<d?d8Z=d9 Z>d: Z?d; Z@d< ZAeBd=k(  r eA        yy# e$ r Y bw xY w)@a@  
---
module: autoscaling_group
version_added: 5.0.0
short_description: Create or delete AWS AutoScaling Groups (ASGs)
description:
  - Can create or delete AWS AutoScaling Groups.
  - Can be used with the M(community.aws.autoscaling_launch_config) module to manage Launch Configurations.
  - Prior to release 5.0.0 this module was called M(community.aws.ec2_asg).
    The usage did not change.
  - This module was originally added to C(community.aws) in release 1.0.0.
author:
  - "Gareth Rushgrove (@garethr)"
options:
  state:
    description:
      - Register or deregister the instance.
    choices: ['present', 'absent']
    default: present
    type: str
  name:
    description:
      - Unique name for group to be created or deleted.
    aliases: ['group_name']
    required: true
    type: str
  load_balancers:
    description:
      - List of ELB names to use for the group. Use for classic load balancers.
    type: list
    elements: str
  target_group_arns:
    description:
      - List of target group ARNs to use for the group. Use for application load balancers.
    type: list
    elements: str
  availability_zones:
    description:
      - List of availability zone names in which to create the group.
      - Defaults to all the availability zones in the region if O(vpc_zone_identifier) is not set.
    type: list
    elements: str
  launch_config_name:
    description:
      - Name of the Launch configuration to use for the group. See the M(community.aws.autoscaling_launch_config) module for managing these.
      - Exactly one of O(launch_config_name) or O(launch_template) must be provided when creating a new AutoScaling Group.
      - B(Note) Amazon has deprecated support for AutoScaling Launch Configurations in favour of EC2 Launch Templates.  See
        U(https://docs.aws.amazon.com/autoscaling/ec2/userguide/launch-configurations.html) for more information
    type: str
  launch_template:
    description:
      - Dictionary describing the Launch Template to use.
      - Exactly one of O(launch_config_name) or O(launch_template) must be provided when creating a new AutoScaling Group.
    suboptions:
      version:
        description:
          - The version number of the launch template to use.
          - Defaults to latest version if not provided.
        type: str
      launch_template_name:
        description:
          - The name of the launch template. Only one of O(launch_template.launch_template_name) or O(launch_template.launch_template_id) is required.
        type: str
      launch_template_id:
        description:
          - The id of the launch template. Only one of O(launch_template.launch_template_name) or O(launch_template.launch_template_id) is required.
        type: str
    type: dict
  min_size:
    description:
      - Minimum number of instances in group, if unspecified then the current group value will be used.
    type: int
  max_size:
    description:
      - Maximum number of instances in group, if unspecified then the current group value will be used.
    type: int
  max_instance_lifetime:
    description:
      - The maximum amount of time, in seconds, that an instance can be in service.
      - Maximum instance lifetime must be equal to V(0), between V(604800) and V(31536000) seconds (inclusive), or not specified.
      - Value of V(0) removes lifetime restriction.
    type: int
  mixed_instances_policy:
    description:
      - A mixed instance policy to use for the ASG.
      - Only used when the ASG is configured to use a Launch Template (O(launch_template)).
      - 'See also U(https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-autoscalinggroup-mixedinstancespolicy.html)'
    required: false
    suboptions:
      instance_types:
        description:
          - A list of instance types.
        type: list
        elements: str
        required: false
      instances_distribution:
        description:
          - >-
            Specifies the distribution of On-Demand Instances and Spot Instances, the maximum price
            to pay for Spot Instances, and how the Auto Scaling group allocates instance types
            to fulfill On-Demand and Spot capacity.
          - 'See also U(https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_InstancesDistribution.html)'
        required: false
        type: dict
        version_added: 1.5.0
        version_added_collection: community.aws
        suboptions:
          on_demand_allocation_strategy:
            description:
              - Indicates how to allocate instance types to fulfill On-Demand capacity.
            type: str
            required: false
            version_added: 1.5.0
            version_added_collection: community.aws
          on_demand_base_capacity:
            description:
              - >-
                The minimum amount of the Auto Scaling group's capacity that must be fulfilled by On-Demand
                Instances. This base portion is provisioned first as your group scales.
              - >-
                Default if not set is V(0). If you leave it set to V(0), On-Demand Instances are launched as a
                percentage of the Auto Scaling group's desired capacity, per the
                O(mixed_instances_policy.instances_distribution.on_demand_percentage_above_base_capacity) setting.
            type: int
            required: false
            version_added: 1.5.0
            version_added_collection: community.aws
          on_demand_percentage_above_base_capacity:
            description:
              - Controls the percentages of On-Demand Instances and Spot Instances for your additional capacity beyond
                O(mixed_instances_policy.instances_distribution.on_demand_base_capacity).
              - 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.
              - 'Valid range: V(0) to V(100).'
            type: int
            required: false
            version_added: 1.5.0
            version_added_collection: community.aws
          spot_allocation_strategy:
            description:
              - Indicates how to allocate instances across Spot Instance pools.
            type: str
            required: false
            version_added: 1.5.0
            version_added_collection: community.aws
          spot_instance_pools:
            description:
              - >-
                The number of Spot Instance pools across which to allocate your Spot Instances. The Spot pools are determined from
                the different instance types in the Overrides array of LaunchTemplate. Default if not set is V(2).
              - Used only when the Spot allocation strategy is lowest-price.
              - 'Valid Range: Minimum value of V(1). Maximum value of V(20).'
            type: int
            required: false
            version_added: 1.5.0
            version_added_collection: community.aws
          spot_max_price:
            description:
              - The maximum price per unit hour that you are willing to pay for a Spot Instance.
              - If you leave the value of this parameter blank (which is the default), the maximum Spot price is set at the On-Demand price.
              - To remove a value that you previously set, include the parameter but leave the value blank.
            type: str
            required: false
            version_added: 1.5.0
            version_added_collection: community.aws
    type: dict
  placement_group:
    description:
      - Physical location of your cluster placement group created in Amazon EC2.
    type: str
  desired_capacity:
    description:
      - Desired number of instances in group, if unspecified then the current group value will be used.
    type: int
  replace_all_instances:
    description:
      - Support for the O(replace_all_instances) parameter has been deprecated and will be removed
        in release 14.0.0.
        The M(amazon.aws.autoscaling_instance_refresh) module can be used to perform an automated
        replacement of instances.
      - In a rolling fashion, replace all instances that used the old launch configuration with one from the new launch configuration.
        It increases the ASG size by O(replace_batch_size), waits for the new instances to be up and running.
        After that, it terminates a batch of old instances, waits for the replacements, and repeats, until all old instances are replaced.
        Once that's done the ASG size is reduced back to the expected size.
    default: false
    type: bool
  replace_batch_size:
    description:
      - Support for the O(replace_all_instances) and O(replace_batch_size) parameters has been
        deprecated and will be removed in release 14.0.0.
        The M(amazon.aws.autoscaling_instance_refresh) module can be used to perform an automated
        replacement of instances.
      - Number of instances you'd like to replace at a time.  Used with O(replace_all_instances).
    required: false
    default: 1
    type: int
  replace_instances:
    description:
      - Support for the O(replace_instances) parameter has been deprecated and will be removed in
        release 14.0.0.
        The M(amazon.aws.autoscaling_instance) module can be used to terminate instances attached
        to an AutoScaling Group.
      - List of instance ids belonging to the named AutoScalingGroup that you would like to terminate and be replaced with instances
        matching the current launch configuration.
    type: list
    elements: str
    default: []
  detach_instances:
    description:
      - Support for the O(detach_instances) parameter has been deprecated and will be removed in
        release 14.0.0.
        The M(amazon.aws.autoscaling_instance) module can be used to attach instances to and detach
        and detach instances from an AutoScaling Group.
      - Removes one or more instances from the specified AutoScalingGroup.
      - If O(decrement_desired_capacity) flag is not set, new instance(s) are launched to replace the detached instance(s).
      - If a Classic Load Balancer is attached to the AutoScalingGroup, the instances are also deregistered from the load balancer.
      - If there are target groups attached to the AutoScalingGroup, the instances are also deregistered from the target groups.
    type: list
    elements: str
    default: []
    version_added: 3.2.0
    version_added_collection: community.aws
  decrement_desired_capacity:
    description:
      - Support for the O(detach_instances) and O(decrement_desired_capacity) parameters has been
        deprecated and will be removed in release 14.0.0.
        The M(amazon.aws.autoscaling_instance) module can be used to attach instances to and detach
        and detach instances from an AutoScaling Group.
      - Indicates whether the AutoScalingGroup decrements the desired capacity value by the number of instances detached.
    default: false
    type: bool
    version_added: 3.2.0
    version_added_collection: community.aws
  lc_check:
    description:
      - Support for the O(detach_instances) and O(lc_check) parameters has been deprecated and will
        be removed in release 14.0.0.
        The M(amazon.aws.autoscaling_instance) module can be used to attach instances to and detach
        and detach instances from an AutoScaling Group.
      - Check to make sure instances that are being replaced with O(replace_instances) do not already have the current launch config.
    default: true
    type: bool
  lt_check:
    description:
      - Support for the O(detach_instances) and O(lt_check) parameters has been deprecated and will
        be removed in release 14.0.0.
        The M(amazon.aws.autoscaling_instance) module can be used to attach instances to and detach
        and detach instances from an AutoScaling Group.
      - Check to make sure instances that are being replaced with O(replace_instances) do not already have the current
        O(launch_template) or O(launch_template) O(launch_template.version).
    default: true
    type: bool
  vpc_zone_identifier:
    description:
      - List of VPC subnets to use
    type: list
    elements: str
  tags:
    description:
      - A list of tags to add to the Auto Scale Group.
      - Optional key is V(propagate_at_launch), which defaults to V(true).
      - When V(propagate_at_launch) is V(true) the tags will be propagated to the Instances created.
    type: list
    elements: dict
    default: []
  purge_tags:
    description:
      - If V(true), existing tags will be purged from the resource to match exactly what is defined by O(tags) parameter.
      - If the O(tags) parameter is not set then tags will not be modified.
    default: false
    type: bool
    version_added: 3.2.0
    version_added_collection: community.aws
  health_check_period:
    description:
      - Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health.
    required: false
    default: 300
    type: int
  health_check_type:
    description:
      - The service you want the health status from, Amazon EC2 or Elastic Load Balancer.
    required: false
    default: EC2
    choices: ['EC2', 'ELB']
    type: str
  default_cooldown:
    description:
      - The number of seconds after a scaling activity completes before another can begin.
    default: 300
    type: int
  wait_timeout:
    description:
      - 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",
        try increasing this value.
    default: 300
    type: int
  wait_for_instances:
    description:
      - 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
        instances have a lifecycle_state of  "InService" and  a health_status of "Healthy".
    default: true
    type: bool
  termination_policies:
    description:
        - An ordered list of criteria used for selecting instances to be removed from the Auto Scaling group when reducing capacity.
        - Using O(termination_policies=Default) when modifying an existing AutoScalingGroup will result in the existing policy being retained
          instead of changed to V(Default).
        - 'Valid values include: V(Default), V(OldestInstance), V(NewestInstance), V(OldestLaunchConfiguration), V(ClosestToNextInstanceHour)'
        - 'Full documentation of valid values can be found in the AWS documentation:'
        - 'U(https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html#custom-termination-policy)'
    default: Default
    type: list
    elements: str
  notification_topic:
    description:
      - A SNS topic ARN to send auto scaling notifications to.
    type: str
  notification_types:
    description:
      - A list of auto scaling events to trigger notifications on.
    default:
      - 'autoscaling:EC2_INSTANCE_LAUNCH'
      - 'autoscaling:EC2_INSTANCE_LAUNCH_ERROR'
      - 'autoscaling:EC2_INSTANCE_TERMINATE'
      - 'autoscaling:EC2_INSTANCE_TERMINATE_ERROR'
    required: false
    type: list
    elements: str
  suspend_processes:
    description:
      - A list of scaling processes to suspend.
      - 'Valid values include:'
      - V(Launch), V(Terminate), V(HealthCheck), V(ReplaceUnhealthy), V(AZRebalance), V(AlarmNotification), V(ScheduledActions), V(AddToLoadBalancer)
      - 'Full documentation of valid values can be found in the AWS documentation:'
      - 'U(https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html)'
    default: []
    type: list
    elements: str
  metrics_collection:
    description:
      - Enable ASG metrics collection.
    type: bool
    default: false
  metrics_granularity:
    description:
      - When O(metrics_collection=true) this will determine the granularity of metrics collected by CloudWatch.
    default: "1Minute"
    type: str
  metrics_list:
    description:
      - List of autoscaling metrics to collect when O(metrics_collection=true).
    default:
      - 'GroupMinSize'
      - 'GroupMaxSize'
      - 'GroupDesiredCapacity'
      - 'GroupInServiceInstances'
      - 'GroupPendingInstances'
      - 'GroupStandbyInstances'
      - 'GroupTerminatingInstances'
      - 'GroupTotalInstances'
    type: list
    elements: str
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.boto3
a]  
# Basic configuration with Launch Template

- name: Create an autoscaling group using launch template
  amazon.aws.autoscaling_group:
    name: example_asg
    load_balancers: ['lb1', 'lb2']
    availability_zones: ['eu-west-1a', 'eu-west-1b']
    launch_template:
      launch_template_name: 'template-1'
    min_size: 1
    max_size: 10
    desired_capacity: 5
    vpc_zone_identifier: ['subnet-abcd1234', 'subnet-1a2b3c4d']
    tags:
      - environment: production
        propagate_at_launch: false

# Rolling ASG Updates

# Below is an example of how to assign a new launch template to an ASG and replace old instances.
# By setting max_healthy_percentage to a value over 100 the old rolling-replacement behaviour of
# scaling up before scaling in can be maintained.

- name: Update autoscaling group with new template - instances are not replaced
  amazon.aws.autoscaling_group:
    name: example_asg
    launch_template:
      launch_template_name: template-2
    health_check_period: 60
    health_check_type: ELB
    min_size: 2
    max_size: 13
    desired_capacity: 6
    region: us-east-1

- name: Replace 2 instances based on EC2 Instance ID by marking them for termination
  amazon.aws.autoscaling_instance:
    group_name: example_asg
    state: terminated
    instance_ids:
      - i-b345231
      - i-24c2931
    decrement_desired_capacity: false
    wait: true

- name: Trigger rolling replacement of all instances that do not match the current configuration.
  amazon.aws.autoscaling_instance_refresh:
    group_name: example_asg
    state: started
    strategy: Rolling
    preferences:
      skip_matching: true
      max_healthy_percentage: 125  # scale out before terminating instances during replacement

# Basic Configuration with Launch Template

- name: Example autoscaling group creation with a launch template
  amazon.aws.autoscaling_group:
    name: example_with_template
    load_balancers: ['lb1', 'lb2']
    availability_zones: ['eu-west-1a', 'eu-west-1b']
    launch_template:
      version: '1'
      launch_template_name: 'lt-example'
      launch_template_id: 'lt-123456'
    min_size: 1
    max_size: 10
    desired_capacity: 5
    vpc_zone_identifier: ['subnet-abcd1234', 'subnet-1a2b3c4d']
    tags:
      - environment: production
        propagate_at_launch: false

# Basic Configuration with Launch Template using mixed instance policy

- name: Example autoscaling group creation with a mixed instance policy
  amazon.aws.autoscaling_group:
    name: example_with_policy
    load_balancers: ['lb1', 'lb2']
    availability_zones: ['eu-west-1a', 'eu-west-1b']
    launch_template:
      version: '1'
      launch_template_name: 'lt-example'
      launch_template_id: 'lt-123456'
    mixed_instances_policy:
      instance_types:
        - t3a.large
        - t3.large
        - t2.large
      instances_distribution:
        on_demand_percentage_above_base_capacity: 0
        spot_allocation_strategy: capacity-optimized
    min_size: 1
    max_size: 10
    desired_capacity: 5
    vpc_zone_identifier: ['subnet-abcd1234', 'subnet-1a2b3c4d']
    tags:
      - environment: production
        propagate_at_launch: false
aX  
---
auto_scaling_group_name:
    description: The unique name of the auto scaling group
    returned: success
    type: str
    sample: "myasg"
auto_scaling_group_arn:
    description: The unique ARN of the autoscaling group
    returned: success
    type: str
    sample: "arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:6a09ad6d-eeee-1234-b987-ee123ced01ad:autoScalingGroupName/myasg"
availability_zones:
    description: The availability zones for the auto scaling group
    returned: success
    type: list
    sample: [
        "us-east-1d"
    ]
created_time:
    description: Timestamp of create time of the auto scaling group
    returned: success
    type: str
    sample: "2017-11-08T14:41:48.272000+00:00"
default_cooldown:
    description: The default cooldown time in seconds.
    returned: success
    type: int
    sample: 300
desired_capacity:
    description: The number of EC2 instances that should be running in this group.
    returned: success
    type: int
    sample: 3
healthcheck_period:
    description: Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health.
    returned: success
    type: int
    sample: 30
healthcheck_type:
    description: The service you want the health status from, one of "EC2" or "ELB".
    returned: success
    type: str
    sample: "ELB"
healthy_instances:
    description: Number of instances in a healthy state
    returned: success
    type: int
    sample: 5
in_service_instances:
    description: Number of instances in service
    returned: success
    type: int
    sample: 3
instance_facts:
    description: Dictionary of EC2 instances and their status as it relates to the ASG.
    returned: success
    type: dict
    sample: {
        "i-0123456789012": {
            "health_status": "Healthy",
            "launch_config_name": "public-webapp-production-1",
            "lifecycle_state": "InService"
        }
    }
instances:
    description: list of instance IDs in the ASG
    returned: success
    type: list
    sample: [
        "i-0123456789012"
    ]
launch_config_name:
    description: >
      Name of launch configuration associated with the ASG. Same as launch_configuration_name,
      provided for compatibility with M(amazon.aws.autoscaling_group) module.
    returned: success
    type: str
    sample: "public-webapp-production-1"
load_balancers:
    description: List of load balancers names attached to the ASG.
    returned: success
    type: list
    sample: ["elb-webapp-prod"]
max_instance_lifetime:
    description: The maximum amount of time, in seconds, that an instance can be in service.
    returned: success
    type: int
    sample: 604800
max_size:
    description: Maximum size of group
    returned: success
    type: int
    sample: 3
min_size:
    description: Minimum size of group
    returned: success
    type: int
    sample: 1
mixed_instances_policy:
    description: Returns the list of instance types if a mixed instances policy is set.
    returned: success
    type: list
    sample: ["t3.micro", "t3a.micro"]
mixed_instances_policy_full:
    description: Returns the full dictionary representation of the mixed instances policy if a mixed instances policy is set.
    returned: success
    type: dict
    sample: {
        "instances_distribution": {
            "on_demand_allocation_strategy": "prioritized",
            "on_demand_base_capacity": 0,
            "on_demand_percentage_above_base_capacity": 0,
            "spot_allocation_strategy": "capacity-optimized"
        },
        "launch_template": {
            "launch_template_specification": {
                "launch_template_id": "lt-53c2425cffa544c23",
                "launch_template_name": "random-LaunchTemplate",
                "version": "2"
            },
            "overrides": [
                {
                    "instance_type": "m5.xlarge"
                },
                {
                    "instance_type": "m5a.xlarge"
                },
            ]
        }
    }
pending_instances:
    description: Number of instances in pending state
    returned: success
    type: int
    sample: 1
tags:
    description: List of tags for the ASG, and whether or not each tag propagates to instances at launch.
    returned: success
    type: list
    sample: [
        {
            "key": "Name",
            "value": "public-webapp-production-1",
            "resource_id": "public-webapp-production-1",
            "resource_type": "auto-scaling-group",
            "propagate_at_launch": "true"
        },
        {
            "key": "env",
            "value": "production",
            "resource_id": "public-webapp-production-1",
            "resource_type": "auto-scaling-group",
            "propagate_at_launch": "true"
        }
    ]
target_group_arns:
    description: List of ARNs of the target groups that the ASG populates
    returned: success
    type: list
    sample: [
        "arn:aws:elasticloadbalancing:ap-southeast-2:123456789012:targetgroup/target-group-host-hello/1a2b3c4d5e6f1a2b",
        "arn:aws:elasticloadbalancing:ap-southeast-2:123456789012:targetgroup/target-group-path-world/abcd1234abcd1234"
    ]
target_group_names:
    description: List of names of the target groups that the ASG populates
    returned: success
    type: list
    sample: [
        "target-group-host-hello",
        "target-group-path-world"
    ]
termination_policies:
    description: A list of termination policies for the group.
    returned: success
    type: list
    sample: ["Default"]
unhealthy_instances:
    description: Number of instances in an unhealthy state
    returned: success
    type: int
    sample: 0
viable_instances:
    description: Number of instances in a viable state
    returned: success
    type: int
    sample: 1
vpc_zone_identifier:
    description: VPC zone ID / subnet id for the auto scaling group
    returned: success
    type: str
    sample: "subnet-a31ef45f"
metrics_collection:
    description: List of enabled AutosSalingGroup metrics
    returned: success
    type: list
    sample: [
        {
            "Granularity": "1Minute",
            "Metric": "GroupInServiceInstances"
        }
    ]
    N)	to_native)camel_dict_to_snake_dict)snake_dict_to_camel_dict)is_boto3_error_code)describe_target_groups)AnsibleAWSModule)AWSRetry)scrub_none_parameters
      g      ?)retriesdelaybackoffc                     | j                  d      }|j                  |g      j                         j                  dg       S )Ndescribe_auto_scaling_groups)AutoScalingGroupNamesAutoScalingGroups)get_paginatorpaginatebuild_full_resultget)
connection
group_namepgs      p/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/amazon/aws/plugins/modules/autoscaling_group.pydescribe_autoscaling_groupsr     s>    		!	!"@	AB;;j\;:LLNRRSfhjkk    c                 @    | j                  |t        |      g       y )N
InstanceId)LoadBalancerName	Instances)'deregister_instances_from_load_balancerdict)r   lb_nameinstance_ids      r   deregister_lb_instancesr'     s"    66 T[-I,J 7 r   c                 f    t        |      }|r|j                  |        | j                  di |S )N)r!   )r"    )r$   updatedescribe_instance_health)r   r%   	instancesparamss       r   r+   r+     s3    7+F	*.:..888r   c                 (    | j                  ||      S )N)TargetGroupArnTargets)describe_target_health)r   target_group_arnr,   s      r   r1   r1     s    ,,<LV_,``r   c                 *    | j                  ||       y N)AutoScalingGroupNameScalingProcesses)suspend_processesr   asg_name	processess      r   suspend_asg_processesr;     s      hQZ [r   c                 *    | j                  ||       y r4   )resume_processesr8   s      r   resume_asg_processesr>     s    XPYZr   c                 f    | j                  d      }|j                  |g      j                         S )Ndescribe_launch_configurations)LaunchConfigurationNames)r   r   r   )r   launch_config_namer   s      r   r@   r@     s1    		!	!"B	CB;;1C0D;EWWYYr   c                 $   |d   	 | j                  |d   g      }|S 	 | j                  |d   g      }|S # t        d      $ r t        j                  d|        Y y w xY w# t        d      $ r t        j                  d|        Y y w xY w)Nlaunch_template_id)LaunchTemplateIdsz+InvalidLaunchTemplateName.NotFoundExceptionz#No launch template found matching: msglaunch_template_name)LaunchTemplateNames)describe_launch_templatesr   module	fail_json)r   launch_templatelts      r   rJ   rJ     s    +,8	Z55YmInHo5pBI	Z55?[qKrJs5tBI ##PQ 	Z#FFW!XY	Z ##PQ 	Z#FFW!XY	Zs    8 A% 'A"!A"%'BBc                 (     | j                   di | y Nr)   )create_auto_scaling_groupr   r-   s     r   
create_asgrS         (J((262r   c                 ,    | j                  |||       y )N)r5   TopicARNNotificationTypes)put_notification_configuration)r   r9   	topic_arnnotification_typess       r   put_notification_configr[     s    --%	M_ . r   c                 *    | j                  ||       y )N)r5   rV   )!delete_notification_configuration)r   r9   rY   s      r   del_notification_configr^     s    00hYb0cr   c                 *    | j                  ||       y N)r5   LoadBalancerNames)attach_load_balancersr   r9   load_balancerss      r   rb   rb         $$(Vd$er   c                 *    | j                  ||       y r`   )detach_load_balancersrc   s      r   rg   rg     re   r   c                 *    | j                  ||       y N)r5   TargetGroupARNs)"attach_load_balancer_target_groupsr   r9   target_group_arnss      r   attach_lb_target_groupsrn         11xar1sr   c                 *    | j                  ||       y ri   )"detach_load_balancer_target_groupsrl   s      r   detach_lb_target_groupsrr     ro   r   c                 (     | j                   di | y rP   )update_auto_scaling_grouprR   s     r   
update_asgru     rT   r   catch_extra_error_codesScalingActivityInProgressc                 *    | j                  ||       y )N)r5   ForceDelete)delete_auto_scaling_group)r   r9   force_deletes      r   
delete_asgr|   !  s    ((hT`(ar   c                 *    | j                  ||       y )N)r    ShouldDecrementDesiredCapacity)(terminate_instance_in_auto_scaling_group)r   r&   decrement_capacitys      r   terminate_asg_instancer   &  s    77?Q 8 r   c                 ,    | j                  |||       y )N)InstanceIdsr5   r~   )detach_instances)r   instance_idsas_group_namer   s       r   detach_asg_instancesr   -  s     }ew   r   c                  ^   g } t         j                  j                  d      5t         j                  j                  d      t         j                  d       dD ]'  }t         j                  |   | j	                  |       ) | r)t         j                  ddj                  |               yy)	zAs many arguments are not required for autoscale group deletion
    they cannot be mandatory arguments for the module, so we enforce
    them hererB   NrM   zQMissing either launch_config_name or launch_template for autoscaling group createrF   )min_sizemax_sizez9Missing required arguments for autoscaling group create: ,)rK   r-   r   rL   appendjoin)missing_argsargs     r   %enforce_required_arguments_for_creater   4  s     L}}-.66==;L;LM^;_;gpq' %==%$% XY\YaYabnYoXpqr r   c                 d   t        dddddd      }t               }| j                  d      }|r|D cg c]  }|d   	 c}|d<   |D ]  }|d   |d   d||d   <   d	|v r|d	   ||d      d
<   nd|v r|d   ||d      d<   |d   dk(  r|d   dk(  r|dxx   dz  cc<   |d   dk(  r|dxx   dz  cc<   n|dxx   dz  cc<   |d   dk(  r|dxx   dz  cc<   |d   dk(  r|dxx   dz  cc<   |d   dk(  s|dxx   dz  cc<    ng |d<   | j                  d      |d<   | j                  d      |d<   | j                  d      |d<   | j                  d      |d<   ||d <   | j                  d!      |d"<   d	| v r| j                  d	      |d
<   n| j                  d      |d<   | j                  d#      |d$<   | j                  d%      |d&<   | j                  d'      |d(<   | j                  d)      |d*<   | j                  d+      |d,<   | j                  d-      |d.<   | j                  d/      |d0<   | j                  d1      |d2<   | j                  d-      |d.<   | j                  d3      |d4<   | j                  d5      |d6<   | j                  d7      |d8<   | j                  d9      }|rBt        |      |d:<   |j                  d      j                  d;      D cg c]  }|d<   	 c}|d=<   | j                  d>      }|r|j                  d? @       ||dA<   |d6   rt        j                  dB      }dC}	g |dD<   t        dt        |d6         |	      D cg c]  }|d6   |||	z     }
}|
D ]2  }|dD   j                  t        ||E      D cg c]  }|dF   	 c}       4 |S g |dD<   |S c c}w c c}w c c}w c c}w )GNr   )healthy_instancesin_service_instancesunhealthy_instancespending_instancesviable_instancesterminating_instancesr"   r    r,   HealthStatusLifecycleState)health_statuslifecycle_stateLaunchConfigurationNamerB   LaunchTemplaterM   Healthy	InServicer      r   r   r   Terminatingr   Pendingr   r5   auto_scaling_group_nameAutoScalingGroupARNauto_scaling_group_arnAvailabilityZonesavailability_zonesCreatedTimecreated_timeinstance_factsra   rd   TagstagsMaxInstanceLifetimemax_instance_lifetimeMinSizer   MaxSizer   DesiredCapacitydesired_capacityDefaultCooldowndefault_cooldownHealthCheckGracePeriodhealthcheck_grace_periodHealthCheckTypehealthcheck_typeTerminationPoliciestermination_policiesrj   rm   VPCZoneIdentifiervpc_zone_identifierMixedInstancesPolicymixed_instances_policy_full	OverridesInstanceTypemixed_instances_policyEnabledMetricsc                     | d   S )NMetricr)   xs    r   <lambda>z get_properties.<locals>.<lambda>  s
    1X; r   keymetrics_collectionelbv2   target_group_names)TargetGroupArnsTargetGroupName)
r$   r   r   sortrK   clientrangelenextendr   )autoscaling_group
propertiesr   autoscaling_group_instancesiraw_mixed_instance_objectr   metricselbv2_connectiontg_chunk_size	tg_chunkschunktgs                r   get_propertiesr   B  s   J VN"3"7"7"D"<W"Xq1\?"X
;, 	5A!">!2#$%5#6/N1\?+ )A-HIJcHdq/0DE!Q&EFGWEXq/0AB I-!4D2E2T-.!3. I-./14/01Q61!"k112a72!"m323q83!"i/./14//	52 #%
;,=,A,ABX,YJ()+<+@+@AV+WJ'('8'<'<=P'QJ#$!2!6!6}!EJ~#1J #4#8#89L#MJ  $55+<+@+@AZ+[
'((9(=(=>N(O
$%*..v6Jv*;*?*?@U*VJ&'.229=Jz.229=Jz%6%:%:;L%MJ!"%6%:%:;L%MJ!"->-B-BC[-\J)*%6%:%:;L%MJ!"%6%:%:;L%MJ!"):)>)>?T)UJ%&&7&;&;<M&NJ"#(9(=(=>Q(RJ$% 1 5 56L M 4LMf4g
01'@'D'DEU'V'Z'Z[f'g0
"#An0

+,  ##$45G./'.J#$%&!==1+-
'( 1c*-@"ABMR
 *+Aq=/@A
	 
  	E+,331GHXjo1pq2%&q	  ,.
'(] #Yj0

 rs   NN#
N( N-
c                    t               }t        j                  j                  d      }t        j                  j                  d      }t        j                  j                  d      }|||S |rF	 t	        | |      }t        d         dk(  rt        j                  d|        d	|d   d   d	   i}|S |rt        ||      d
   d   }|d   d|d   |d   di}nd|d   t        |d         di}|r{|j                  dg       }	|j                  di       }
dd|d   ii}|	r*g |d   d<   |	D ]  }d|i}|d   d   j                  |        |
rt        |
      }t!        |d      |d<   ||d<   |S y # t
        j                  j                  t
        j                  j                  f$ r"}t        j                  |d       Y d }~Jd }~ww xY w)NrB   rM   r   z(Failed to describe launch configurationsrF   LaunchConfigurationsr   z!No launch config found with name r   LaunchTemplatesversionr   LaunchTemplateIdr   VersionLatestVersionNumberinstance_typesinstances_distributionLaunchTemplateSpecificationr   r   T)capitalize_firstInstancesDistributionr   )r$   rK   r-   r   r@   botocore
exceptionsClientErrorBotoCoreErrorfail_json_awsr   rL   rJ   strr   r
   r   )r   ec2_connectionlaunch_objectrB   rM   r   launch_configserN   r   r   policyinstance_typeinstance_type_dictinstances_distribution_paramss                  r   get_launch_objectr     sD   FM**+?@mm''(9:O#]]../GH!o&=		T;JHZ[N ~456!;#DEWDX!YZ%~6L'Ma'PQj'k
 	&~GHYZ[\]9%1 r:L7MZijsZt"uM
 !(*+=(>"2&;#<=#M "3778H"MN%;%?%?@XZ\%]"&)FVfHg(hiF8:'(5%3 UM*8-)H&+,[9@@ASTU &0EF\0]-2J1D3./ 5;M01; 
 ##//1D1D1R1RS 	T  (R SS	Ts   1E3 37G*GGc           
          t        | |      d   }t        j                  j                  d      }d}|d   r|d   dk(  rt        j	                  d      }ny |d   D ]*  }t        |||       t        j                  d| d	|        , t        j                         |z   }|t        j                         kD  r|dkD  rd}|d   D ]V  }t        ||g       }|d
   D ]?  }	|	d   |k(  s|	d   dk(  s|dz  }t        j                  |	d    d|	d    d|	d           A X t        j                  d       |t        j                         kD  r|dkD  r|t        j                         k  r,t        j                  dt        j                                 y y )Nr   wait_timeoutr   ra   r   ELBelbzDe-registering z
 from ELB InstanceStatesr    Stater   : , Descriptionr   z,Waited too long for instance to deregister. rF   )r   rK   r-   r   r   r'   debugtimer+   sleeprL   asctime)
asg_connectionr   r&   as_groupr   countelb_connectionlblb_instancesr   s
             r   elb_dregr    s   *>:FqIH==$$^4LE#$2C)D)Mu-*+ DK@{m:bTBCD 99;-L

$./ 	YB3NBKL!"23 Y\?k1ajK6OQJELLAlO#4Bqzl"Q}EUDV!WXY	Y 	

2 
$ tyy{"KDLLNK[\] #r   c           	      &   t               }t        | |      d   }t        |      }g }|d   j                         D ]2  \  }}|d   dk(  s|d   dk(  s|j	                  t        |             4 t        j                  d|        t        j                  d	       t               }	|j                  d
      D ]c  }
	 t        ||
|      }	|	j                  d      D ]?  }|d   dk(  r|j#                  |d          t        j                  d|d    d|d           A e t%        |      S # t        d      $ r Y  y t        j                  j                  t        j                  j                  f$ r!}t        j!                  |d       Y d }~d }~ww xY w)Nr   r   r   r   r   r   r   =ASG considers the following instances InService and Healthy: zELB instance status:ra   InvalidInstancezFailed to get load balancer.rF   r  r  r    zELB Health State r  )setr   r   itemsr   r$   rK   r  listr   r+   r   r   r   r   r   r   addr   )r
  r  r   r   r  propsr,   instancesettingsr  r  r   r   s                r   elb_healthyr    s   *>:FqIH8$EI#$45;;= 8(%&+5(?:SW`:`TX678 LLPQZP[\]
LL'(6Lll./ N	H3NB	RL !!"23 	NAz[(!%%ao6LL,Q|_,=R'
|LM	NN"  !! ##45 	++--
 	H   (F GG		Hs   ;D((F96F/FFc           	      >   t               }t        | |      d   }t        |      }g }|d   j                         D ]2  \  }}|d   dk(  s|d   dk(  s|j	                  t        |             4 t        j                  d|        t        j                  d	       t               }	|j                  d
      D ]o  }
	 t        ||
|      }	|	j                  d      D ]K  }|d   d   dk(  r|j#                  |d   d          t        j                  d|d   d    d|d   d           M q t%        |      S # t        d      $ r Y  y t        j                  j                  t        j                  j                  f$ r!}t        j!                  |d       Y d }~d }~ww xY w)Nr   r   r   r   r   r   )Idr  zTarget Group instance status:rj   r  zFailed to get target group.rF   TargetHealthDescriptionsTargetHealthr  healthyTargetr  zTarget Group Health State r  )r  r   r   r  r   r$   rK   r  r  r   r1   r   r   r   r   r   r   r  r   )r
  r   r   r   r  r  r,   r  r  tg_instancesr   r   r   s                r   
tg_healthyr#    s   *>:FqIH8$EI#$45;;= 0(%&+5(?:SW`:`TX./0 LLPQZP[\]
LL016Lll,- i	G12BB	RL !!"<= 	iA )Y6!%%ak$&78LL5ak$6G5H1^K\]dKeJfgh	ii"  !! ##45 	++--
 	G   (E FF		Gs   ;D44F6F;FFc                 (   t         j                  j                  d      }t        | |      d   }|j                  d      rR|j                  d      dk(  r<t         j	                  d       t         j                  d      }t        j                         |z   }t        | ||      }||j                  d      k  r~|t        j                         kD  rgt        | ||      }t         j	                  d	| d
       t        j                  d       ||j                  d      k  r|t        j                         kD  rg|t        j                         k  r+t         j                  dt        j                                 t         j	                  d| d
       y y y )Nr   r   ra   r   r   z.Waiting for ELB to consider instances healthy.r   r   zELB thinks  instances are healthy.r   1Waited too long for ELB instances to be healthy. rF   zWaiting complete. ELB thinks )rK   r-   r   r   r  r   r  r  r  rL   r	  )r
  r   r   r  r  r   s         r   wait_for_elbr'  /  sH   ==$$^4L +>:FqIH||'(X\\:K-LPU-UEFu-yy{\1'
S(,,y"99lTYY[>X +NNJ WLL;'8&99PQRJJrN  (,,y"99lTYY[>X 499;&#TUYUaUaUcTd!ef45F4GG^_` .V(r   c                 (   t         j                  j                  d      }t        | |      d   }|j                  d      rR|j                  d      dk(  r<t         j	                  d       t         j                  d      }t        j                         |z   }t        | ||      }||j                  d      k  r~|t        j                         kD  rgt        | ||      }t         j	                  d	| d
       t        j                  d       ||j                  d      k  r|t        j                         kD  rg|t        j                         k  r+t         j                  dt        j                                 t         j	                  d| d
       y y y )Nr   r   rj   r   r   z7Waiting for Target Group to consider instances healthy.r   r   zTarget Group thinks r%  r   r&  rF   z&Waiting complete. Target Group thinks )rK   r-   r   r   r  r   r  r#  r  rL   r	  )r
  r   r   r  r   r   s         r   wait_for_target_groupr)  G  sK   ==$$^4L +>:FqIH||%&8<<8I+Je+SNO!==1yy{\1&~7GT(,,y"99lTYY[>X *>;KZ XLL/0A/BBYZ[JJrN  (,,y"99lTYY[>X 499;&#TUYUaUaUcTd!ef=>O=PPghi ,T&r   c                    t        t        j                  j                  d            }	 t        |d   D cg c]  }|d   	 c}      }||k(  ryt        ||z
        }|r*t        | t        j                  j                  d      |       |r3t        | t        j                  j                  d      t        |             yc c}w # t        $ r t               }Y w xY w)Nr7   SuspendedProcessesProcessNameFnameT)r  rK   r-   r   AttributeErrorr  r>   r;   )r   r  processes_to_suspendpsuspended_processesr=   s         r   r7   r7   _  s    v}}001DEF$!XFZ=["\1]#3"\]
 22/2FFG^V]]->->v-FHXYnfmm.?.?.GNbIcd #] $!e$s"   C B?C ?C CCc                    t         j                  j                  d      }t         j                  d   }t         j                  d   }t         j                  d   }t         j                  j                  d      }t         j                  d   }t         j                  d   }t         j                  j                  d      }t         j                  j                  d	      }	t         j                  j                  d
      }
t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }	 t        | |      }t         j                  d      }|rdj                  |      }g }|D ]a  }|j                         D ]L  \  }}|dk7  s|j                  t        |t        |      t        |j                  dd            d|              N c st         j                   rt         j#                  dd!"       |s9|s7|j%                         d#   D  cg c]  } | d$   	 c} x}t         j                  d<   t'                |
|}
t        ||||
|||||%	      }!|r||!d&<   |r||!d#<   |	r|	|!d'<   |r||!d(<   |r||!d)<   |r||!d*<   t)        | |      }"d+|"v r	|"d+   |!d+<   n0d,|"v rd-|"v r	|"d-   |!d-<   n|"d,   |!d,<   nt         j+                  d.       	 t-        | fi |! |r| j/                  |||/       t        | |      }#t1        |#      d0k(  rt         j+                  d1|        |#d0   }$t3        | |$       |r+t5        | |||
d2       |rt7        | |       |rt9        | |       |rt;        | |||       t        | |      d0   }$t=        |$      }%d}&|&|%fS t         j                   rt         j#                  dd4"       |d0   }$t=        |$      }'d5}&t3        | |$      rd}&|$j                  d6      }(|})|r|)s|(r| j?                  tA        |(      7       t1        |      d0kD  r|(r|(jC                  d8 9       |)r|)jC                  d: 9       g }*|(D +cg c]  }+|+d;   	 },}+|)D +cg c]  }+|+d;   	 }-}+tE        |,      jG                  |-      D ]>  }.d}&|r |*j                  t        |$d<   d|.=             |(D /cg c]  }/|/d;   |.k7  s|/ }(}/@ |*r| j?                  |*7       tI        |(|)      }0t1        |(      t1        |)      k7  stK        d> |0D              sd}&| jM                  |7       |r|$d(   sd}&	 tO        | ||       n|$d(   r|d u}1|s
tA               }tE        |      }2tE        |$d(         }3|3|2z
  r.|1r,|3jG                  |2      }4|4rd}&	 tQ        | |tA        |4             |2|3z
  r,|2jG                  |3      }5|5rd}&	 tO        | |tA        |5             |r|$d)   sd}&	 tS        | ||       nx|v|$d)   rqtE        |      }6tE        |$d)         }7|7jG                  |6      }8|8rd}&	 tU        | |tA        |8             |6jG                  |7      }9|9rd}&	 tS        | |tA        |9             ||$dD   }||$dE   }|
|$dF   }
t        ||||
||||G      }!t)        | |      }"d+|"v r	|"d+   |!d+<   n#d,|"v rd-|"v r	|"d-   |!d-<   n|"d,   |!d,<   n		 |$d+   |!d+<   |r||!d#<   |r||!d&<   |||!d*<   	 tY        | fi |! |r| j/                  |||/       n| j[                  ||K       |r	 t;        | |||       |rUt5        | |||
d2       |r!t         j]                  dN       t7        | |       |r!t         j]                  dO       t9        | |       	 t        | |      d0   }$t=        |$      }%|%|'k7  rd}&|&|%fS # t        j
                  j                  t        j
                  j                  f$ r"}t         j                  |d       Y d }~d }~ww xY wc c} w # t        j
                  j                  t        j
                  j                  f$ r!}t         j                  |d3       Y d }~y d }~ww xY wc c}+w c c}+w c c}/w # t        j
                  j                  t        j
                  j                  f$ r"}t         j                  |d?       Y d }~d }~ww xY w# t        j
                  j                  t        j
                  j                  f$ r%}t         j                  |d@|4        Y d }~}d }~ww xY w# t        j
                  j                  t        j
                  j                  f$ r%}t         j                  |dA|5        Y d }~d }~ww xY w# t        j
                  j                  t        j
                  j                  f$ r"}t         j                  |d?       Y d }~wd }~ww xY w# t        j
                  j                  t        j
                  j                  f$ r%}t         j                  |dB|8        Y d }~d }~ww xY w# t        j
                  j                  t        j
                  j                  f$ r t         j+                  dC|9        Y 1w xY w# tV        $ r |$d,   }|dH   |dI   dJ|!d,<   Y w xY w# t        j
                  j                  t        j
                  j                  f$ r"}t         j                  |dL       Y d }~d }~ww xY w# t        j
                  j                  t        j
                  j                  f$ r"}t         j                  |dM       Y d }~Gd }~ww xY w# t        j
                  j                  t        j
                  j                  f$ r$}t         j                  |dP       Y d }~|&%fS d }~ww xY w)QNr-  rd   rm   r   rM   r   r   r   placement_groupr   r   r   
purge_tagshealth_check_periodhealth_check_typer   wait_for_instancesr   r   notification_topicrZ   r   metrics_granularitymetrics_listz'Failed to describe auto scaling groups.rF   ec2r   propagate_at_launchTzauto-scaling-group)KeyValuePropagateAtLaunchResourceType
ResourceIdz9Would have created AutoScalingGroup if not in check_mode.changedrG   r   ZoneName)	r5   r   r   r   r   r   r   r   r   r   PlacementGroupra   rj   r   r   r   r   z1Missing LaunchConfigurationName or LaunchTemplate)r5   GranularityMetricsr   z*No auto scaling group found with the name r   z#Failed to create Autoscaling Group.zFWould have modified AutoScalingGroup if required if not in check_mode.Fr   )r   c                     | d   S Nr=  r)   r   s    r   r   z*create_autoscaling_group.<locals>.<lambda>  
    QuX r   r   c                     | d   S rI  r)   r   s    r   r   z*create_autoscaling_group.<locals>.<lambda>  rJ  r   r=  r5   )rA  r@  r=  c              3   ,   K   | ]  \  }}||k(    y wNr)   ).0r   ys      r   	<genexpr>z+create_autoscaling_group.<locals>.<genexpr>  s     :Uda16:Us   z#Failed to update Autoscaling Group.z Failed to detach load balancers z Failed to attach load balancers z-Failed to detach load balancer target groups z-Failed to attach load balancer target groups r   r   r   )r5   r   r   r   r   r   r   r   r   r   r   )r5   rG  z"Failed to update autoscaling groupz1Failed to update Autoscaling Group notifications.z	WAITING FOR ELB HEALTHz	WAITING FOR TG HEALTHz+Failed to read existing Autoscaling Groups.)/rK   r-   r   r   r   r   r   r   r   r   r   r  r   r$   r   bool
check_mode	exit_jsondescribe_availability_zonesr   r   rL   rS   enable_metrics_collectionr   r7   wait_for_new_instr'  r)  r[   r   delete_tagsr  r   r  
differencezipallcreate_or_update_tagsrb   rg   rn   rr   KeyErrorru   disable_metrics_collectionr  ):r   r   rd   rm   r   rM   r   r   r   r3  r   r   set_tagsr4  r5  r6  r   r7  r   r   r8  rZ   r   r9  r:  	as_groupsr   r   asg_tagstagkvzoneagr   all_agr  asg_propertiesrC  initial_asg_properties	have_tags	want_tags	dead_tagsr   have_tag_keyvalswant_tag_keyvalsdead_taghave_tagzippedchange_load_balancerswanted_elbshas_elbselbs_to_detachelbs_to_attach
wanted_tgshas_tgstgs_to_detachtgs_to_attachs:                                                             r   create_autoscaling_grouprz  u  sX   ""6*J]]#34N&9:';<mm''(9:O}}Z(H}}Z(H"MM--.EFmm''(9:O}}(();< --++,AB}}  (H""<0J --++,AB))*=>}}(();<**+?@==$$^4L!==,,-CD**+?@**+?@**+?@ --++,AB==$$^4LO/
JG	 ]]5)N!hh':;H IIK 
	DAq))'l*.sww7Ld/S*T%9#-
	 T/jk"+=-;-W-W-YZm-nH%)Z H /C!D 	./#'!+,#6-, 4

 &9B"#&8B"##2B &4B"#$5B ! (=B$%)*nE$5,9:S,TB().%6-:;Q-R)*'45E'F#$!TU	Oz(R(!44)3AT^j 5  1ZHF6{a  'QR\Q]%^ _ayHj(3!!*j,HXZlm! Z8$)*jA!'
J@RTfg2:zJ1MH+H5NGN** T/wxQ<!/!9Z2G LL(		iI""Y"8x=1#56#56I2;<Q%<<2;<Q%<< 01<<=MN `$$'/0F'GVjpx
 7@_(8E?V^C^X_	_` &&I&6I.F9~Y/s:Uf:U7U00h0? (+>"?GS%j*nM
 )*$2$$>!!!%n-K8$789H+%*?!)!4!4[!A!"Gi-j*d>FZ[ X%!,!7!7!A!"Gi-j*d>FZ[ X.?%@GS'
J@QR *x8I/J./J(#456G#..z:Mq+J
DDWX '11':Mj+J
DDWX 	*H	*H#'(9:!+,#6-, 4	
 **nE$5,9:S,TB().%6-:;Q-R)*'45E'F#$089R0S,- &8B"#&9B"# ,(=B$%	Nz(R(!44)3AT^j 5  55:_k5l
 a'
J@RTfg j*lDTVhi78Z4 !67%j*=	W2:zJ1MH+H5N!77 &&G	 ++X-@-@-N-NO OQ$MNNO4HH ##//1D1D1R1RS 	O  (M NN	O2  =< `  ''33X5H5H5V5VW S$$Q,Q$RRS( %//;;X=P=P=^=^_ i,,Q6VWeVf4g,hhi %//;;X=P=P=^=^_ i,,Q6VWeVf4g,hhi ''33X5H5H5V5VW S$$Q,Q$RRS !++779L9L9Z9Z[ q((2_`m_n0o(ppq !++779L9L9Z9Z[ j$$+XYfXg)h$ijD  "*+;"< )88J(K.y9(#$2 ##//1D1D1R1RS 	N  (L MM	N ''33X5H5H5V5VW a$$Q,_$``a& ##//1D1D1R1RS 	W  (U VV&&	Ws4  .d e.Ce3 gg'g5g$g =h9 .j k7 m >n2 0p	 6p, r -!s$ 7e+	e&&e+37g*gg7h6h11h697j0jj7k4k//k477m.mm7n/
n**n/2App	p)(p),7r#r  r7s!?ss!$7t?t::t?c                    t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }|rt        | ||       t	        | |      }|rt         j
                  rt         j                  dd       t        j                         |z   }|st        | |d       nt        |d	d	d	
      }t        | fi | d}|rp|rn|t        j                         k\  rWt	        | |      }|r|d	   }	|	j                  d      sd}t        j                  d       |r|r|t        j                         k\  rW|t        j                         k  r+t         j                  dt        j                                 t        | |d       t	        | |      rP|t        j                         k\  r9t        j                  d       t	        | |      r|t        j                         k\  r9|t        j                         k  r+t         j                  dt        j                                 yy)Nr-  r8  r7  r   Tz9Would have deleted AutoScalingGroup if not in check_mode.rB  )r{   r   )r5   r   r   r   r"   Fr   0Waited too long for old instances to terminate. rF      z#Waited too long for ASG to delete. )rK   r-   r   r^   r   rR  rS  r  r|   r$   ru   r  rL   r	  )
r   r   r8  r7  r   groupsupdated_paramsr,   
tmp_groups	tmp_groups
             r   delete_autoscaling_groupr    s   ""6*J**+?@**+?@==$$^4L
J8JK(Z@FT/jkyy{\1!z:DA!z1VWijkNz4^4I 2|tyy{7R8ZP
 *1I$==5$)	

2  2|tyy{7R tyy{*  'WX\XdXdXfWg%h iz:EB)*jAlVZV_V_VaFaJJqM **jAlVZV_V_VaFa499;&#Ft||~FV!WXr   c              #   V   K   t        dt        |       |      D ]  }| |||z      y w)Nr   )r   r   )objects
chunk_sizer   s      r   
get_chunksr    s3     1c'lJ/ (aJ''(s   ')c                     t         j                  d       t         j                  d| d| d|        t               }|d   |d<   ||d<   ||d<   ||d<   t        | fi | y )	Nzsetting ASG sizeszminimum size: z, desired_capacity: z, max size: r5   r   r   r   )rK   r  r$   ru   )r   groupr   r   dcupdated_groups         r   update_sizer    st    
LL$%
LL>(+?t<PXzZ[FM,12H,IM()'M)'M)')M#$z+]+r   c                    t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }|r t         j                  j                  d	      }	nd
}	t         j                  j                  d      }
|
r t         j                  j                  d      }nd
}t         j                  j                  d      }t         j                  j                  d      }t        | |      d   }||d   }|rt	        | |||d   d       t        |      }|d   }|r|}|r|}|rt        ||	|      \  }}n|
rt        |||      \  }}|t              z
  }|	s|ri|dk(  rErCt         j                  d       t        | ||d       t        | |      d   }t        |      }d}||fS ||k  rt         j                  d|        |}sd
}||fS ||d   }||d   }t        | |      d   }t        | |||z   ||z   ||z          |r-t	        | |||d   |z   d       t        | |       t        | |       t        | |      d   }t        |      }|d   }|r|}t         j                  d       t        ||      D ]b  }t        | ||d
      \  }}}|r3t        | |       t	        | |||d       t        | |       t        | |       |sMt         j                  d        n t        | ||||       t        | |      d   }t        |      }t         j                  d       d}||fS )Nreplace_batch_sizer   r7  r-  r   r   r   rB   lc_checkFrM   lt_checkreplace_instancesreplace_all_instancesr   r   r   r   r,   zNNo new instances needed, but old instances are present. Removing old instancesTzOverriding batch size to r   zbeginning main loopzbreaking loopzRolling update complete.)rK   r-   r   r   rV  r   get_instances_by_launch_config get_instances_by_launch_templater   r  terminate_batchr  r'  r)  r  wait_for_term_inst)r   
batch_sizer   r7  r   r   r   r   rB   r  rM   r  r  r  r  r  r,   new_instancesold_instancesnum_new_inst_neededrC  r   break_earlydesired_sizeterm_instancesrg  s                             r   replacer    s   ""#78J==$$^4L**+?@""6*J}}  ,H}}  ,H}}(();<**+?@ ==$$Z0mm''(9:O==$$Z0))*=>"MM--.EF*:zB1EH#$56*j,@SUgh8$Ek"I &%	 'EeXW`'a$}	'GxYb'c$}*S-??8!#LLijJy$G2:zJ1MH"8,EGE>! +LL45H4IJK,J~ I&I&
 +:zB1EH
Hh&;X
=RTdgqTqr*j,@SV`@`btuZ,j*5*:zB1EH8$Ek"I%	
LL&'	:. 4CJPQS\^c4d1\>z>:j*lLRdeZ0!*j9LL) 
Hh:JK*:zB1EH#H-N
LL+,GN""r   c                    t         j                  j                  d      }t         j                  j                  d      }t        | |      d   }t         j                  j                  d      }t         j                  j                  d      }t	        |      }|d   }g }|D ]  }	|	|v s|j                  |	        |r;t        |      t        |      z
  }
|r"||
kD  rt         j                  d|
 d| d	
       |r	 t        | |||       t	        |      }d|fS # t        j                  j                  t        j                  j                  f$ r!}t         j                  |d
       Y d }~bd }~ww xY w)Nr-  r   r   decrement_desired_capacityr   r,   z`Detaching instance(s) with 'decrement_desired_capacity' flag set reduces number of instances to z! which is below current min_size z0, please update AutoScalingGroup Sizes properly.rF   z1Failed to detach instances from AutoScaling GroupT)rK   r-   r   r   r   r   r   rL   r   r   r   r   r   r   )r   r   r   r  r  r   r  r,   instances_to_detachr&   decremented_desired_capacityr   rg  s                r   detachr  a  sy   ""6*J}}(();<*:zB1EH!'!2!23O!P}}  ,H8$Ek"I ' 4)#&&{34 "'*9~<O8P'P$#??455VW_V` a88   	] -@*Nhi $H-N	 ##//1D1D1R1RS 	]  ([ \\	]s   ;D 7E0E++E0c                    g }g }|rg| d   D ]^  }d| d   |   v r|j                  |       | d   |   j                  d      | d   k(  r|j                  |       N|j                  |       ` nLt        j                  dg |        | d   D ])  }||vr|j                  |       |j                  |       + t        j                  dt	        |       dg |        t        j                  dt	        |       dg |        ||fS )	Nr,   rM   r   rB   *Comparing initial instances with current: New instances: r  Old instances: r   r   rK   r  r   )r  r  initial_instancesr  r  r   s         r   r  r    s5   MM{# 	(A E*:$;A$>>$$Q''(+//0DEOcIdd$$Q'$$Q'	( 	ABWDUBWAXYZ{# 	(A))$$Q'$$Q'		( LL?3}#5"6b9J=9J8KLM
LL?3}#5"6b9J=9J8KLM-''r   c                    g }g }|rg| d   D ]^  }d| d   |   v r|j                  |       | d   |   j                  d      | d   k(  r|j                  |       N|j                  |       ` nLt        j                  dg |        | d   D ])  }||vr|j                  |       |j                  |       + t        j                  dt	        |       dg |        t        j                  dt	        |       dg |        ||fS )	Nr,   rB   r   rM   r  r  r  r  r  )r  r  r  r  r  r   s         r   r  r    s5   MM{# 	(A#u-='>q'AA$$Q''(+//0ABeL]F^^$$Q'$$Q'	( 	ABWDUBWAXYZ{# 	(A))$$Q'$$Q'		( LL?3}#5"6b9J=9J8KLM
LL?3}#5"6b9J=9J8KLM-''r   c                     g } fd|D        }dt         j                  v rW|r6|D ]/  }d d   |   v s d   |   d    d   k7  s|j                  |       1 |S |D ]  }||v s|j                  |        |S dt         j                  v rU|r6|D ]/  }d d   |   v s d   |   d    d   k7  s|j                  |       1 |S |D ]  }||v s|j                  |        |S )Nc              3   2   K   | ]  }|d    v s|  yw)r,   Nr)   )rN  inst_idr  s     r   rP  z+list_purgeable_instances.<locals>.<genexpr>  s     [WWkHZ=Z[s   rB   rM   r   )rK   r-   r   )r  r  r  r  r  instances_to_terminater,   r   s   `       r   list_purgeable_instancesr    sD   [(9[I v}}, 5%/?)@)CC-.q12FG5QeKff*11!45. "!!  5))*11!45  "! 
fmm	+ 5(E2B,CA,FF-.q12CDN_H``*11!45 "!	  5))*11!45 "!r   c                 *   t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }t         j                  j                  d      }	d}
d}t        | |      d   }||d	   }t	        |      }|d
   }t         j                  j                  d      rt        |||      \  }}nt        ||	|      \  }}|t        |      z
  }t        |||	||      }t         j                  d|        t         j                  dg |        t         j                  dg |        t         j                  dg |        |dk(  rdd}
|d
   |k7  r;||d
   }t        |d   |      }t        | fi | t         j                  d|        |rd}
d}|}|}t         j                  d       ||k  r&|dk7  r!|d | }d}
d}t         j                  | d       t         j                  d|
        |D ]4  }t        | ||       t         j                  d|        t        | ||
       6 |||fS )Nr  r   r   r-  r  r  Fr   r   r   rB   znew instances needed: znew instances: zold instances: zbatch instances: Tr5   )r5   r   z*Updating minimum size back to original of zNo new instances neededz new instances neededzdecrementing capacity: zterminating instance: )rK   r-   r   r   r   r  r  r   r  r  r$   ru   r  r   )r   r  r  	leftoversr  r   r   r   r  r  r   
break_loopr  r  r  r  r  r  r  r  r&   s                        r   r  r    s   ""#78J}}  ,H}}(();<""6*J}}  ,H}}  ,HJ*:zB1EH#$568$EI&L}}-.'EeXWh'i$}'GxYj'k$}*S-?? 6eXxQbduv
LL)*=)>?@
LL?#4]#4"567
LL?#4]#4"567
LL$%?'=%?$@ABa!I(*#I.!x@V7WaijNz4^4LLEhZPQ !&
!../Z',?1,D!78L9L!M"
+,,ABC
LL*+=*>?@- LZ5-k];<z;8JKL |%;;;r   c           	         t         j                  j                  d      }t         j                  j                  d      }t        | |      d   }d}t	        j                         |z   }|t	        j                         kD  r|dkD  rt         j                  d       d}t        | |      d   }t        |      }|d   }fd|D        }|D ]L  }	||	   d   }
||	   d	   }t         j                  d
|	 d|
 d|        |
j                  d      s|dk(  sH|dz  }N t	        j                  d       |t	        j                         kD  r|dkD  r|t	        j                         k  r,t         j                  dt	        j                                 y y )Nr   r-  r   r   z"waiting for instances to terminater   c              3   ,   K   | ]  }|v s|  y wrM  r)   )rN  r   r  s     r   rP  z%wait_for_term_inst.<locals>.<genexpr>.  s     F1!~2EQFs   	r   r   z	Instance z has state of r   r   	Unhealthyr   r|  rF   )rK   r-   r   r   r  r  r   
startswithr  rL   r	  )r   r  r   r   r  r  r  r   r,   r   	lifecyclehealths    `          r   r  r  "  sn   ==$$^4L""6*J*:zB1EHE99;-L

$9:.z:FqIx(/0FF	 	A&q)*;<I#A&7FLL9QC~i[&JK##M2f6K
	 	

2 
$ tyy{"OPTP\P\P^O_`a #r   c           	         t        | |      d   }t        |      }t        j                  d| d| d||           t	        j                         |z   }|t	        j                         kD  rx|||   kD  rpt        j                  d| d| d||           t	        j
                  d       t        | |      d   }t        |      }|t	        j                         kD  r	|||   kD  rp|t	        j                         k  r+t        j                  dt	        j                                 t        j                  d| d	|        |S )
Nr   zWaiting for z = z, currently r   z4Waited too long for new instances to become viable. rF   zReached r  )r   r   rK   r  r  r  rL   r	  )r   r   r   r  propr  r  s          r   rV  rV  <  s   *:zB1EH8$E
LL<vSl5;-PQ99;-L

$d)C|D6\N,uT{mTU

2.z:FqIx(	 
$d)C
 tyy{"STXT`T`TbScde
LL8D6L>23Lr   c                     t         j                  j                  d      }t        | |      }t	        t        |            S )Nr-  )rK   r-   r   r   rQ  r   )r   r   r  s      r   
asg_existsr  O  s1    ""6*J*:zBHHr   c                     t        dHi dt        dddg      dt        dd      d	t        dd      d
t        dd      dt        d      dt        dd t        t        d      t        d      t        d                  dt        d      dt        d      dt        d      dt        dd t        t        dd      t        dd t        t        d      t        d      t        d      t        d      t        d      t        d                              dt        d      dt        d      dt        dd      dt        dddd      d t        ddd!d"      d#t        dddg d$      d%t        dddg d$      d&t        ddd!d"      d't        ddd!d      d(t        ddd!d      d)t        dd*+      d,t        d-d-d.g/      d0t        dg d1      d2t        d!d"+      d3t        dd*+      d4t        d5d5d6g/      d7t        dd*+      d8t        d!d+      d9t        dd:d1      d;t        dd +      d<t        dg d=d1      d>t        dg d1      d?t        d!d"+      d@t        ddA+      dBt        dg dCd1      } t        | dd d#gd d%gddggD      at        j                  j	                  d,      }t        j                  j	                  d#      }t        j                  j	                  d       }t        j                  j	                  d%      }t        j                  dE      }d"x}x}x}}	t        |      }
|d-k(  rt        |      \  }}n&|d.k(  r!t        |      }t        j                  |F       |
rP|s|rLt        j                  j	                  d      st        j                  j	                  d      rt        |      \  }}|
rN|rLt        j                  j	                  d      st        j                  j	                  d      rt        |      \  }	}|s|s|	rd}t        j                  dHdG|i y )INr-  Tr   r   )requiredtypealiasesrd   r  )r  elementsrm   r   rB   )r  rM   r$   )r   rH   rD   )r  defaultoptionsr   intr   r   r   )on_demand_allocation_strategyon_demand_base_capacity(on_demand_percentage_above_base_capacityspot_allocation_strategyspot_instance_poolsspot_max_price)r   r   r3  r   r   r  z14.0.0z
amazon.awsr   )removed_in_versionremoved_from_collectionr  r  r  rQ  Fr  )r  r  r  r  r  r   r  r  r  r   i,  )r  r  statepresentabsent)r  choicesr   )r  r  r  r4  r5  r6  EC2r   r   r7  r   Defaultr8  rZ   )zautoscaling:EC2_INSTANCE_LAUNCHz%autoscaling:EC2_INSTANCE_LAUNCH_ERRORz"autoscaling:EC2_INSTANCE_TERMINATEz(autoscaling:EC2_INSTANCE_TERMINATE_ERRORr7   r   r9  1Minuter:  )GroupMinSizeGroupMaxSizeGroupDesiredCapacityGroupInServiceInstancesGroupPendingInstancesGroupStandbyInstancesGroupTerminatingInstancesGroupTotalInstances)argument_specsupports_check_modemutually_exclusiveautoscaling)rC  rC  r)   )r$   r   rK   r-   r   r   r  rz  r  rS  r  r  )r  r  r  r  r   r   rC  create_changedreplace_changeddetach_changedexistsrg  s               r   mainr  U  s(    y4el^Dy%8y FU;y  Ve<	y
  U+y %(%)u%5#'U#3
y 5!y  5!!y" #.#y$  $#%@'+  6:6F04%0@AE5AQ1551A,0e,<'+'7( 
%yJ %(KyL 5)MyN !fu=OyP  '$0	
Qy\ #'$0	
]yh '$0
iyv '$0
wyD $('$0	$
EyP '$0	
Qy\ '$0	
]yh uc2iyj 9y(.CDkyl vrF;myn VU3oyp !eS9qyr uuenEsyt 5#6uyv  VT:wyx "vy5Qyyz  UD9{y|   	
}yP FBGQyR  VU;SyT !eY?UyV 	 
WyMx # $&9:$&89!#45
F MMg&E))*=>"MM--.EF}}(();<}-JBGGGGnG
#F	)A*)M&	(	*:6) 	"&7]]348I8IJ[8\*1**=' 	]]348I8IJ[8\)/
);&N
7W77r   __main__r)   )F)CDOCUMENTATIONEXAMPLESRETURNr  r   ImportErroransible.module_utils._textr   0ansible.module_utils.common.dict_transformationsr   r   <ansible_collections.amazon.aws.plugins.module_utils.botocorer   =ansible_collections.amazon.aws.plugins.module_utils.elb_utilsr   ;ansible_collections.amazon.aws.plugins.module_utils.modulesr   ;ansible_collections.amazon.aws.plugins.module_utils.retriesr	   Bansible_collections.amazon.aws.plugins.module_utils.transformationr
   r$   backoff_paramsjittered_backoffr   r'   r+   r1   r;   r>   r@   rJ   rS   r[   r^   rb   rg   rn   rr   ru   r|   r   r   r   r   r   r  r  r#  r'  r)  r7   rz  r  r  r  r  r  r  r  r  r  r  rV  r  r  __name__r)   r   r   <module>r     s  n`dLJ
X 	 1 U U \ ` X P db37 ,^,l -l
 ,^, - ,^,9 -9 ,^,a -a ,^,\ -\ ,^,[ -[ ,^,Z -Z
 ,^,Z -Z ,^,3 -3 ,^, - ,^,d -d ,^,f -f ,^,f -f ,^,t -t ,^,t -t ,^,3 -3 c4O3PcTbcb db ,^, - ,^, -s[|/d^:"@"@a0j0,'D
'T(
,m#`# L(8(6"B@<Fb4&i8X zF i*  		s   I* *I32I3