Home

Awesome

AWS Auto Scaling Group (ASG) Terraform module

Terraform module which creates Auto Scaling resources on AWS.

SWUbanner

Available Features

Usage

module "asg" {
  source  = "terraform-aws-modules/autoscaling/aws"

  # Autoscaling group
  name = "example-asg"

  min_size                  = 0
  max_size                  = 1
  desired_capacity          = 1
  wait_for_capacity_timeout = 0
  health_check_type         = "EC2"
  vpc_zone_identifier       = ["subnet-1235678", "subnet-87654321"]

  initial_lifecycle_hooks = [
    {
      name                  = "ExampleStartupLifeCycleHook"
      default_result        = "CONTINUE"
      heartbeat_timeout     = 60
      lifecycle_transition  = "autoscaling:EC2_INSTANCE_LAUNCHING"
      notification_metadata = jsonencode({ "hello" = "world" })
    },
    {
      name                  = "ExampleTerminationLifeCycleHook"
      default_result        = "CONTINUE"
      heartbeat_timeout     = 180
      lifecycle_transition  = "autoscaling:EC2_INSTANCE_TERMINATING"
      notification_metadata = jsonencode({ "goodbye" = "world" })
    }
  ]

  instance_refresh = {
    strategy = "Rolling"
    preferences = {
      checkpoint_delay       = 600
      checkpoint_percentages = [35, 70, 100]
      instance_warmup        = 300
      min_healthy_percentage = 50
      max_healthy_percentage = 100
    }
    triggers = ["tag"]
  }

  # Launch template
  launch_template_name        = "example-asg"
  launch_template_description = "Launch template example"
  update_default_version      = true

  image_id          = "ami-ebd02392"
  instance_type     = "t3.micro"
  ebs_optimized     = true
  enable_monitoring = true

  # IAM role & instance profile
  create_iam_instance_profile = true
  iam_role_name               = "example-asg"
  iam_role_path               = "/ec2/"
  iam_role_description        = "IAM role example"
  iam_role_tags = {
    CustomIamRole = "Yes"
  }
  iam_role_policies = {
    AmazonSSMManagedInstanceCore = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
  }

  block_device_mappings = [
    {
      # Root volume
      device_name = "/dev/xvda"
      no_device   = 0
      ebs = {
        delete_on_termination = true
        encrypted             = true
        volume_size           = 20
        volume_type           = "gp2"
      }
    }, {
      device_name = "/dev/sda1"
      no_device   = 1
      ebs = {
        delete_on_termination = true
        encrypted             = true
        volume_size           = 30
        volume_type           = "gp2"
      }
    }
  ]

  capacity_reservation_specification = {
    capacity_reservation_preference = "open"
  }

  cpu_options = {
    core_count       = 1
    threads_per_core = 1
  }

  credit_specification = {
    cpu_credits = "standard"
  }

  instance_market_options = {
    market_type = "spot"
    spot_options = {
      block_duration_minutes = 60
    }
  }

  # This will ensure imdsv2 is enabled, required, and a single hop which is aws security
  # best practices
  # See https://docs.aws.amazon.com/securityhub/latest/userguide/autoscaling-controls.html#autoscaling-4
  metadata_options = {
    http_endpoint               = "enabled"
    http_tokens                 = "required"
    http_put_response_hop_limit = 1
  }

  network_interfaces = [
    {
      delete_on_termination = true
      description           = "eth0"
      device_index          = 0
      security_groups       = ["sg-12345678"]
    },
    {
      delete_on_termination = true
      description           = "eth1"
      device_index          = 1
      security_groups       = ["sg-12345678"]
    }
  ]

  placement = {
    availability_zone = "us-west-1b"
  }

  tag_specifications = [
    {
      resource_type = "instance"
      tags          = { WhatAmI = "Instance" }
    },
    {
      resource_type = "volume"
      tags          = { WhatAmI = "Volume" }
    },
    {
      resource_type = "spot-instances-request"
      tags          = { WhatAmI = "SpotInstanceRequest" }
    }
  ]

  tags = {
    Environment = "dev"
    Project     = "megasecret"
  }
}

Conditional creation

The following combinations are supported to conditionally create resources and/or use externally created resources within the module:

Note: the default behavior of the module is to create an autoscaling group and launch template.

  create                 = false
  create_launch_template = false
  create = false
  create_launch_template = false
  launch_template        = aws_launch_template.my_launch_template.name
  use_mixed_instances_policy = true
  scaling_policies = {
    my-policy = {
      policy_type               = "TargetTrackingScaling"
      target_tracking_configuration = {
        predefined_metric_specification = {
          predefined_metric_type = "ASGAverageCPUUtilization"
          resource_label         = "MyLabel"
        }
        target_value = 50.0
      }
    }
  }

Examples

<!-- BEGIN_TF_DOCS -->

Requirements

NameVersion
<a name="requirement_terraform"></a> terraform>= 1.3
<a name="requirement_aws"></a> aws>= 5.82.1

Providers

NameVersion
<a name="provider_aws"></a> aws>= 5.82.1

Modules

No modules.

Resources

NameType
aws_autoscaling_group.idcresource
aws_autoscaling_group.thisresource
aws_autoscaling_policy.thisresource
aws_autoscaling_schedule.thisresource
aws_autoscaling_traffic_source_attachment.thisresource
aws_iam_instance_profile.thisresource
aws_iam_role.thisresource
aws_iam_role_policy_attachment.thisresource
aws_launch_template.thisresource
aws_iam_policy_document.assume_role_policydata source
aws_partition.currentdata source

Inputs

NameDescriptionTypeDefaultRequired
<a name="input_autoscaling_group_tags"></a> autoscaling_group_tagsA map of additional tags to add to the autoscaling groupmap(string){}no
<a name="input_availability_zone_distribution"></a> availability_zone_distributionA map of configuration for capacity distribution across availability zonesany{}no
<a name="input_availability_zones"></a> availability_zonesA list of one or more availability zones for the group. Used for EC2-Classic and default subnets when not specified with vpc_zone_identifier argument. Conflicts with vpc_zone_identifierlist(string)nullno
<a name="input_block_device_mappings"></a> block_device_mappingsSpecify volumes to attach to the instance besides the volumes specified by the AMIlist(any)[]no
<a name="input_capacity_rebalance"></a> capacity_rebalanceIndicates whether capacity rebalance is enabledboolnullno
<a name="input_capacity_reservation_specification"></a> capacity_reservation_specificationTargeting for EC2 capacity reservationsany{}no
<a name="input_cpu_options"></a> cpu_optionsThe CPU options for the instancemap(string){}no
<a name="input_create"></a> createDetermines whether to create autoscaling group or notbooltrueno
<a name="input_create_iam_instance_profile"></a> create_iam_instance_profileDetermines whether an IAM instance profile is created or to use an existing IAM instance profileboolfalseno
<a name="input_create_launch_template"></a> create_launch_templateDetermines whether to create launch template or notbooltrueno
<a name="input_create_scaling_policy"></a> create_scaling_policyDetermines whether to create target scaling policy schedule or notbooltrueno
<a name="input_create_schedule"></a> create_scheduleDetermines whether to create autoscaling group schedule or notbooltrueno
<a name="input_credit_specification"></a> credit_specificationCustomize the credit specification of the instancemap(string){}no
<a name="input_default_cooldown"></a> default_cooldownThe amount of time, in seconds, after a scaling activity completes before another scaling activity can startnumbernullno
<a name="input_default_instance_warmup"></a> default_instance_warmupAmount 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.numbernullno
<a name="input_default_version"></a> default_versionDefault Version of the launch templatestringnullno
<a name="input_delete_timeout"></a> delete_timeoutDelete timeout to wait for destroying autoscaling groupstringnullno
<a name="input_desired_capacity"></a> desired_capacityThe number of Amazon EC2 instances that should be running in the autoscaling groupnumbernullno
<a name="input_desired_capacity_type"></a> desired_capacity_typeThe unit of measurement for the value specified for desired_capacity. Supported for attribute-based instance type selection only. Valid values: units, vcpu, memory-mib.stringnullno
<a name="input_disable_api_stop"></a> disable_api_stopIf true, enables EC2 instance stop protectionboolnullno
<a name="input_disable_api_termination"></a> disable_api_terminationIf true, enables EC2 instance termination protectionboolnullno
<a name="input_ebs_optimized"></a> ebs_optimizedIf true, the launched EC2 instance will be EBS-optimizedboolnullno
<a name="input_elastic_gpu_specifications"></a> elastic_gpu_specificationsThe elastic GPU to attach to the instancemap(string){}no
<a name="input_elastic_inference_accelerator"></a> elastic_inference_acceleratorConfiguration block containing an Elastic Inference Accelerator to attach to the instancemap(string){}no
<a name="input_enable_monitoring"></a> enable_monitoringEnables/disables detailed monitoringbooltrueno
<a name="input_enabled_metrics"></a> enabled_metricsA list of metrics to collect. The allowed values are GroupDesiredCapacity, GroupInServiceCapacity, GroupPendingCapacity, GroupMinSize, GroupMaxSize, GroupInServiceInstances, GroupPendingInstances, GroupStandbyInstances, GroupStandbyCapacity, GroupTerminatingCapacity, GroupTerminatingInstances, GroupTotalCapacity, GroupTotalInstanceslist(string)[]no
<a name="input_enclave_options"></a> enclave_optionsEnable Nitro Enclaves on launched instancesmap(string){}no
<a name="input_force_delete"></a> force_deleteAllows 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 danglingboolnullno
<a name="input_health_check_grace_period"></a> health_check_grace_periodTime (in seconds) after instance comes into service before checking healthnumbernullno
<a name="input_health_check_type"></a> health_check_typeEC2 or ELB. Controls how health checking is donestringnullno
<a name="input_hibernation_options"></a> hibernation_optionsThe hibernation options for the instancemap(string){}no
<a name="input_iam_instance_profile_arn"></a> iam_instance_profile_arnAmazon Resource Name (ARN) of an existing IAM instance profile. Used when create_iam_instance_profile = falsestringnullno
<a name="input_iam_instance_profile_name"></a> iam_instance_profile_nameThe name of the IAM instance profile to be created (create_iam_instance_profile = true) or existing (create_iam_instance_profile = false)stringnullno
<a name="input_iam_role_description"></a> iam_role_descriptionDescription of the rolestringnullno
<a name="input_iam_role_name"></a> iam_role_nameName to use on IAM role createdstringnullno
<a name="input_iam_role_path"></a> iam_role_pathIAM role pathstringnullno
<a name="input_iam_role_permissions_boundary"></a> iam_role_permissions_boundaryARN of the policy that is used to set the permissions boundary for the IAM rolestringnullno
<a name="input_iam_role_policies"></a> iam_role_policiesIAM policies to attach to the IAM rolemap(string){}no
<a name="input_iam_role_tags"></a> iam_role_tagsA map of additional tags to add to the IAM role createdmap(string){}no
<a name="input_iam_role_use_name_prefix"></a> iam_role_use_name_prefixDetermines whether the IAM role name (iam_role_name) is used as a prefixbooltrueno
<a name="input_ignore_desired_capacity_changes"></a> ignore_desired_capacity_changesDetermines whether the desired_capacity value is ignored after initial apply. See README note for more detailsboolfalseno
<a name="input_ignore_failed_scaling_activities"></a> ignore_failed_scaling_activitiesWhether to ignore failed Auto Scaling scaling activities while waiting for capacity. The default is false -- failed scaling activities cause errors to be returned.boolfalseno
<a name="input_image_id"></a> image_idThe AMI from which to launch the instancestring""no
<a name="input_initial_lifecycle_hooks"></a> initial_lifecycle_hooksOne or more Lifecycle Hooks to attach to the Auto Scaling Group before instances are launched. The syntax is exactly the same as the separate aws_autoscaling_lifecycle_hook resource, without the autoscaling_group_name attribute. Please note that this will only work when creating a new Auto Scaling Group. For all other use-cases, please use aws_autoscaling_lifecycle_hook resourcelist(map(string))[]no
<a name="input_instance_initiated_shutdown_behavior"></a> instance_initiated_shutdown_behaviorShutdown behavior for the instance. Can be stop or terminate. (Default: stop)stringnullno
<a name="input_instance_maintenance_policy"></a> instance_maintenance_policyIf this block is configured, add a instance maintenance policy to the specified Auto Scaling groupmap(any){}no
<a name="input_instance_market_options"></a> instance_market_optionsThe market (purchasing) option for the instanceany{}no
<a name="input_instance_name"></a> instance_nameName that is propogated to launched EC2 instances via a tag - if not provided, defaults to var.namestring""no
<a name="input_instance_refresh"></a> instance_refreshIf this block is configured, start an Instance Refresh when this Auto Scaling Group is updatedany{}no
<a name="input_instance_requirements"></a> instance_requirementsThe attribute requirements for the type of instance. If present then instance_type cannot be presentany{}no
<a name="input_instance_type"></a> instance_typeThe type of the instance. If present then instance_requirements cannot be presentstringnullno
<a name="input_kernel_id"></a> kernel_idThe kernel IDstringnullno
<a name="input_key_name"></a> key_nameThe key name that should be used for the instancestringnullno
<a name="input_launch_template_description"></a> launch_template_descriptionDescription of the launch templatestringnullno
<a name="input_launch_template_id"></a> launch_template_idID of an existing launch template to be used (created outside of this module)stringnullno
<a name="input_launch_template_name"></a> launch_template_nameName of launch template to be createdstring""no
<a name="input_launch_template_use_name_prefix"></a> launch_template_use_name_prefixDetermines whether to use launch_template_name as is or create a unique name beginning with the launch_template_name as the prefixbooltrueno
<a name="input_launch_template_version"></a> launch_template_versionLaunch template version. Can be version number, $Latest, or $Defaultstringnullno
<a name="input_license_specifications"></a> license_specificationsA list of license specifications to associate withmap(string){}no
<a name="input_maintenance_options"></a> maintenance_optionsThe maintenance options for the instanceany{}no
<a name="input_max_instance_lifetime"></a> max_instance_lifetimeThe 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 secondsnumbernullno
<a name="input_max_size"></a> max_sizeThe maximum size of the autoscaling groupnumbernullno
<a name="input_metadata_options"></a> metadata_optionsCustomize the metadata options for the instancemap(string){}no
<a name="input_metrics_granularity"></a> metrics_granularityThe granularity to associate with the metrics to collect. The only valid value is 1Minutestringnullno
<a name="input_min_elb_capacity"></a> min_elb_capacitySetting this causes Terraform to wait for this number of instances to show up healthy in the ELB only on creation. Updates will not wait on ELB instance number changesnumbernullno
<a name="input_min_size"></a> min_sizeThe minimum size of the autoscaling groupnumbernullno
<a name="input_mixed_instances_policy"></a> mixed_instances_policyConfiguration block containing settings to define launch targets for Auto Scaling groupsanynullno
<a name="input_name"></a> nameName used across the resources createdstringn/ayes
<a name="input_network_interfaces"></a> network_interfacesCustomize network interfaces to be attached at instance boot timelist(any)[]no
<a name="input_placement"></a> placementThe placement of the instancemap(string){}no
<a name="input_placement_group"></a> placement_groupThe name of the placement group into which you'll launch your instances, if anystringnullno
<a name="input_private_dns_name_options"></a> private_dns_name_optionsThe options for the instance hostname. The default values are inherited from the subnetmap(string){}no
<a name="input_protect_from_scale_in"></a> protect_from_scale_inAllows setting instance protection. The autoscaling group will not select instances with this setting for termination during scale in events.boolfalseno
<a name="input_putin_khuylo"></a> putin_khuyloDo you agree that Putin doesn't respect Ukrainian sovereignty and territorial integrity? More info: https://en.wikipedia.org/wiki/Putin_khuylo!booltrueno
<a name="input_ram_disk_id"></a> ram_disk_idThe ID of the ram diskstringnullno
<a name="input_scaling_policies"></a> scaling_policiesMap of target scaling policy schedule to createany{}no
<a name="input_schedules"></a> schedulesMap of autoscaling group schedule to createmap(any){}no
<a name="input_security_groups"></a> security_groupsA list of security group IDs to associatelist(string)[]no
<a name="input_service_linked_role_arn"></a> service_linked_role_arnThe ARN of the service-linked role that the ASG will use to call other AWS servicesstringnullno
<a name="input_suspended_processes"></a> suspended_processesA list of processes to suspend for the Auto Scaling Group. The allowed values are Launch, Terminate, HealthCheck, ReplaceUnhealthy, AZRebalance, AlarmNotification, ScheduledActions, AddToLoadBalancer, InstanceRefresh. Note that if you suspend either the Launch or Terminate process types, it can prevent your Auto Scaling Group from functioning properlylist(string)[]no
<a name="input_tag_specifications"></a> tag_specificationsThe tags to apply to the resources during launchlist(any)[]no
<a name="input_tags"></a> tagsA map of tags to assign to resourcesmap(string){}no
<a name="input_termination_policies"></a> termination_policiesA list of policies to decide how the instances in the Auto Scaling Group should be terminated. The allowed values are OldestInstance, NewestInstance, OldestLaunchConfiguration, ClosestToNextInstanceHour, OldestLaunchTemplate, AllocationStrategy, Defaultlist(string)[]no
<a name="input_traffic_source_attachments"></a> traffic_source_attachmentsMap of traffic source attachment definitions to createany{}no
<a name="input_update_default_version"></a> update_default_versionWhether to update Default Version each update. Conflicts with default_versionboolnullno
<a name="input_use_mixed_instances_policy"></a> use_mixed_instances_policyDetermines whether to use a mixed instances policy in the autoscaling group or notboolfalseno
<a name="input_use_name_prefix"></a> use_name_prefixDetermines whether to use name as is or create a unique name beginning with the name as the prefixbooltrueno
<a name="input_user_data"></a> user_dataThe Base64-encoded user data to provide when launching the instancestringnullno
<a name="input_vpc_zone_identifier"></a> vpc_zone_identifierA list of subnet IDs to launch resources in. Subnets automatically determine which availability zones the group will reside. Conflicts with availability_zoneslist(string)nullno
<a name="input_wait_for_capacity_timeout"></a> wait_for_capacity_timeoutA 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.stringnullno
<a name="input_wait_for_elb_capacity"></a> wait_for_elb_capacitySetting this will cause Terraform to wait for exactly this number of healthy instances in all attached load balancers on both create and update operations. Takes precedence over min_elb_capacity behavior.numbernullno
<a name="input_warm_pool"></a> warm_poolIf this block is configured, add a Warm Pool to the specified Auto Scaling groupany{}no

Outputs

NameDescription
<a name="output_autoscaling_group_arn"></a> autoscaling_group_arnThe ARN for this AutoScaling Group
<a name="output_autoscaling_group_availability_zones"></a> autoscaling_group_availability_zonesThe availability zones of the autoscale group
<a name="output_autoscaling_group_default_cooldown"></a> autoscaling_group_default_cooldownTime between a scaling activity and the succeeding scaling activity
<a name="output_autoscaling_group_desired_capacity"></a> autoscaling_group_desired_capacityThe number of Amazon EC2 instances that should be running in the group
<a name="output_autoscaling_group_enabled_metrics"></a> autoscaling_group_enabled_metricsList of metrics enabled for collection
<a name="output_autoscaling_group_health_check_grace_period"></a> autoscaling_group_health_check_grace_periodTime after instance comes into service before checking health
<a name="output_autoscaling_group_health_check_type"></a> autoscaling_group_health_check_typeEC2 or ELB. Controls how health checking is done
<a name="output_autoscaling_group_id"></a> autoscaling_group_idThe autoscaling group id
<a name="output_autoscaling_group_load_balancers"></a> autoscaling_group_load_balancersThe load balancer names associated with the autoscaling group
<a name="output_autoscaling_group_max_size"></a> autoscaling_group_max_sizeThe maximum size of the autoscale group
<a name="output_autoscaling_group_min_size"></a> autoscaling_group_min_sizeThe minimum size of the autoscale group
<a name="output_autoscaling_group_name"></a> autoscaling_group_nameThe autoscaling group name
<a name="output_autoscaling_group_target_group_arns"></a> autoscaling_group_target_group_arnsList of Target Group ARNs that apply to this AutoScaling Group
<a name="output_autoscaling_group_vpc_zone_identifier"></a> autoscaling_group_vpc_zone_identifierThe VPC zone identifier
<a name="output_autoscaling_policy_arns"></a> autoscaling_policy_arnsARNs of autoscaling policies
<a name="output_autoscaling_schedule_arns"></a> autoscaling_schedule_arnsARNs of autoscaling group schedules
<a name="output_iam_instance_profile_arn"></a> iam_instance_profile_arnARN assigned by AWS to the instance profile
<a name="output_iam_instance_profile_id"></a> iam_instance_profile_idInstance profile's ID
<a name="output_iam_instance_profile_unique"></a> iam_instance_profile_uniqueStable and unique string identifying the IAM instance profile
<a name="output_iam_role_arn"></a> iam_role_arnThe Amazon Resource Name (ARN) specifying the IAM role
<a name="output_iam_role_name"></a> iam_role_nameThe name of the IAM role
<a name="output_iam_role_unique_id"></a> iam_role_unique_idStable and unique string identifying the IAM role
<a name="output_launch_template_arn"></a> launch_template_arnThe ARN of the launch template
<a name="output_launch_template_default_version"></a> launch_template_default_versionThe default version of the launch template
<a name="output_launch_template_id"></a> launch_template_idThe ID of the launch template
<a name="output_launch_template_latest_version"></a> launch_template_latest_versionThe latest version of the launch template
<a name="output_launch_template_name"></a> launch_template_nameThe name of the launch template
<!-- END_TF_DOCS -->

Notes

Authors

Module is maintained by Anton Babenko with help from these awesome contributors.

License

Apache 2 Licensed. See LICENSE for full details.

Additional information for users from Russia and Belarus