Resource: awsAutoscalingGroup
Provides an Auto Scaling Group resource.
-> Note: You must specify either launchConfiguration
, launchTemplate
, or mixedInstancesPolicy
.
\~> NOTE on Auto Scaling Groups and ASG Attachments: Terraform currently provides both a standalone awsAutoscalingAttachment
resource (describing an ASG attached to an ELB or ALB), and an awsAutoscalingGroup
with loadBalancers
and targetGroupArns
defined in-line. These two methods are not mutually-exclusive. If awsAutoscalingAttachment
resources are used, either alone or with inline loadBalancers
or targetGroupArns
, the awsAutoscalingGroup
resource must be configured to ignore changes to the loadBalancers
and targetGroupArns
arguments within a lifecycle
configuration block.
Hands-on: Try the Manage AWS Auto Scaling Groups tutorial on HashiCorp Learn.
Example Usage
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsPlacementGroupTest = new aws.placementGroup.PlacementGroup(
this,
"test",
{
name: "test",
strategy: "cluster",
}
);
new aws.autoscalingGroup.AutoscalingGroup(this, "bar", {
desiredCapacity: 4,
forceDelete: true,
healthCheckGracePeriod: 300,
healthCheckType: "ELB",
initialLifecycleHook: [
{
defaultResult: "CONTINUE",
heartbeatTimeout: 2000,
lifecycleTransition: "autoscaling:EC2_INSTANCE_LAUNCHING",
name: "foobar",
notificationMetadata: '${jsonencode({\n foo = "bar"\n })}',
notificationTargetArn: "arn:aws:sqs:us-east-1:444455556666:queue1*",
roleArn: "arn:aws:iam::123456789012:role/S3Access",
},
],
launchConfiguration: "${aws_launch_configuration.foobar.name}",
maxSize: 5,
minSize: 2,
name: "foobar3-terraform-test",
placementGroup: awsPlacementGroupTest.id,
tag: [
{
key: "foo",
propagateAtLaunch: true,
value: "bar",
},
{
key: "lorem",
propagateAtLaunch: false,
value: "ipsum",
},
],
timeouts: [
{
delete: "15m",
},
],
vpcZoneIdentifier: ["${aws_subnet.example1.id}", "${aws_subnet.example2.id}"],
});
With Latest Version Of Launch Template
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsLaunchTemplateFoobar = new aws.launchTemplate.LaunchTemplate(
this,
"foobar",
{
imageId: "ami-1a2b3c",
instanceType: "t2.micro",
namePrefix: "foobar",
}
);
new aws.autoscalingGroup.AutoscalingGroup(this, "bar", {
availabilityZones: ["us-east-1a"],
desiredCapacity: 1,
launchTemplate: {
id: awsLaunchTemplateFoobar.id,
version: "$Latest",
},
maxSize: 1,
minSize: 1,
});
Mixed Instances Policy
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsLaunchTemplateExample = new aws.launchTemplate.LaunchTemplate(
this,
"example",
{
imageId: "${data.aws_ami.example.id}",
instanceType: "c5.large",
namePrefix: "example",
}
);
const awsAutoscalingGroupExample = new aws.autoscalingGroup.AutoscalingGroup(
this,
"example_1",
{
availabilityZones: ["us-east-1a"],
desiredCapacity: 1,
maxSize: 1,
minSize: 1,
mixedInstancesPolicy: {
launchTemplate: {
launchTemplateSpecification: {
launchTemplateId: awsLaunchTemplateExample.id,
},
override: [
{
instanceType: "c4.large",
weightedCapacity: "3",
},
{
instanceType: "c3.large",
weightedCapacity: "2",
},
],
},
},
}
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsAutoscalingGroupExample.overrideLogicalId("example");
Mixed Instances Policy with Spot Instances and Capacity Rebalance
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsLaunchTemplateExample = new aws.launchTemplate.LaunchTemplate(
this,
"example",
{
imageId: "${data.aws_ami.example.id}",
instanceType: "c5.large",
namePrefix: "example",
}
);
const awsAutoscalingGroupExample = new aws.autoscalingGroup.AutoscalingGroup(
this,
"example_1",
{
capacityRebalance: true,
desiredCapacity: 12,
maxSize: 15,
minSize: 12,
mixedInstancesPolicy: {
instancesDistribution: {
onDemandBaseCapacity: 0,
onDemandPercentageAboveBaseCapacity: 25,
spotAllocationStrategy: "capacity-optimized",
},
launchTemplate: {
launchTemplateSpecification: {
launchTemplateId: awsLaunchTemplateExample.id,
},
override: [
{
instanceType: "c4.large",
weightedCapacity: "3",
},
{
instanceType: "c3.large",
weightedCapacity: "2",
},
],
},
},
vpcZoneIdentifier: [
"${aws_subnet.example1.id}",
"${aws_subnet.example2.id}",
],
}
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsAutoscalingGroupExample.overrideLogicalId("example");
Mixed Instances Policy with Instance level LaunchTemplateSpecification Overrides
When using a diverse instance set, some instance types might require a launch template with configuration values unique to that instance type such as a different AMI (Graviton2), architecture specific user data script, different EBS configuration, or different networking configuration.
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsLaunchTemplateExample = new aws.launchTemplate.LaunchTemplate(
this,
"example",
{
imageId: "${data.aws_ami.example.id}",
instanceType: "c5.large",
namePrefix: "example",
}
);
const awsLaunchTemplateExample2 = new aws.launchTemplate.LaunchTemplate(
this,
"example2",
{
imageId: "${data.aws_ami.example2.id}",
namePrefix: "example2",
}
);
const awsAutoscalingGroupExample = new aws.autoscalingGroup.AutoscalingGroup(
this,
"example_2",
{
availabilityZones: ["us-east-1a"],
desiredCapacity: 1,
maxSize: 1,
minSize: 1,
mixedInstancesPolicy: {
launchTemplate: {
launchTemplateSpecification: {
launchTemplateId: awsLaunchTemplateExample.id,
},
override: [
{
instanceType: "c4.large",
weightedCapacity: "3",
},
{
instanceType: "c6g.large",
launchTemplateSpecification: {
launchTemplateId: awsLaunchTemplateExample2.id,
},
weightedCapacity: "2",
},
],
},
},
}
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsAutoscalingGroupExample.overrideLogicalId("example");
Mixed Instances Policy with Attribute-based Instance Type Selection
As an alternative to manually choosing instance types when creating a mixed instances group, you can specify a set of instance attributes that describe your compute requirements.
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsLaunchTemplateExample = new aws.launchTemplate.LaunchTemplate(
this,
"example",
{
imageId: "${data.aws_ami.example.id}",
instanceType: "c5.large",
namePrefix: "example",
}
);
const awsAutoscalingGroupExample = new aws.autoscalingGroup.AutoscalingGroup(
this,
"example_1",
{
availabilityZones: ["us-east-1a"],
desiredCapacity: 1,
maxSize: 1,
minSize: 1,
mixedInstancesPolicy: {
launchTemplate: {
launchTemplateSpecification: {
launchTemplateId: awsLaunchTemplateExample.id,
},
override: [
{
instanceRequirements: {
memoryMib: {
min: 1000,
},
vcpuCount: {
min: 4,
},
},
},
],
},
},
}
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsAutoscalingGroupExample.overrideLogicalId("example");
Interpolated tags
import * as cdktf from "cdktf";
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
/*Terraform Variables are not always the best fit for getting inputs in the context of Terraform CDK.
You can read more about this at https://cdk.tf/variables*/
const extraTags = new cdktf.TerraformVariable(this, "extra_tags", {
default: [
{
key: "Foo",
propagate_at_launch: true,
value: "Bar",
},
{
key: "Baz",
propagate_at_launch: true,
value: "Bam",
},
],
});
new aws.autoscalingGroup.AutoscalingGroup(this, "bar", {
launchConfiguration: "${aws_launch_configuration.foobar.name}",
maxSize: 5,
minSize: 2,
name: "foobar3-terraform-test",
tags: `\${concat(
[
{
"key" = "interpolation1"
"value" = "value3"
"propagate_at_launch" = true
},
{
"key" = "interpolation2"
"value" = "value4"
"propagate_at_launch" = true
},
],
${extraTags.value},
)}`,
vpcZoneIdentifier: ["${aws_subnet.example1.id}", "${aws_subnet.example2.id}"],
});
Automatically refresh all instances after the group is updated
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const dataAwsAmiExample = new aws.dataAwsAmi.DataAwsAmi(this, "example", {
filter: [
{
name: "name",
values: ["amzn-ami-hvm-*-x86_64-gp2"],
},
],
mostRecent: true,
owners: ["amazon"],
});
const awsLaunchTemplateExample = new aws.launchTemplate.LaunchTemplate(
this,
"example_1",
{
imageId: dataAwsAmiExample.id,
instanceType: "t3.nano",
}
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsLaunchTemplateExample.overrideLogicalId("example");
const awsAutoscalingGroupExample = new aws.autoscalingGroup.AutoscalingGroup(
this,
"example_2",
{
availabilityZones: ["us-east-1a"],
desiredCapacity: 1,
instanceRefresh: {
preferences: {
minHealthyPercentage: 50,
},
strategy: "Rolling",
triggers: ["tag"],
},
launchTemplate: {
id: awsLaunchTemplateExample.id,
version: awsLaunchTemplateExample.latestVersion,
},
maxSize: 2,
minSize: 1,
tag: [
{
key: "Key",
propagateAtLaunch: true,
value: "Value",
},
],
}
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsAutoscalingGroupExample.overrideLogicalId("example");
Auto Scaling group with Warm Pool
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.autoscalingGroup.AutoscalingGroup(this, "example", {
availabilityZones: ["us-east-1a"],
desiredCapacity: 1,
maxSize: 5,
minSize: 1,
warmPool: {
instanceReusePolicy: {
reuseOnScaleIn: true,
},
maxGroupPreparedCapacity: 10,
minSize: 1,
poolState: "Hibernated",
},
});
const awsLaunchTemplateExample = new aws.launchTemplate.LaunchTemplate(
this,
"example_1",
{
imageId: "${data.aws_ami.example.id}",
instanceType: "c5.large",
namePrefix: "example",
}
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsLaunchTemplateExample.overrideLogicalId("example");
Argument Reference
The following arguments are supported:
name
- (Optional) Name of the Auto Scaling Group. By default generated by Terraform. Conflicts withnamePrefix
.namePrefix
- (Optional) Creates a unique name beginning with the specified prefix. Conflicts withname
.maxSize
- (Required) Maximum size of the Auto Scaling Group.minSize
- (Required) Minimum size of the Auto Scaling Group. (See also Waiting for Capacity below.)availabilityZones
- (Optional) 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 withvpcZoneIdentifier
argument. Conflicts withvpcZoneIdentifier
.capacityRebalance
- (Optional) Whether capacity rebalance is enabled. Otherwise, capacity rebalance is disabled.context
- (Optional) Reserved.defaultCooldown
- (Optional) Amount of time, in seconds, after a scaling activity completes before another scaling activity can start.defaultInstanceWarmup
- (Optional) Amount of time, in seconds, until a newly launched instance can contribute to the Amazon CloudWatch metrics. This delay lets an instance finish initializing before Amazon EC2 Auto Scaling aggregates instance metrics, resulting in more reliable usage data. Set this value equal to the amount of time that it takes for resource consumption to become stable after an instance reaches the InService state. (See Set the default instance warmup for an Auto Scaling group)launchConfiguration
- (Optional) Name of the launch configuration to use.launchTemplate
- (Optional) Nested argument with Launch template specification to use to launch instances. See Launch Template below for more details.mixedInstancesPolicy
(Optional) Configuration block containing settings to define launch targets for Auto Scaling groups. See Mixed Instances Policy below for more details.initialLifecycleHook
- (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 separateawsAutoscalingLifecycleHook
resource, without theautoscalingGroupName
attribute. Please note that this will only work when creating a new Auto Scaling Group. For all other use-cases, please useawsAutoscalingLifecycleHook
resource.healthCheckGracePeriod
- (Optional, Default: 300) Time (in seconds) after instance comes into service before checking health.healthCheckType
- (Optional) "EC2" or "ELB". Controls how health checking is done.desiredCapacity
- (Optional) Number of Amazon EC2 instances that should be running in the group. (See also Waiting for Capacity below.)desiredCapacityType
- (Optional) The unit of measurement for the value specified fordesiredCapacity
. Supported for attribute-based instance type selection only. Valid values:"units"
,"vcpu"
,"memoryMib"
.forceDelete
- (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.loadBalancers
(Optional) List of elastic load balancer names to add to the autoscaling group names. Only valid for classic load balancers. For ALBs, usetargetGroupArns
instead.vpcZoneIdentifier
(Optional) List of subnet IDs to launch resources in. Subnets automatically determine which availability zones the group will reside. Conflicts withavailabilityZones
.targetGroupArns
(Optional) Set ofawsAlbTargetGroup
ARNs, for use with Application or Network Load Balancing.terminationPolicies
(Optional) 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
. Additionally, the ARN of a Lambda function can be specified for custom termination policies.suspendedProcesses
- (Optional) List of processes to suspend for the Auto Scaling Group. The allowed values arelaunch
,terminate
,healthCheck
,replaceUnhealthy
,azRebalance
,alarmNotification
,scheduledActions
,addToLoadBalancer
,instanceRefresh
. 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, Deprecated usetag
instead) Set of maps containing resource tags. Conflicts withtag
. See Tags below for more details.placementGroup
(Optional) Name of the placement group into which you'll launch your instances, if any.metricsGranularity
- (Optional) Granularity to associate with the metrics to collect. The only valid value is1Minute
. Default is1Minute
.enabledMetrics
- (Optional) List of metrics to collect. The allowed values are defined by the underlying AWS API.waitForCapacityTimeout
(Default: "10m") 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.minElbCapacity
- (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.)waitForElbCapacity
- (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 overminElbCapacity
behavior.) (See also Waiting for Capacity below.)protectFromScaleIn
(Optional) Whether newly launched instances are automatically protected from termination by Amazon EC2 Auto Scaling when scaling in. For more information about preventing instances from terminating on scale in, see Using instance scale-in protection in the Amazon EC2 Auto Scaling User Guide.serviceLinkedRoleArn
(Optional) ARN of the service-linked role that the ASG will use to call other AWS servicesmaxInstanceLifetime
(Optional) 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.instanceRefresh
- (Optional) If this block is configured, start an Instance Refresh when this Auto Scaling Group is updated. Defined below.warmPool
- (Optional) If this block is configured, add a Warm Pool to the specified Auto Scaling group. Defined below
launchTemplate
\~> NOTE: Either id
or name
must be specified.
The top-level launchTemplate
block supports the following:
id
- (Optional) ID of the launch template. Conflicts withname
.name
- (Optional) Name of the launch template. Conflicts withid
.version
- (Optional) Template version. Can be version number,$latest
, or$default
. (Default:$default
).
mixedInstancesPolicy
instancesDistribution
- (Optional) Nested argument containing settings on how to mix on-demand and Spot instances in the Auto Scaling group. Defined below.launchTemplate
- (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:
onDemandAllocationStrategy
- (Optional) Strategy to use when launching on-demand instances. Valid values:prioritized
,lowestPrice
. Default:prioritized
.onDemandBaseCapacity
- (Optional) Absolute minimum amount of desired capacity that must be fulfilled by on-demand instances. Default:0
.onDemandPercentageAboveBaseCapacity
- (Optional) Percentage split between on-demand and Spot instances above the base on-demand capacity. Default:100
.spotAllocationStrategy
- (Optional) How to allocate capacity across the Spot pools. Valid values:lowestPrice
,capacityOptimized
,capacityOptimizedPrioritized
, andpriceCapacityOptimized
. Default:lowestPrice
.spotInstancePools
- (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. Only available withspotAllocationStrategy
set tolowestPrice
. Otherwise it must be set to0
, if it has been defined before. Default:2
.spotMaxPrice
- (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:
launchTemplateSpecification
- (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 launchTemplateId
or launchTemplateName
must be specified.
This configuration block supports the following:
launchTemplateId
- (Optional) ID of the launch template. Conflicts withlaunchTemplateName
.launchTemplateName
- (Optional) Name of the launch template. Conflicts withlaunchTemplateId
.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:
instanceType
- (Optional) Override the instance type in the Launch Template.instanceRequirements
- (Optional) Override the instance type in the Launch Template with instance types that satisfy the requirements.launchTemplateSpecification
- (Optional) Override the instance launch template specification in the Launch Template.weightedCapacity
- (Optional) Number of capacity units, which gives the instance type a proportional weight to other instance types.
mixed_instances_policy launch_template override instance_requirements
This configuration block supports the following:
\~> NOTE: Both memoryMibMin
and vcpuCountMin
must be specified.
-
acceleratorCount
- (Optional) Block describing the minimum and maximum number of accelerators (GPUs, FPGAs, or AWS Inferentia chips). Default is no minimum or maximum.min
- (Optional) Minimum.max
- (Optional) Maximum. Set to0
to exclude instance types with accelerators.
-
acceleratorManufacturers
- (Optional) List of accelerator manufacturer names. Default is any manufacturer. -
acceleratorNames
- (Optional) List of accelerator names. Default is any acclerator. -
acceleratorTotalMemoryMib
- (Optional) Block describing the minimum and maximum total memory of the accelerators. Default is no minimum or maximum.min
- (Optional) Minimum.max
- (Optional) Maximum.
-
acceleratorTypes
- (Optional) List of accelerator types. Default is any accelerator type. -
allowedInstanceTypes
- (Optional) List of instance types to apply your specified attributes against. All other instance types are ignored, even if they match your specified attributes. You can use strings with one or more wild cards, represented by an asterisk (*), to allow an instance type, size, or generation. The following are examples:m58Xlarge
,c5*.*
,m5A.*
,r*
,*3*
. For example, if you specifyc5*
, you are allowing the entire C5 instance family, which includes all C5a and C5n instance types. If you specifym5A.*
, you are allowing all the M5a instance types, but not the M5n instance types. Maximum of 400 entries in the list; each entry is limited to 30 characters. Default is all instance types.\~> NOTE: If you specify
allowedInstanceTypes
, you can't specifyexcludedInstanceTypes
. -
bareMetal
- (Optional) Indicate whether bare metal instace types should beincluded
,excluded
, orrequired
. Default isexcluded
. -
baselineEbsBandwidthMbps
- (Optional) Block describing the minimum and maximum baseline EBS bandwidth, in Mbps. Default is no minimum or maximum.min
- (Optional) Minimum.max
- (Optional) Maximum.
-
burstablePerformance
- (Optional) Indicate whether burstable performance instance types should beincluded
,excluded
, orrequired
. Default isexcluded
. -
cpuManufacturers
(Optional) List of CPU manufacturer names. Default is any manufacturer.\~> NOTE: Don't confuse the CPU hardware manufacturer with the CPU hardware architecture. Instances will be launched with a compatible CPU architecture based on the Amazon Machine Image (AMI) that you specify in your launch template.
-
excludedInstanceTypes
- (Optional) List of instance types to exclude. You can use strings with one or more wild cards, represented by an asterisk (*), to exclude an instance type, size, or generation. The following are examples:m58Xlarge
,c5*.*
,m5A.*
,r*
,*3*
. For example, if you specifyc5*
, you are excluding the entire C5 instance family, which includes all C5a and C5n instance types. If you specifym5A.*
, you are excluding all the M5a instance types, but not the M5n instance types. Maximum of 400 entries in the list; each entry is limited to 30 characters. Default is no excluded instance types.\~> NOTE: If you specify
excludedInstanceTypes
, you can't specifyallowedInstanceTypes
. -
instanceGenerations
- (Optional) List of instance generation names. Default is any generation. -
localStorage
- (Optional) Indicate whether instance types with local storage volumes areincluded
,excluded
, orrequired
. Default isincluded
. -
localStorageTypes
- (Optional) List of local storage type names. Default any storage type. -
memoryGibPerVcpu
- (Optional) Block describing the minimum and maximum amount of memory (GiB) per vCPU. Default is no minimum or maximum.min
- (Optional) Minimum. May be a decimal number, e.g.05
.max
- (Optional) Maximum. May be a decimal number, e.g.05
.
-
memoryMib
- (Required) Block describing the minimum and maximum amount of memory (MiB). Default is no maximum.min
- (Required) Minimum.max
- (Optional) Maximum.
-
networkBandwidthGbps
- (Optional) Block describing the minimum and maximum amount of network bandwidth, in gigabits per second (Gbps). Default is no minimum or maximum.min
- (Optional) Minimum.max
- (Optional) Maximum.
-
networkInterfaceCount
- (Optional) Block describing the minimum and maximum number of network interfaces. Default is no minimum or maximum.min
- (Optional) Minimum.max
- (Optional) Maximum.
-
onDemandMaxPricePercentageOverLowestPrice
- (Optional) Price protection threshold for On-Demand Instances. This is the maximum you’ll pay for an On-Demand Instance, expressed as a percentage higher than the cheapest M, C, or R instance type with your specified attributes. When Amazon EC2 Auto Scaling selects instance types with your attributes, we will exclude instance types whose price is higher than your threshold. The parameter accepts an integer, which Amazon EC2 Auto Scaling interprets as a percentage. To turn off price protection, specify a high value, such as 999999. Default is 20.If you set DesiredCapacityType to vcpu or memory-mib, the price protection threshold is applied based on the per vCPU or per memory price instead of the per instance price.
-
requireHibernateSupport
- (Optional) Indicate whether instance types must support On-Demand Instance Hibernation, eithertrue
orfalse
. Default isfalse
. -
spotMaxPricePercentageOverLowestPrice
- (Optional) Price protection threshold for Spot Instances. This is the maximum you’ll pay for a Spot Instance, expressed as a percentage higher than the cheapest M, C, or R instance type with your specified attributes. When Amazon EC2 Auto Scaling selects instance types with your attributes, we will exclude instance types whose price is higher than your threshold. The parameter accepts an integer, which Amazon EC2 Auto Scaling interprets as a percentage. To turn off price protection, specify a high value, such as 999999. Default is 100.If you set DesiredCapacityType to vcpu or memory-mib, the price protection threshold is applied based on the per vCPU or per memory price instead of the per instance price.
-
totalLocalStorageGb
- (Optional) Block describing the minimum and maximum total local storage (GB). Default is no minimum or maximum.min
- (Optional) Minimum. May be a decimal number, e.g.05
.max
- (Optional) Maximum. May be a decimal number, e.g.05
.
-
vcpuCount
- (Required) Block describing the minimum and maximum number of vCPUs. Default is no maximum.min
- (Required) Minimum.max
- (Optional) Maximum.
tag and tags
The tag
attribute accepts exactly one tag declaration with the following fields:
key
- (Required) Keyvalue
- (Required) ValuepropagateAtLaunch
- (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 the minSize
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.
instanceRefresh
This configuration block supports the following:
strategy
- (Required) 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.checkpointDelay
- (Optional) Number of seconds to wait after a checkpoint. Defaults to3600
.checkpointPercentages
- (Optional) List of percentages for each checkpoint. Values must be unique and in ascending order. To replace all instances, the final number must be100
.instanceWarmup
- (Optional) 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.minHealthyPercentage
- (Optional) 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
.skipMatching
- (Optional) Replace instances that already have your desired configuration. Defaults tofalse
.autoRollback
- (Optional) Automatically rollback if instance refresh fails. Defaults tofalse
.triggers
- (Optional) Set of additional property names that will trigger an Instance Refresh. A refresh will always be triggered by a change in any oflaunchConfiguration
,launchTemplate
, ormixedInstancesPolicy
.
\~> NOTE: A refresh is started when any of the following Auto Scaling Group properties change: launchConfiguration
, launchTemplate
, mixedInstancesPolicy
. Additional properties can be specified in the triggers
property of instanceRefresh
.
\~> NOTE: A refresh will not start when version = "$latest"
is configured in the launchTemplate
block. To trigger the instance refresh when a launch template is changed, configure version
to use the latestVersion
attribute of the awsLaunchTemplate
resource.
\~> 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.
warmPool
This configuration block supports the following:
poolState
- (Optional) Sets the instance state to transition to after the lifecycle hooks finish. Valid values are: Stopped (default), Running or Hibernated.minSize
- (Optional) 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.instanceReusePolicy
- (Optional) Whether instances in the Auto Scaling group can be returned to the warm pool on scale in. The default is to terminate instances in the Auto Scaling group when the group scales in.maxGroupPreparedCapacity
- (Optional) 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.
instanceReusePolicy
This configuration block supports the following:
reuseOnScaleIn
- (Optional) Whether instances in the Auto Scaling group can be returned to the warm pool on scale in.
Attributes Reference
In addition to all arguments above, the following attributes are exported:
id
- Auto Scaling Group id.arn
- ARN for this Auto Scaling GroupavailabilityZones
- Availability zones of the Auto Scaling Group.minSize
- Minimum size of the Auto Scaling GroupmaxSize
- Maximum size of the Auto Scaling GroupdefaultCooldown
- Time between a scaling activity and the succeeding scaling activity.defaultInstanceWarmup
- The duration of the default instance warmup, in seconds.name
- Name of the Auto Scaling GrouphealthCheckGracePeriod
- Time after instance comes into service before checking health.healthCheckType
- "EC2" or "ELB". Controls how health checking is done.desiredCapacity
-The number of Amazon EC2 instances that should be running in the group.launchConfiguration
- The launch configuration of the Auto Scaling GroupvpcZoneIdentifier
(Optional) - The VPC zone identifier
\~> NOTE: When using elb
as the healthCheckType
, healthCheckGracePeriod
is required.
\~> NOTE: Terraform has two types of ways you can add lifecycle hooks - via the initialLifecycleHook
attribute from this resource, or via the separate awsAutoscalingLifecycleHook
resource. initialLifecycleHook
exists here because any lifecycle hooks added with awsAutoscalingLifecycleHook
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 with initialLifecycleHook
here, but take care to not duplicate these hooks in awsAutoscalingLifecycleHook
.
Timeouts
delete
- (Default10M
)
Waiting for Capacity
A newly-created ASG is initially empty and begins to scale to minSize
(or desiredCapacity
, if specified) by launching instances using the provided Launch Configuration. These instances take time to launch and boot.
On ASG Update, changes to these values also take time to result in the target number of instances providing service.
Terraform provides two mechanisms to help consistently manage ASG scale up time across dependent resources.
Waiting for ASG Capacity
The first is default behavior. Terraform waits after ASG creation for minSize
(or desiredCapacity
, if specified) healthy instances to show up in the ASG before continuing.
If minSize
or desiredCapacity
are changed in a subsequent update, Terraform will also wait for the correct number of healthy instances before continuing.
Terraform considers an instance "healthy" when the ASG reports healthStatus: "healthy"
and lifecycleState: "inService"
. See the AWS AutoScaling Docs for more information on an ASG's lifecycle.
Terraform will wait for healthy instances for up to waitForCapacityTimeout
. If ASG creation is taking more than a few minutes, it's worth investigating for scaling activity errors, which can be caused by problems with the selected Launch Configuration.
Setting waitForCapacityTimeout
to "0"
disables ASG Capacity waiting.
Waiting for ELB Capacity
The second mechanism is optional, and affects ASGs with attached ELBs specified via the loadBalancers
attribute or with ALBs specified with targetGroupArns
.
The minElbCapacity
parameter causes Terraform to wait for at least the requested number of instances to show up "inService"
in all attached ELBs during ASG creation. It has no effect on ASG updates.
If waitForElbCapacity
is set, Terraform will wait for exactly that number of Instances to be "inService"
in all attached ELBs on both creation and updates.
These parameters can be used to ensure that service is being provided before Terraform moves on. If new instances don't pass the ELB's health checks for any reason, the Terraform apply will time out, and the ASG will be marked as tainted (i.e., marked to be destroyed in a follow up run).
As with ASG Capacity, Terraform will wait for up to waitForCapacityTimeout
for the proper number of instances to be healthy.
Troubleshooting Capacity Waiting Timeouts
If ASG creation takes more than a few minutes, this could indicate one of a number of configuration problems. See the AWS Docs on Load Balancer Troubleshooting for more information.
Import
Auto Scaling Groups can be imported using the name
, e.g.,