community.aws.ec2_asg – Create or delete AWS AutoScaling Groups (ASGs)

Note

This plugin is part of the community.aws collection (version 1.4.0).

To install it use: ansible-galaxy collection install community.aws.

To use it in a playbook, specify: community.aws.ec2_asg.

New in version 1.0.0: of community.aws

Synopsis

  • Can create or delete AWS AutoScaling Groups.

  • Can be used with the community.aws.ec2_lc module to manage Launch Configurations.

Requirements

The below requirements are needed on the host that executes this module.

  • boto

  • boto3

  • botocore

  • python >= 2.6

Parameters

Parameter Choices/Defaults Comments
availability_zones
list / elements=string
List of availability zone names in which to create the group.
Defaults to all the availability zones in the region if vpc_zone_identifier is not set.
aws_access_key
string
AWS access key. If not set then the value of the AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY or EC2_ACCESS_KEY environment variable is used.
If profile is set this parameter is ignored.
Passing the aws_access_key and profile options at the same time has been deprecated and the options will be made mutually exclusive after 2022-06-01.

aliases: ec2_access_key, access_key
aws_ca_bundle
path
The location of a CA Bundle to use when validating SSL certificates.
Only used for boto3 based modules.
Note: The CA Bundle is read 'module' side and may need to be explicitly copied from the controller if not run locally.
aws_config
dictionary
A dictionary to modify the botocore configuration.
Only the 'user_agent' key is used for boto modules. See http://boto.cloudhackers.com/en/latest/boto_config_tut.html#boto for more boto configuration.
aws_secret_key
string
AWS secret key. If not set then the value of the AWS_SECRET_ACCESS_KEY, AWS_SECRET_KEY, or EC2_SECRET_KEY environment variable is used.
If profile is set this parameter is ignored.
Passing the aws_secret_key and profile options at the same time has been deprecated and the options will be made mutually exclusive after 2022-06-01.

aliases: ec2_secret_key, secret_key
debug_botocore_endpoint_logs
boolean
    Choices:
  • no ←
  • yes
Use a botocore.endpoint logger to parse the unique (rather than total) "resource:action" API calls made during a task, outputing the set to the resource_actions key in the task results. Use the aws_resource_action callback to output to total list made during a playbook. The ANSIBLE_DEBUG_BOTOCORE_LOGS environment variable may also be used.
default_cooldown
integer
Default:
300
The number of seconds after a scaling activity completes before another can begin.
desired_capacity
integer
Desired number of instances in group, if unspecified then the current group value will be used.
ec2_url
string
Url to use to connect to EC2 or your Eucalyptus cloud (by default the module will use EC2 endpoints). Ignored for modules where region is required. Must be specified for all other modules if region is not used. If not set then the value of the EC2_URL environment variable, if any, is used.

aliases: aws_endpoint_url, endpoint_url
health_check_period
integer
Default:
300
Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health.
health_check_type
string
    Choices:
  • EC2 ←
  • ELB
The service you want the health status from, Amazon EC2 or Elastic Load Balancer.
launch_config_name
string
Name of the Launch configuration to use for the group. See the community.aws.ec2_lc) module for managing these.
If unspecified then the current group value will be used. One of launch_config_name or launch_template must be provided.
launch_template
dictionary
Dictionary describing the Launch Template to use
launch_template_id
string
The id of the launch template. Only one of launch_template_name or launch_template_id is required.
launch_template_name
string
The name of the launch template. Only one of launch_template_name or launch_template_id is required.
version
string
The version number of the launch template to use.
Defaults to latest version if not provided.
lc_check
boolean
    Choices:
  • no
  • yes ←
Check to make sure instances that are being replaced with replace_instances do not already have the current launch_config.
load_balancers
list / elements=string
List of ELB names to use for the group. Use for classic load balancers.
lt_check
boolean
    Choices:
  • no
  • yes ←
Check to make sure instances that are being replaced with replace_instances do not already have the current launch_template or I(launch_template version.
max_instance_lifetime
integer
The maximum amount of time, in seconds, that an instance can be in service.
Maximum instance lifetime must be equal to 0, between 604800 and 31536000 seconds (inclusive), or not specified.
Value of 0 removes lifetime restriction.
max_size
integer
Maximum number of instances in group, if unspecified then the current group value will be used.
metrics_collection
boolean
    Choices:
  • no ←
  • yes
Enable ASG metrics collection.
metrics_granularity
string
Default:
"1Minute"
When metrics_collection=true this will determine the granularity of metrics collected by CloudWatch.
metrics_list
list / elements=string
Default:
["GroupMinSize", "GroupMaxSize", "GroupDesiredCapacity", "GroupInServiceInstances", "GroupPendingInstances", "GroupStandbyInstances", "GroupTerminatingInstances", "GroupTotalInstances"]
List of autoscaling metrics to collect when metrics_collection=true.
min_size
integer
Minimum number of instances in group, if unspecified then the current group value will be used.
mixed_instances_policy
dictionary
A mixed instance policy to use for the ASG.
Only used when the ASG is configured to use a Launch Template (launch_template).
instance_types
list / elements=string
A list of instance_types.
name
string / required
Unique name for group to be created or deleted.
notification_topic
string
A SNS topic ARN to send auto scaling notifications to.
notification_types
list / elements=string
Default:
["autoscaling:EC2_INSTANCE_LAUNCH", "autoscaling:EC2_INSTANCE_LAUNCH_ERROR", "autoscaling:EC2_INSTANCE_TERMINATE", "autoscaling:EC2_INSTANCE_TERMINATE_ERROR"]
A list of auto scaling events to trigger notifications on.
placement_group
string
Physical location of your cluster placement group created in Amazon EC2.
profile
string
Uses a boto profile. Only works with boto >= 2.24.0.
Using profile will override aws_access_key, aws_secret_key and security_token and support for passing them at the same time as profile has been deprecated.
aws_access_key, aws_secret_key and security_token will be made mutually exclusive with profile after 2022-06-01.

aliases: aws_profile
region
string
The AWS region to use. If not specified then the value of the AWS_REGION or EC2_REGION environment variable, if any, is used. See http://docs.aws.amazon.com/general/latest/gr/rande.html#ec2_region

aliases: aws_region, ec2_region
replace_all_instances
boolean
    Choices:
  • no ←
  • yes
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 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.
replace_batch_size
integer
Default:
1
Number of instances you'd like to replace at a time. Used with replace_all_instances.
replace_instances
list / elements=string
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.
security_token
string
AWS STS security token. If not set then the value of the AWS_SECURITY_TOKEN or EC2_SECURITY_TOKEN environment variable is used.
If profile is set this parameter is ignored.
Passing the security_token and profile options at the same time has been deprecated and the options will be made mutually exclusive after 2022-06-01.

aliases: aws_security_token, access_token
state
string
    Choices:
  • present ←
  • absent
Register or deregister the instance.
suspend_processes
list / elements=string
Default:
[]
A list of scaling processes to suspend.
Valid values include:
Launch, Terminate, HealthCheck, ReplaceUnhealthy, AZRebalance, AlarmNotification, ScheduledActions, AddToLoadBalancer
Full documentation of valid values can be found in the AWS documentation:
tags
list / elements=dictionary
A list of tags to add to the Auto Scale Group.
Optional key is propagate_at_launch, which defaults to true.
When propagate_at_launch is true the tags will be propagated to the Instances created.
target_group_arns
list / elements=string
List of target group ARNs to use for the group. Use for application load balancers.
termination_policies
list / elements=string
Default:
"Default"
An ordered list of criteria used for selecting instances to be removed from the Auto Scaling group when reducing capacity.
Using termination_policies=Default when modifying an existing AutoScalingGroup will result in the existing policy being retained instead of changed to Default.
Valid values include: Default, OldestInstance, NewestInstance, OldestLaunchConfiguration, ClosestToNextInstanceHour
Full documentation of valid values can be found in the AWS documentation:
validate_certs
boolean
    Choices:
  • no
  • yes ←
When set to "no", SSL certificates will not be validated for boto versions >= 2.6.0.
vpc_zone_identifier
list / elements=string
List of VPC subnets to use
wait_for_instances
boolean
    Choices:
  • no
  • yes ←
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".
wait_timeout
integer
Default:
300
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.

Notes

Note

  • If parameters are not set within the module, the following environment variables can be used in decreasing order of precedence AWS_URL or EC2_URL, AWS_PROFILE or AWS_DEFAULT_PROFILE, AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY or EC2_ACCESS_KEY, AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY or EC2_SECRET_KEY, AWS_SECURITY_TOKEN or EC2_SECURITY_TOKEN, AWS_REGION or EC2_REGION, AWS_CA_BUNDLE

  • Ansible uses the boto configuration file (typically ~/.boto) if no credentials are provided. See https://boto.readthedocs.io/en/latest/boto_config_tut.html

  • AWS_REGION or EC2_REGION can be typically be used to specify the AWS region, when required, but this can also be configured in the boto config file

Examples

# Basic configuration with Launch Configuration

- community.aws.ec2_asg:
    name: special
    load_balancers: [ 'lb1', 'lb2' ]
    availability_zones: [ 'eu-west-1a', 'eu-west-1b' ]
    launch_config_name: 'lc-1'
    min_size: 1
    max_size: 10
    desired_capacity: 5
    vpc_zone_identifier: [ 'subnet-abcd1234', 'subnet-1a2b3c4d' ]
    tags:
      - environment: production
        propagate_at_launch: no

# Rolling ASG Updates

# Below is an example of how to assign a new launch config to an ASG and terminate old instances.
#
# All instances in "myasg" that do not have the launch configuration named "my_new_lc" will be terminated in
# a rolling fashion with instances using the current launch configuration, "my_new_lc".
#
# This could also be considered a rolling deploy of a pre-baked AMI.
#
# If this is a newly created group, the instances will not be replaced since all instances
# will have the current launch configuration.

- name: create launch config
  community.aws.ec2_lc:
    name: my_new_lc
    image_id: ami-lkajsf
    key_name: mykey
    region: us-east-1
    security_groups: sg-23423
    instance_type: m1.small
    assign_public_ip: yes

- community.aws.ec2_asg:
    name: myasg
    launch_config_name: my_new_lc
    health_check_period: 60
    health_check_type: ELB
    replace_all_instances: yes
    min_size: 5
    max_size: 5
    desired_capacity: 5
    region: us-east-1

# To only replace a couple of instances instead of all of them, supply a list
# to "replace_instances":

- community.aws.ec2_asg:
    name: myasg
    launch_config_name: my_new_lc
    health_check_period: 60
    health_check_type: ELB
    replace_instances:
    - i-b345231
    - i-24c2931
    min_size: 5
    max_size: 5
    desired_capacity: 5
    region: us-east-1

# Basic Configuration with Launch Template

- community.aws.ec2_asg:
    name: special
    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: no

# Basic Configuration with Launch Template using mixed instance policy

- community.aws.ec2_asg:
    name: special
    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
    min_size: 1
    max_size: 10
    desired_capacity: 5
    vpc_zone_identifier: [ 'subnet-abcd1234', 'subnet-1a2b3c4d' ]
    tags:
      - environment: production
        propagate_at_launch: no

Return Values

Common return values are documented here, the following are the fields unique to this module:

Key Returned Description
auto_scaling_group_arn
string
success
The unique ARN of the autoscaling group

Sample:
arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:6a09ad6d-eeee-1234-b987-ee123ced01ad:autoScalingGroupName/myasg
auto_scaling_group_name
string
success
The unique name of the auto scaling group

Sample:
myasg
availability_zones
list / elements=string
success
The availability zones for the auto scaling group

Sample:
['us-east-1d']
created_time
string
success
Timestamp of create time of the auto scaling group

Sample:
2017-11-08T14:41:48.272000+00:00
default_cooldown
integer
success
The default cooldown time in seconds.

Sample:
300
desired_capacity
integer
success
The number of EC2 instances that should be running in this group.

Sample:
3
healthcheck_period
integer
success
Length of time in seconds after a new EC2 instance comes into service that Auto Scaling starts checking its health.

Sample:
30
healthcheck_type
string
success
The service you want the health status from, one of "EC2" or "ELB".

Sample:
ELB
healthy_instances
integer
success
Number of instances in a healthy state

Sample:
5
in_service_instances
integer
success
Number of instances in service

Sample:
3
instance_facts
dictionary
success
Dictionary of EC2 instances and their status as it relates to the ASG.

Sample:
{'i-0123456789012': {'health_status': 'Healthy', 'launch_config_name': 'public-webapp-production-1', 'lifecycle_state': 'InService'}}
instances
list / elements=string
success
list of instance IDs in the ASG

Sample:
['i-0123456789012']
launch_config_name
string
success
Name of launch configuration associated with the ASG. Same as launch_configuration_name, provided for compatibility with ec2_asg module.

Sample:
public-webapp-production-1
load_balancers
list / elements=string
success
List of load balancers names attached to the ASG.

Sample:
['elb-webapp-prod']
max_instance_lifetime
integer
success
The maximum amount of time, in seconds, that an instance can be in service.

Sample:
604800
max_size
integer
success
Maximum size of group

Sample:
3
metrics_collection
list / elements=string
success
List of enabled AutosSalingGroup metrics

Sample:
[{'Granularity': '1Minute', 'Metric': 'GroupInServiceInstances'}]
min_size
integer
success
Minimum size of group

Sample:
1
mixed_instance_policy
list / elements=string
success
Returns the list of instance types if a mixed instance policy is set.

Sample:
['t3.micro', 't3a.micro']
pending_instances
integer
success
Number of instances in pending state

Sample:
1
tags
list / elements=string
success
List of tags for the ASG, and whether or not each tag propagates to instances at launch.

Sample:
[{'key': 'Name', 'propagate_at_launch': 'true', 'resource_id': 'public-webapp-production-1', 'resource_type': 'auto-scaling-group', 'value': 'public-webapp-production-1'}, {'key': 'env', 'propagate_at_launch': 'true', 'resource_id': 'public-webapp-production-1', 'resource_type': 'auto-scaling-group', 'value': 'production'}]
target_group_arns
list / elements=string
success
List of ARNs of the target groups that the ASG populates

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
list / elements=string
success
List of names of the target groups that the ASG populates

Sample:
['target-group-host-hello', 'target-group-path-world']
termination_policies
list / elements=string
success
A list of termination policies for the group.

Sample:
['Default']
unhealthy_instances
integer
success
Number of instances in an unhealthy state

viable_instances
integer
success
Number of instances in a viable state

Sample:
1
vpc_zone_identifier
string
success
VPC zone ID / subnet id for the auto scaling group

Sample:
subnet-a31ef45f


Authors

  • Gareth Rushgrove (@garethr)