AWS Amazon EC2 Auto Scaling Group
This page shows how to write Terraform and CloudFormation for Amazon EC2 Auto Scaling Group and write them securely.
aws_autoscaling_group (Terraform)
The Group in Amazon EC2 Auto Scaling can be configured in Terraform with the resource name aws_autoscaling_group
. The following sections describe 2 examples of how to use the resource and its parameters.
Example Usage from GitHub
resource "aws_autoscaling_group" "success" {
name = "test"
min_size = 1
max_size = 1
tag {
resource "aws_autoscaling_group" "ngx_plus" {
name = "nginxlab-ngx-plus-autoscaling"
min_size = 2
max_size = 2
launch_configuration = aws_launch_configuration.ngx_plus.name
vpc_zone_identifier = [
Parameters
The following arguments are supported:
name
- (Optional) The name of the Auto Scaling Group. By default generated by Terraform. Conflicts withname_prefix
.name_prefix
- (Optional) Creates a unique name beginning with the specified prefix. Conflicts withname
.max_size
- (Required) The maximum size of the Auto Scaling Group.min_size
- (Required) The minimum size of the Auto Scaling Group. (See also Waiting for Capacity below.)availability_zones
- (Optional) A list of one or more availability zones for the group. Used for EC2-Classic, attaching a network interface via id from a launch template and default subnets when not specified withvpc_zone_identifier
argument. Conflicts withvpc_zone_identifier
.capacity_rebalance
- (Optional) Indicates whether capacity rebalance is enabled. Otherwise, capacity rebalance is disabled.default_cooldown
- (Optional) The amount of time, in seconds, after a scaling activity completes before another scaling activity can start.launch_configuration
- (Optional) The name of the launch configuration to use.launch_template
- (Optional) Nested argument with Launch template specification to use to launch instances. See Launch Template below for more details.mixed_instances_policy
(Optional) Configuration block containing settings to define launch targets for Auto Scaling groups. See Mixed Instances Policy below for more details.initial_lifecycle_hook
- (Optional) One or more Lifecycle Hooks to attach to the Auto Scaling Group before instances are launched. The syntax is exactly the same as the separateaws_autoscaling_lifecycle_hook
resource, without theautoscaling_group_name
attribute. Please note that this will only work when creating a new Auto Scaling Group. For all other use-cases, please useaws_autoscaling_lifecycle_hook
resource.health_check_grace_period
- (Optional, Default: 300) Time (in seconds) after instance comes into service before checking health.health_check_type
- (Optional) "EC2" or "ELB". Controls how health checking is done.desired_capacity
- (Optional) The number of Amazon EC2 instances that should be running in the group. (See also Waiting for Capacity below.)force_delete
- (Optional) Allows deleting the Auto Scaling Group without waiting for all instances in the pool to terminate. You can force an Auto Scaling Group to delete even if it's in the process of scaling a resource. Normally, Terraform drains all the instances before deleting the group. This bypasses that behavior and potentially leaves resources dangling.load_balancers
(Optional) A list of elastic load balancer names to add to the autoscaling group names. Only valid for classic load balancers. For ALBs, usetarget_group_arns
instead.vpc_zone_identifier
(Optional) A list of subnet IDs to launch resources in. Subnets automatically determine which availability zones the group will reside. Conflicts withavailability_zones
.target_group_arns
(Optional) A set ofaws_alb_target_group
ARNs, for use with Application or Network Load Balancing.termination_policies
(Optional) A list of policies to decide how the instances in the Auto Scaling Group should be terminated. The allowed values areOldestInstance
,NewestInstance
,OldestLaunchConfiguration
,ClosestToNextInstanceHour
,OldestLaunchTemplate
,AllocationStrategy
,Default
.suspended_processes
- (Optional) A list of processes to suspend for the Auto Scaling Group. The allowed values areLaunch
,Terminate
,HealthCheck
,ReplaceUnhealthy
,AZRebalance
,AlarmNotification
,ScheduledActions
,AddToLoadBalancer
. Note that if you suspend either theLaunch
orTerminate
process types, it can prevent your Auto Scaling Group from functioning properly.tag
(Optional) Configuration block(s) containing resource tags. Conflicts withtags
. See Tag below for more details.tags
(Optional) Set of maps containing resource tags. Conflicts withtag
. See Tags below for more details.placement_group
(Optional) The name of the placement group into which you'll launch your instances, if any.metrics_granularity
- (Optional) The granularity to associate with the metrics to collect. The only valid value is1Minute
. Default is1Minute
.enabled_metrics
- (Optional) A list of metrics to collect. The allowed values areGroupDesiredCapacity
,GroupInServiceCapacity
,GroupPendingCapacity
,GroupMinSize
,GroupMaxSize
,GroupInServiceInstances
,GroupPendingInstances
,GroupStandbyInstances
,GroupStandbyCapacity
,GroupTerminatingCapacity
,GroupTerminatingInstances
,GroupTotalCapacity
,GroupTotalInstances
.wait_for_capacity_timeout
(Default: "10m") A maximum duration that Terraform should wait for ASG instances to be healthy before timing out. (See also Waiting for Capacity below.) Setting this to "0" causes Terraform to skip all Capacity Waiting behavior.min_elb_capacity
- (Optional) Setting this causes Terraform to wait for this number of instances from this Auto Scaling Group to show up healthy in the ELB only on creation. Updates will not wait on ELB instance number changes. (See also Waiting for Capacity below.)wait_for_elb_capacity
- (Optional) Setting this will cause Terraform to wait for exactly this number of healthy instances from this Auto Scaling Group in all attached load balancers on both create and update operations. (Takes precedence overmin_elb_capacity
behavior.) (See also Waiting for Capacity below.)protect_from_scale_in
(Optional) Allows setting instance protection. The Auto Scaling Group will not select instances with this setting for termination during scale in events.service_linked_role_arn
(Optional) The ARN of the service-linked role that the ASG will use to call other AWS servicesmax_instance_lifetime
(Optional) The maximum amount of time, in seconds, that an instance can be in service, values must be either equal to 0 or between 86400 and 31536000 seconds.instance_refresh
- (Optional) If this block is configured, start an Instance Refresh when this Auto Scaling Group is updated. Defined below.warm_pool
- (Optional) If this block is configured, add a Warm Pool to the specified Auto Scaling group. Defined below
launch_template
NOTE: Either
id
orname
must be specified.
The top-level launch_template
block supports the following:
id
- (Optional) The ID of the launch template. Conflicts withname
.name
- (Optional) The name of the launch template. Conflicts withid
.version
- (Optional) Template version. Can be version number,$Latest
, or$Default
. (Default:$Default
).
mixed_instances_policy
instances_distribution
- (Optional) Nested argument containing settings on how to mix on-demand and Spot instances in the Auto Scaling group. Defined below.launch_template
- (Required) Nested argument containing launch template settings along with the overrides to specify multiple instance types and weights. Defined below.
mixed_instances_policy instances_distribution
This configuration block supports the following:
on_demand_allocation_strategy
- (Optional) Strategy to use when launching on-demand instances. Valid values:prioritized
. Default:prioritized
.on_demand_base_capacity
- (Optional) Absolute minimum amount of desired capacity that must be fulfilled by on-demand instances. Default:0
.on_demand_percentage_above_base_capacity
- (Optional) Percentage split between on-demand and Spot instances above the base on-demand capacity. Default:100
.spot_allocation_strategy
- (Optional) How to allocate capacity across the Spot pools. Valid values:lowest-price
,capacity-optimized
,capacity-optimized-prioritized
. Default:lowest-price
.spot_instance_pools
- (Optional) Number of Spot pools per availability zone to allocate capacity. EC2 Auto Scaling selects the cheapest Spot pools and evenly allocates Spot capacity across the number of Spot pools that you specify. Default:2
.spot_max_price
- (Optional) Maximum price per unit hour that the user is willing to pay for the Spot instances. Default: an empty string which means the on-demand price.
mixed_instances_policy launch_template
This configuration block supports the following:
launch_template_specification
- (Required) Nested argument defines the Launch Template. Defined below.override
- (Optional) List of nested arguments provides the ability to specify multiple instance types. This will override the same parameter in the launch template. For on-demand instances, Auto Scaling considers the order of preference of instance types to launch based on the order specified in the overrides list. Defined below.
mixed_instances_policy launch_template launch_template_specification
NOTE: Either
launch_template_id
orlaunch_template_name
must be specified.
This configuration block supports the following:
launch_template_id
- (Optional) The ID of the launch template. Conflicts withlaunch_template_name
.launch_template_name
- (Optional) The name of the launch template. Conflicts withlaunch_template_id
.version
- (Optional) Template version. Can be version number,$Latest
, or$Default
. (Default:$Default
).
mixed_instances_policy launch_template override
This configuration block supports the following:
instance_type
- (Optional) Override the instance type in the Launch Template.launch_template_specification
- (Optional) Override the instance launch template specification in the Launch Template.weighted_capacity
- (Optional) The number of capacity units, which gives the instance type a proportional weight to other instance types.
tag and tags
The tag
attribute accepts exactly one tag declaration with the following fields:
key
- (Required) Keyvalue
- (Required) Valuepropagate_at_launch
- (Required) Enables propagation of the tag to Amazon EC2 instances launched via this ASG
To declare multiple tags additional tag
blocks can be specified.
Alternatively the tags
attributes can be used, which accepts a list of maps containing the above field names as keys and their respective values.
This allows the construction of dynamic lists of tags which is not possible using the single tag
attribute.
tag
and tags
are mutually exclusive, only one of them can be specified.
NOTE: Other AWS APIs may automatically add special tags to their associated Auto Scaling Group for management purposes, such as ECS Capacity Providers adding the
AmazonECSManaged
tag. These generally should be included in the configuration so Terraform does not attempt to remove them and so if themin_size
was greater than zero on creation, that these tag(s) are applied to any initial EC2 Instances in the Auto Scaling Group. If these tag(s) were missing in the Auto Scaling Group configuration on creation, affected EC2 Instances missing the tags may require manual intervention of adding the tags to ensure they work properly with the other AWS service.
instance_refresh
This configuration block supports the following:
strategy
- (Required) The strategy to use for instance refresh. The only allowed value isRolling
. See StartInstanceRefresh Action for more information.preferences
- (Optional) Override default parameters for Instance Refresh.checkpoint_delay
- (Optional) The number of seconds to wait after a checkpoint. Defaults to3600
.checkpoint_percentages
- (Optional) List of percentages for each checkpoint. Values must be unique and in ascending order. To replace all instances, the final number must be100
.instance_warmup
- (Optional) The number of seconds until a newly launched instance is configured and ready to use. Default behavior is to use the Auto Scaling Group's health check grace period.min_healthy_percentage
- (Optional) The amount of capacity in the Auto Scaling group that must remain healthy during an instance refresh to allow the operation to continue, as a percentage of the desired capacity of the Auto Scaling group. Defaults to90
.
triggers
- (Optional) Set of additional property names that will trigger an Instance Refresh. A refresh will always be triggered by a change in any oflaunch_configuration
,launch_template
, ormixed_instances_policy
.
NOTE: A refresh is started when any of the following Auto Scaling Group properties change:
launch_configuration
,launch_template
,mixed_instances_policy
. Additional properties can be specified in thetriggers
property ofinstance_refresh
.
NOTE: Auto Scaling Groups support up to one active instance refresh at a time. When this resource is updated, any existing refresh is cancelled.
NOTE: Depending on health check settings and group size, an instance refresh may take a long time or fail. This resource does not wait for the instance refresh to complete.
warm_pool
This configuration block supports the following:
pool_state
- (Optional) Sets the instance state to transition to after the lifecycle hooks finish. Valid values are: Stopped (default) or Running.min_size
- (Optional) Specifies the minimum number of instances to maintain in the warm pool. This helps you to ensure that there is always a certain number of warmed instances available to handle traffic spikes. Defaults to 0 if not specified.max_group_prepared_capacity
- (Optional) Specifies the total maximum number of instances that are allowed to be in the warm pool or in any state except Terminated for the Auto Scaling group.
In addition to all arguments above, the following attributes are exported:
id
- The Auto Scaling Group id.arn
- The ARN for this Auto Scaling Groupavailability_zones
- The availability zones of the Auto Scaling Group.min_size
- The minimum size of the Auto Scaling Groupmax_size
- The maximum size of the Auto Scaling Groupdefault_cooldown
- Time between a scaling activity and the succeeding scaling activity.name
- The name of the Auto Scaling Grouphealth_check_grace_period
- Time after instance comes into service before checking health.health_check_type
- "EC2" or "ELB". Controls how health checking is done.desired_capacity
-The number of Amazon EC2 instances that should be running in the group.launch_configuration
- The launch configuration of the Auto Scaling Groupvpc_zone_identifier
(Optional) - The VPC zone identifier
NOTE: When using
ELB
as thehealth_check_type
,health_check_grace_period
is required.
NOTE: Terraform has two types of ways you can add lifecycle hooks - via the
initial_lifecycle_hook
attribute from this resource, or via the separateaws_autoscaling_lifecycle_hook
resource.initial_lifecycle_hook
exists here because any lifecycle hooks added withaws_autoscaling_lifecycle_hook
will not be added until the Auto Scaling Group has been created, and depending on your capacity settings, after the initial instances have been launched, creating unintended behavior. If you need hooks to run on all instances, add them withinitial_lifecycle_hook
here, but take care to not duplicate these hooks inaws_autoscaling_lifecycle_hook
.
Explanation in Terraform Registry
Provides an Auto Scaling Group resource. -> Note: You must specify either
launch_configuration
,launch_template
, ormixed_instances_policy
.NOTE on Auto Scaling Groups and ASG Attachments: Terraform currently provides both a standalone
aws_autoscaling_attachment
resource (describing an ASG attached to an ELB or ALB), and anaws_autoscaling_group
withload_balancers
andtarget_group_arns
defined in-line. These two methods are not mutually-exclusive. Ifaws_autoscaling_attachment
resources are used, either alone or with inlineload_balancers
ortarget_group_arns
, theaws_autoscaling_group
resource must be configured to ignore changes to theload_balancers
andtarget_group_arns
arguments within alifecycle
configuration block.
Tips: Best Practices for The Other AWS Amazon EC2 Auto Scaling Resources
In addition to the aws_launch_configuration, AWS Amazon EC2 Auto Scaling has the other resources that should be configured for security reasons. Please check some examples of those resources and precautions.
aws_launch_configuration
Check public IPs should be given to Auto Scaling instances
It is better to block public access on the Internet to them. It is better to avoid associating public IP addresses if this is unintentional.
AWS::AutoScaling::AutoScalingGroup (CloudFormation)
The AutoScalingGroup in AutoScaling can be configured in CloudFormation with the resource name AWS::AutoScaling::AutoScalingGroup
. The following sections describe how to use the resource and its parameters.
Example Usage from GitHub
An example could not be found in GitHub.
Parameters
-
AutoScalingGroupName
optional - String -
AvailabilityZones
optional - List -
CapacityRebalance
optional - Boolean -
Context
optional - String -
Cooldown
optional - String -
DesiredCapacity
optional - String -
DesiredCapacityType
optional - String -
HealthCheckGracePeriod
optional - Integer -
HealthCheckType
optional - String -
InstanceId
optional - String -
LaunchConfigurationName
optional - String -
LaunchTemplate
optional - LaunchTemplateSpecification -
LifecycleHookSpecificationList
optional - List of LifecycleHookSpecification -
LoadBalancerNames
optional - List -
MaxInstanceLifetime
optional - Integer -
MaxSize
required - String -
MetricsCollection
optional - List of MetricsCollection -
MinSize
required - String -
MixedInstancesPolicy
optional - MixedInstancesPolicy -
NewInstancesProtectedFromScaleIn
optional - Boolean -
NotificationConfigurations
optional - List of NotificationConfiguration -
PlacementGroup
optional - String -
ServiceLinkedRoleARN
optional - String -
Tags
optional - List of TagProperty -
TargetGroupARNs
optional - List -
TerminationPolicies
optional - List -
VPCZoneIdentifier
optional - List
Explanation in CloudFormation Registry
The
AWS::AutoScaling::AutoScalingGroup
resource defines an Amazon EC2 Auto Scaling group, which is a collection of Amazon EC2 instances that are treated as a logical grouping for the purposes of automatic scaling and management.Note Amazon EC2 Auto Scaling configures instances launched as part of an Auto Scaling group using either a launch template or a launch configuration. We recommend that you use a launch template to make sure that you can use the latest features of Amazon EC2, such as Dedicated Hosts and T2 Unlimited instances. For more information, see Creating a launch template for an Auto Scaling group. You can find sample launch templates in AWS::EC2::LaunchTemplate.
For more information, see CreateAutoScalingGroup and UpdateAutoScalingGroup in the Amazon EC2 Auto Scaling API Reference. For more information about Amazon EC2 Auto Scaling, see the Amazon EC2 Auto Scaling User Guide.
Frequently asked questions
What is AWS Amazon EC2 Auto Scaling Group?
AWS Amazon EC2 Auto Scaling Group is a resource for Amazon EC2 Auto Scaling of Amazon Web Service. Settings can be wrote in Terraform and CloudFormation.
Where can I find the example code for the AWS Amazon EC2 Auto Scaling Group?
For Terraform, the terraform-compliance/cli and jpouyaud-perso/aws-nlb-ha-sni-routing-asg source code examples are useful. See the Terraform Example section for further details.