### Example Autoscaling Module Configuration (v4.x) Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/docs/UPGRADE-5.0.md An example of how the autoscaling module was configured in version 4.x. This serves as a baseline before upgrading. ```hcl module "example" { source = "terraform-aws-modules/autoscaling/aws" version = "~> 4.x" # } ``` -------------------------------- ### Terraform Initialization and Application Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/examples/complete/README.md Commands to initialize, plan, and apply Terraform configurations for the Auto Scaling Group examples. ```bash $ terraform init $ terraform plan $ terraform apply ``` -------------------------------- ### Example Autoscaling Module Configuration (v5.x with new feature) Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/docs/UPGRADE-5.0.md An example of the autoscaling module configured for version 5.x, including the new `ignore_desired_capacity_changes` parameter. ```hcl module "example" { source = "terraform-aws-modules/autoscaling/aws" version = "~> 5.x" # ignore_desired_capacity_changes = true } ``` -------------------------------- ### One-Time Schedule Example Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/schedules.md Configures a one-time scheduled action to adjust desired capacity at a specific start time. Requires 'start_time' in RFC3339 UTC format. ```hcl schedules = { scale_up_morning = { desired_capacity = 5 start_time = "2024-06-01T08:00:00Z" } } ``` -------------------------------- ### Classic Load Balancer Attachment Example Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/traffic-source-attachment.md Demonstrates attaching a classic load balancer to an Auto Scaling group. This example includes the necessary ELB resource and the module configuration for the Auto Scaling group. ```hcl resource "aws_elb" "classic" { name = "classic-lb" # ... ELB configuration ... } module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "classic-elb-asg" # ... other configuration ... traffic_source_attachments = { elb = { traffic_source_identifier = aws_elb.classic.name traffic_source_type = "elb" } } } ``` -------------------------------- ### Configure Secondary Network Interfaces Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md Attach additional network interfaces to your instance at launch time. This is useful for complex networking setups. ```hcl dynamic "secondary_interfaces" { for_each = var.secondary_interfaces != null ? var.secondary_interfaces : [] } ``` -------------------------------- ### Step Scaling Policy Example Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/scaling-policies.md Configures a Step Scaling policy with multiple step adjustments based on metric intervals. The `estimated_instance_warmup` parameter is important for accurate scaling. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "step-scaling-asg" # ... other configuration ... scaling_policies = { scale_up_steps = { policy_type = "StepScaling" adjustment_type = "ChangeInCapacity" metric_aggregation_type = "Average" estimated_instance_warmup = 300 step_adjustment = [ { metric_interval_lower_bound = 0 metric_interval_upper_bound = 15 scaling_adjustment = 1 }, { metric_interval_lower_bound = 15 metric_interval_upper_bound = 30 scaling_adjustment = 2 }, { metric_interval_lower_bound = 30 scaling_adjustment = 3 } ] } } } ``` -------------------------------- ### Basic Launch Template Configuration Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md Example of creating a basic launch template for an Auto Scaling Group, specifying essential parameters like AMI, instance type, and network configuration. ```HCL module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "my-asg" # Launch template create_launch_template = true launch_template_name = "my-launch-template" image_id = "ami-0c55b159cbfafe1f0" instance_type = "t3.micro" # Network vpc_zone_identifier = ["subnet-123", "subnet-456"] security_groups = ["sg-123456"] # EBS enable_monitoring = true ebs_optimized = false # Capacity min_size = 1 max_size = 3 desired_capacity = 2 } ``` -------------------------------- ### Single ALB Target Group Attachment Example Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/traffic-source-attachment.md Demonstrates attaching a single ALB target group to an Auto Scaling group. This example includes the necessary ALB and target group resources along with the module configuration for the Auto Scaling group. ```hcl resource "aws_lb" "app" { name = "app-alb" # ... ALB configuration ... } resource "aws_lb_target_group" "app" { name = "app-targets" port = 80 protocol = "HTTP" vpc_id = aws_vpc.main.id target_type = "instance" health_check { healthy_threshold = 2 unhealthy_threshold = 2 timeout = 5 interval = 30 path = "/" } } module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "alb-asg" # ... other configuration ... traffic_source_attachments = { alb = { traffic_source_identifier = aws_lb_target_group.app.arn traffic_source_type = "elbv2" } } } ``` -------------------------------- ### Launch Template with User Data and Key Pair Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md Example demonstrating how to include user data and a key pair when creating a launch template for an Auto Scaling Group. User data is base64-encoded and can execute scripts on instance launch. ```HCL module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "web-asg" image_id = "ami-0c55b159cbfafe1f0" instance_type = "t3.small" key_name = "my-keypair" user_data = base64encode(file("${path.module}/user_data.sh")) vpc_zone_identifier = ["subnet-123", "subnet-456"] min_size = 2 max_size = 5 } ``` -------------------------------- ### Autoscaling Module Configuration Before v5.x Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/docs/UPGRADE-5.0.md This example shows the configuration of the autoscaling module using version 4.x, including settings for both the autoscaling group and the launch configuration. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" version = "~> 4.0" # Autoscaling group name = "example-asg" min_size = 0 max_size = 1 desired_capacity = 1 health_check_type = "EC2" vpc_zone_identifier = ["subnet-1235678", "subnet-87654321"] # Launch template lt_name = "example-asg" description = "Launch template example" update_default_version = true use_lt = true create_lt = true image_id = "ami-ebd02392" instance_type = "t3.micro" tags_as_map = { extra_tag1 = "extra_value1" extra_tag2 = "extra_value2" } } ``` -------------------------------- ### Complete Autoscaling Group with ALB and Health Checks Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/traffic-source-attachment.md A comprehensive example of an autoscaling group configured with an ALB, target group, health checks, and scaling policies. This snippet demonstrates a full setup for production environments. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "complete-alb-asg" # Capacity min_size = 2 max_size = 10 desired_capacity = 3 # Network vpc_zone_identifier = ["subnet-123", "subnet-456"] # Launch template image_id = "ami-0c55b159cbfafe1f0" instance_type = "t3.micro" # Health checks health_check_type = "ELB" health_check_grace_period = 300 # Traffic source attachment traffic_source_attachments = { alb = { traffic_source_identifier = aws_lb_target_group.app.arn traffic_source_type = "elbv2" } } # Scaling policies scaling_policies = { target_cpu = { policy_type = "TargetTrackingScaling" target_tracking_configuration = { target_value = 70.0 predefined_metric_specification = { predefined_metric_type = "ALBRequestCountPerTarget" resource_label = "${aws_lb.app.arn_suffix}/${aws_lb_target_group.app.arn_suffix}" } } } } tags = { Environment = "production" } } # ALB and target group resource "aws_lb" "app" { name = "app-alb" internal = false load_balancer_type = "application" security_groups = [aws_security_group.alb.id] subnets = ["subnet-123", "subnet-456"] } resource "aws_lb_target_group" "app" { name = "app-tg" port = 80 protocol = "HTTP" vpc_id = aws_vpc.main.id target_type = "instance" health_check { healthy_threshold = 2 unhealthy_threshold = 2 timeout = 5 interval = 30 path = "/" matcher = "200" } stickiness { type = "lb_cookie" enabled = true cookie_duration = 86400 } } resource "aws_lb_listener" "http" { load_balancer_arn = aws_lb.app.arn port = 80 protocol = "HTTP" default_action { type = "forward" target_group_arn = aws_lb_target_group.app.arn } } ``` -------------------------------- ### Target Tracking Scaling Policy (CPU) Example Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/scaling-policies.md Sets up a Target Tracking Scaling policy to maintain average CPU utilization at a target value. `disable_scale_in` can be set to `true` to prevent scaling in. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "target-tracking-asg" # ... other configuration ... scaling_policies = { target_cpu = { policy_type = "TargetTrackingScaling" target_tracking_configuration = { target_value = 50.0 disable_scale_in = false predefined_metric_specification = { predefined_metric_type = "ASGAverageCPUUtilization" } } } } } ``` -------------------------------- ### Define Scaling Policies Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/README.md Configure scaling policies by defining a map for `scaling_policies`. This example shows a Target Tracking Scaling policy based on average CPU utilization. ```hcl scaling_policies = { my-policy = { policy_type = "TargetTrackingScaling" target_tracking_configuration = { predefined_metric_specification = { predefined_metric_type = "ASGAverageCPUUtilization" resource_label = "MyLabel" } target_value = 50.0 } } } ``` -------------------------------- ### Autoscaling Group Configuration Before v7.x Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/docs/UPGRADE-8.0.md This example shows the configuration for traffic source attachment in versions prior to 7.x, using deprecated variables. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" version = "~> 7.0" # Truncated for brevity # Traffic source attachment create_traffic_source_attachment = true traffic_source_identifier = "arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456" traffic_source_type = "elbv2" ... } ``` -------------------------------- ### Autoscaling Module Configuration After v5.x Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/docs/UPGRADE-5.0.md This example demonstrates the updated configuration for the autoscaling module in version 5.x, reflecting the removal of launch configuration specific settings and changes in tag management. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" version = "~> 5.0" # Autoscaling group name = "example-asg" min_size = 0 max_size = 1 desired_capacity = 1 health_check_type = "EC2" vpc_zone_identifier = ["subnet-1235678", "subnet-87654321"] # 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" tags = { extra_tag1 = "extra_value1" extra_tag2 = "extra_value2" } } ``` -------------------------------- ### Basic IAM Role Creation for ASG Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/iam-instance-profile.md Example of creating a basic IAM role and instance profile for an Auto Scaling group. This snippet demonstrates setting the role name and description. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "asg-with-iam" # ... other configuration ... create_iam_instance_profile = true iam_role_name = "asg-role" iam_role_description = "Role for ASG instances" iam_role_policies = { "CloudWatchAgentServerPolicy" = "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy" } } ``` -------------------------------- ### Configure Development Environment Off-Hours Scaling Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/schedules.md Implement minimal scaling for development environments during off-hours and weekends to save costs. This example sets a low desired capacity outside of typical working hours. ```HCL module "dev_asg" { source = "terraform-aws-modules/autoscaling/aws" name = "dev-asg" min_size = 1 max_size = 5 # ... other configuration ... schedules = { scale_up_work_hours = { desired_capacity = 3 recurrence = "0 6 ? * MON-FRI" time_zone = "America/New_York" } scale_down_off_hours = { desired_capacity = 1 recurrence = "0 20 ? * MON-FRI" time_zone = "America/New_York" } scale_down_weekends = { desired_capacity = 1 recurrence = "0 0 ? * SAT" time_zone = "America/New_York" } } } ``` -------------------------------- ### Move Terraform State for `ignore_desired_capacity_changes` (Specific Example) Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/docs/UPGRADE-5.0.md The specific Terraform state move command corresponding to the example configuration update from v4.x to v5.x with `ignore_desired_capacity_changes` enabled. ```bash terraform state mv 'module.example.aws_autoscaling_group.this[0]' 'module.example.aws_autoscaling_group.idc[0]' ``` -------------------------------- ### Complete Security-Hardened IAM Instance Profile Example Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/iam-instance-profile.md Configures a highly secure IAM instance profile and role for an Auto Scaling Group, adhering to the principle of least privilege with custom policies and tags. ```hcl # Custom policy for least-privilege access resource "aws_iam_policy" "app_policy" { name = "app-server-policy" policy = jsonencode({ Version = "2012-10-17" Statement = [ { Sid = "S3AppDataAccess" Effect = "Allow" Action = [ "s3:GetObject", "s3:PutObject" ] Resource = "${aws_s3_bucket.app_data.arn}/*" }, { Sid = "KMSDecryption" Effect = "Allow" Action = [ "kms:Decrypt", "kms:GenerateDataKey" ] Resource = aws_kms_key.app.arn }, { Sid = "SecretsManagerAccess" Effect = "Allow" Action = [ "secretsmanager:GetSecretValue" ] Resource = "arn:aws:secretsmanager:*:*:secret:app/*" } ] }) } module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "secure-app-asg" # ... other configuration ... create_iam_instance_profile = true iam_role_name = "secure-app-role" iam_role_path = "/applications/" iam_role_description = "Role for application servers with least-privilege access" iam_role_policies = { "AmazonSSMManagedInstanceCore" = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" "CloudWatchAgentServerPolicy" = "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy" "AppServerPolicy" = aws_iam_policy.app_policy.arn } iam_role_tags = { Environment = "production" Classification = "restricted" Compliance = "pci-dss" } } resource "aws_s3_bucket" "app_data" { bucket = "app-data-bucket" } resource "aws_kms_key" "app" { description = "Key for app encryption" } ``` -------------------------------- ### Multiple Target Groups Attachment Example Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/traffic-source-attachment.md Shows how to attach multiple target groups (e.g., for HTTP and gRPC traffic) to a single Auto Scaling group. This allows for more complex routing configurations. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "multi-target-asg" # ... other configuration ... traffic_source_attachments = { http_tg = { traffic_source_identifier = aws_lb_target_group.http.arn traffic_source_type = "elbv2" } grpc_tg = { traffic_source_identifier = aws_lb_target_group.grpc.arn traffic_source_type = "elbv2" } } } ``` -------------------------------- ### Autoscaling Group Configuration Before v9.x Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/docs/UPGRADE-9.0.md Example of an autoscaling group configuration using version 8.x of the module, demonstrating the 'override' block directly within the 'autoscaling' module. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" version = "~> 8.0" # Truncated for brevity override = [ { instance_type = "t3.nano" weighted_capacity = "2" }, { instance_type = "t3.medium" weighted_capacity = "1" }, ] ... } ``` -------------------------------- ### Autoscaling Group Configuration After v8.x Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/docs/UPGRADE-8.0.md This example demonstrates the updated configuration for traffic source attachment in version 8.x, utilizing the new `traffic_source_attachments` variable. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" version = "~> 8.0" # Truncated for brevity traffic_source_attachments = { ex-alb = { traffic_source_identifier = "arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456" traffic_source_type = "elbv2" } ... } ... } ``` -------------------------------- ### Simple Scaling Policy Example Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/scaling-policies.md Defines two Simple Scaling policies, one for scaling up and one for scaling down, triggered by CloudWatch alarms. Ensure CloudWatch alarms are created to trigger these policies. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "simple-scaling-asg" # ... other configuration ... scaling_policies = { scale_up = { name = "scale-up" policy_type = "SimpleScaling" adjustment_type = "ChangeInCapacity" scaling_adjustment = 1 cooldown = 300 } scale_down = { name = "scale-down" policy_type = "SimpleScaling" adjustment_type = "ChangeInCapacity" scaling_adjustment = -1 cooldown = 600 } } } # Create CloudWatch alarms to trigger these policies resource "aws_cloudwatch_metric_alarm" "high_cpu" { alarm_name = "asg-high-cpu" comparison_operator = "GreaterThanThreshold" evaluation_periods = 2 metric_name = "CPUUtilization" namespace = "AWS/EC2" period = 300 statistic = "Average" threshold = 80 alarm_actions = [module.asg.autoscaling_policy_arns["scale_up"]] } resource "aws_cloudwatch_metric_alarm" "low_cpu" { alarm_name = "asg-low-cpu" comparison_operator = "LessThanThreshold" evaluation_periods = 15 metric_name = "CPUUtilization" namespace = "AWS/EC2" period = 300 statistic = "Average" threshold = 20 alarm_actions = [module.asg.autoscaling_policy_arns["scale_down"]] } ``` -------------------------------- ### Autoscaling Group Configuration After v9.x Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/docs/UPGRADE-9.0.md Example of an autoscaling group configuration using version 9.x of the module, showing the 'override' block now nested within the 'launch_template' block. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" version = "~> 9.0" # Truncated for brevity launch_template = { override = [ { instance_type = "t3.nano" weighted_capacity = "2" }, { instance_type = "t3.medium" weighted_capacity = "1" }, ] } ... } ``` -------------------------------- ### Usage Example: Business Hours Scaling Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/schedules.md Demonstrates configuring multiple scheduled actions for an Auto Scaling group to manage capacity during business hours and weekends. Includes scaling up in the morning and scaling down in the evening/weekends. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "business-hours-asg" # ... other configuration ... schedules = { scale_up_morning = { desired_capacity = 10 min_size = 5 max_size = 20 recurrence = "0 8 ? * MON-FRI" time_zone = "America/New_York" } scale_down_evening = { desired_capacity = 2 min_size = 1 max_size = 20 recurrence = "0 18 ? * MON-FRI" time_zone = "America/New_York" } scale_down_weekend = { desired_capacity = 1 min_size = 1 max_size = 20 recurrence = "0 0 ? * SAT" time_zone = "America/New_York" } } } ``` -------------------------------- ### Terraform Autoscaling Module Usage Example Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/outputs.md Demonstrates how to configure and use the Terraform AWS Autoscaling module, including defining basic ASG parameters and outputting key identifiers like the autoscaling group ID, launch template ID, and IAM role ARN. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "example-asg" min_size = 1 max_size = 3 desired_capacity = 2 vpc_zone_identifier = ["subnet-123", "subnet-456"] image_id = "ami-123456" instance_type = "t3.micro" } output "asg_id" { value = module.asg.autoscaling_group_id } output "launch_template_id" { value = module.asg.launch_template_id } output "iam_role_arn" { value = module.asg.iam_role_arn } ``` -------------------------------- ### Autoscaling Launch Template with Spot Instance Configuration Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md Set up autoscaling groups to utilize spot instances, specifying the market type, maximum price, and instance interruption behavior. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "spot-asg" image_id = "ami-0c55b159cbfafe1f0" instance_type = "t3.medium" instance_market_options = { market_type = "spot" spot_options = { max_price = "0.05" spot_instance_type = "persistent" instance_interruption_behavior = "terminate" } } vpc_zone_identifier = ["subnet-123", "subnet-456"] min_size = 0 max_size = 10 } ``` -------------------------------- ### Example IAM Role Policies Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/iam-instance-profile.md This map defines the policies to be attached to the IAM role. It maps policy names to their respective ARNs. ```hcl iam_role_policies = { "AmazonSSMManagedInstanceCore" = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" "CloudWatchAgentServerPolicy" = "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy" "AmazonEC2ContainerRegistryReadOnly" = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly" } ``` -------------------------------- ### Autoscaling Launch Template with Security Best Practices Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md Implement security best practices for autoscaling groups, including enforcing IMDSv2, enabling protection against termination and stop actions, and configuring encrypted EBS volumes. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "secure-asg" image_id = "ami-0c55b159cbfafe1f0" instance_type = "t3.medium" # IMDSv2 enforced (default) metadata_options = { http_endpoint = "enabled" http_tokens = "required" http_put_response_hop_limit = 1 } # Protection enabled disable_api_termination = true disable_api_stop = true # Monitoring enabled enable_monitoring = true # Monitoring encryption block_device_mappings = [{ device_name = "/dev/xvda" ebs = { encrypted = true volume_type = "gp3" volume_size = 50 } }] vpc_zone_identifier = ["subnet-123"] create_iam_instance_profile = true min_size = 1 max_size = 3 } ``` -------------------------------- ### Use External Launch Template Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/README.md Set `create_launch_template` to `false` and provide the name of an existing launch template to create an autoscaling group with it. ```hcl create_launch_template = false launch_template = aws_launch_template.my_launch_template.name ``` -------------------------------- ### Common Managed Policies for IAM Roles Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/iam-instance-profile.md Examples of common AWS managed policies that can be assigned to IAM roles for specific use cases. ```hcl iam_role_policies = { "AmazonSSMManagedInstanceCore" = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" } ``` ```hcl iam_role_policies = { "CloudWatchAgentServerPolicy" = "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy" } ``` ```hcl iam_role_policies = { "AmazonEC2ContainerRegistryReadOnly" = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly" } ``` ```hcl iam_role_policies = { "AmazonS3ReadOnlyAccess" = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess" } ``` ```hcl iam_role_policies = { "service-role/AmazonEC2ContainerServiceforEC2Role" = "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role" } ``` -------------------------------- ### IAM Role with Custom Permissions Boundary Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/iam-instance-profile.md Example of creating an IAM role with a custom permissions boundary to restrict the maximum permissions granted to instances. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "asg-bounded" # ... other configuration ... create_iam_instance_profile = true iam_role_name = "limited-role" iam_role_permissions_boundary = aws_iam_policy.max_permissions.arn iam_role_policies = { "AmazonSSMManagedInstanceCore" = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" } } resource "aws_iam_policy" "max_permissions" { name = "max-permissions-boundary" policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = [ "ec2:*", "s3:ListBucket", "cloudwatch:PutMetricData" ] Resource = "*" } ] }) } ``` -------------------------------- ### Autoscaling Launch Template with Flexible Instance Type Selection Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md Use this configuration to define autoscaling groups with flexible instance type requirements based on CPU and memory, allowing for a range of compatible instance types. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "flexible-asg" instance_requirements = { vcpu_count = { min = 2 max = 4 } memory_mib = { min = 2048 max = 8192 } allowed_instance_types = ["t3.*", "m5.*"] } vpc_zone_identifier = ["subnet-123", "subnet-456"] min_size = 1 max_size = 10 } ``` -------------------------------- ### Recurring Schedule Example Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/schedules.md Configures a recurring scheduled action using a cron expression and specifies a time zone. Requires 'recurrence' in cron format. ```hcl schedules = { scale_up_weekdays = { desired_capacity = 5 recurrence = "0 8 ? * MON-FRI" time_zone = "America/New_York" } } ``` -------------------------------- ### Configure Instance Placement Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md Dynamically configure placement options for instances, such as availability zone, affinity, and placement group. Use this when specific placement strategies are required. ```HCL dynamic "placement" { for_each = var.placement != null ? [var.placement] : [] } ``` -------------------------------- ### Destroying Resources Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/examples/complete/README.md Command to destroy all resources created by the Terraform Auto Scaling Group examples. Use this when resources are no longer needed to avoid ongoing costs. ```bash terraform destroy ``` -------------------------------- ### Create Only Launch Template Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/README.md Set `create` to `false` to exclusively create a launch template without an autoscaling group. ```hcl create = false ``` -------------------------------- ### Configure Simple Scaling Policy Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/scaling-policies.md Sets up a Simple Scaling policy for basic capacity adjustments. Use this for predictable scaling needs based on a single metric alarm. ```hcl scaling_policies = { scale_up = { policy_type = "SimpleScaling" adjustment_type = "ChangeInCapacity" scaling_adjustment = 1 cooldown = 300 } } ``` -------------------------------- ### Cron Expression Examples Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/schedules.md Illustrates common cron expressions for AWS Auto Scaling scheduled actions, including daily, weekly, and interval-based schedules. Times are in UTC. ```text 0 8 ? * MON-FRI # 8:00 AM weekdays 0 9 * * * # Every day at 9:00 AM 0 8,12,18 * * * # 8:00 AM, 12:00 PM, 6:00 PM every day 0 0 1 * * # First day of month at midnight 30 2 ? * SUN # 2:30 AM every Sunday 0/30 * * * * # Every 30 minutes ``` -------------------------------- ### Configure Metadata Options (IMDSv2) Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md Set instance metadata service options, including enabling the endpoint, setting hop limits, and requiring tokens for IMDSv2. Defaults enforce security best practices. ```hcl dynamic "metadata_options" { for_each = var.metadata_options != null ? [var.metadata_options] : [] } ``` ```hcl metadata_options = { http_endpoint = "enabled" http_put_response_hop_limit = 1 http_tokens = "required" } ``` -------------------------------- ### IAM Role for Container Registry Access Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/iam-instance-profile.md Example of creating an IAM role for an Auto Scaling group to allow pulling container images from ECR. This is useful for containerized applications. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "asg-with-ecr" # ... other configuration ... create_iam_instance_profile = true iam_role_name = "asg-ecr-role" iam_role_policies = { "AmazonEC2ContainerRegistryReadOnly" = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly" } } ``` -------------------------------- ### Autoscaling Launch Template with Block Devices and Storage Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md Configure autoscaling groups with specific block device mappings, including EBS volume details like size, type, encryption, and deletion on termination. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "storage-asg" image_id = "ami-0c55b159cbfafe1f0" instance_type = "m5.large" ebs_optimized = true block_device_mappings = [ { device_name = "/dev/xvda" ebs = { volume_size = 50 volume_type = "gp3" delete_on_termination = true encrypted = true iops = 3000 throughput = 125 } }, { device_name = "/dev/sda1" ebs = { volume_size = 100 volume_type = "gp3" delete_on_termination = true } } ] vpc_zone_identifier = ["subnet-123"] min_size = 1 max_size = 5 } ``` -------------------------------- ### Apply Tags to Resources Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md Dynamically apply tags to various resources created from the launch template, including EC2 instances, EBS volumes, and spot requests. Specify the resource type and the tags to apply. ```HCL dynamic "tag_specifications" { for_each = var.tag_specifications != null ? var.tag_specifications : [] } ``` -------------------------------- ### aws_launch_template Resource Configuration Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md This snippet outlines the configuration parameters for the `aws_launch_template` resource managed by the module. It covers core settings, AMI and instance type selection, instance requirements, IAM instance profiles, storage configurations, and CPU options. ```APIDOC ## Resource: aws_launch_template ### Description Manages AWS EC2 Launch Templates with comprehensive instance configuration options. This resource is optionally created by the module when `create_launch_template` is set to `true`. ### Parameters #### Core Configuration - **region** (string, Optional) - AWS region. Defaults to provider region. - **launch_template_name** (string, Optional) - Template name. Defaults to `var.name`. - **launch_template_use_name_prefix** (bool, Optional) - Use name as prefix if true. Defaults to `true`. - **launch_template_description** (string, Optional) - Template description. Defaults to `null`. - **default_version** (string, Optional) - Default version number. Defaults to `null`. - **update_default_version** (bool, Optional) - Update default version on each update. Defaults to `null`. #### AMI and Instance Type - **image_id** (string, Optional) - AMI ID (e.g., ami-0c55b159cbfafe1f0). Defaults to `null`. - **instance_type** (string, Optional) - Instance type (e.g., t3.micro, m5.large). Cannot be used with `instance_requirements`. Defaults to `null`. - **instance_initiated_shutdown_behavior** (string, Optional) - Shutdown behavior: "stop" or "terminate". Defaults to `null`. #### Instance Requirements (Flexible Instance Type) - **instance_requirements** (object, Optional) - Attribute-based instance requirements. Cannot be used with `instance_type`. Defaults to `null`. - **vcpu_count** (object, Optional) - {min, max} vCPU count. - **memory_mib** (object, Optional) - {min, max} RAM in MiB. - **allowed_instance_types** (list(string), Optional) - List of allowed types. - **excluded_instance_types** (list(string), Optional) - List of excluded types. - **require_hibernate_support** (bool, Optional) - Requires hibernate support. #### IAM Instance Profile - **iam_instance_profile_name** (string, Optional) - Name of the IAM instance profile. - **iam_instance_profile_arn** (string, Optional) - ARN of the IAM instance profile. #### Storage Configuration (Block Device Mappings) - **block_device_mappings** (list(object), Optional) - List of block device mappings. - **device_name** (string, Optional) - Device name (e.g., /dev/xvda, /dev/sda1). Defaults to `null`. - **ebs** (object, Optional) - EBS volume configuration. Defaults to `null`. - **volume_size** (number, Optional) - Size in GiB. - **volume_type** (string, Optional) - gp2, gp3, io1, io2, st1, sc1. - **iops** (number, Optional) - IOPS (for gp3, io1, io2). - **throughput** (number, Optional) - Throughput MiB/s (for gp3). - **delete_on_termination** (bool, Optional) - Whether to delete on termination. - **encrypted** (bool, Optional) - Whether the EBS volume is encrypted. - **kms_key_id** (string, Optional) - KMS key ID for encryption. - **snapshot_id** (string, Optional) - Snapshot ID for volume creation. - **virtual_name** (string, Optional) - Virtual name for instance store. Defaults to `null`. - **no_device** (string, Optional) - Suppress device from AMI. Defaults to `null`. #### CPU Options - **cpu_options** (object, Optional) - CPU configuration options. - **core_count** (number, Optional) - Number of CPU cores. Defaults to `null`. - **threads_per_core** (number, Optional) - Threads per core (1 or 2). Defaults to `null`. - **amd_sev_snp** (string, Optional) - AMD SEV-SNP support. Defaults to `null`. - **nested_virtualization** (string, Optional) - Nested virtualization support. Defaults to `null`. ### Outputs - **launch_template_id** - **launch_template_name** - **launch_template_arn** - **launch_template_latest_version** - **launch_template_default_version** ``` -------------------------------- ### Launch Template Configuration Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/autoscaling-group.md Use this block to specify an existing launch template for the autoscaling group. It cannot be used with a mixed instances policy. ```hcl dynamic "launch_template" { for_each = var.use_mixed_instances_policy ? [] : [1] content { id = local.launch_template_id version = local.launch_template_version } } ``` -------------------------------- ### Traffic Source Attachment for Classic Load Balancer (ELB) Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/traffic-source-attachment.md Example configuration for attaching a classic load balancer to an Auto Scaling group. Use this for legacy deployments. The `traffic_source_identifier` is the name of the ELB. ```hcl traffic_source_attachments = { classic_lb = { traffic_source_identifier = aws_elb.classic.name traffic_source_type = "elb" } } ``` -------------------------------- ### Initial Lifecycle Hook Configuration Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/autoscaling-group.md Define lifecycle hooks that execute during instance launch or termination. This block iterates over `initial_lifecycle_hooks` to set up multiple hooks. ```hcl dynamic "initial_lifecycle_hook" { for_each = var.initial_lifecycle_hooks != null ? var.initial_lifecycle_hooks : [] content { name = initial_lifecycle_hook.value.name lifecycle_transition = initial_lifecycle_hook.value.lifecycle_transition default_result = initial_lifecycle_hook.value.default_result heartbeat_timeout = initial_lifecycle_hook.value.heartbeat_timeout notification_target_arn = initial_lifecycle_hook.value.notification_target_arn notification_metadata = initial_lifecycle_hook.value.notification_metadata role_arn = initial_lifecycle_hook.value.role_arn } } ``` -------------------------------- ### Using Externally Created Launch Configuration Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/docs/UPGRADE-4.0.md Configure these variables when you are managing the launch configuration outside of this module. ```hcl lc_name = "externally-created" use_lc = true ``` -------------------------------- ### Automatic IAM Instance Profile Integration with Launch Template Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/iam-instance-profile.md This dynamic block ensures that the specified or created IAM instance profile is automatically attached to the launch template. Instances launched using this template will inherit the profile. ```hcl dynamic "iam_instance_profile" { for_each = local.iam_instance_profile_name != null || local.iam_instance_profile_arn != null ? [1] : [] content { name = local.iam_instance_profile_name arn = local.iam_instance_profile_arn } } ``` -------------------------------- ### Mixed Instances Policy Configuration Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/autoscaling-group.md Enables flexible instance type selection with On-Demand and Spot pricing strategies. This block cannot be used with a regular launch template block. ```hcl dynamic "mixed_instances_policy" { for_each = var.use_mixed_instances_policy ? [var.mixed_instances_policy] : [] content { # instances_distribution configuration dynamic "launch_template" { # launch_template_specification with overrides } } } ``` -------------------------------- ### Traffic Source Attachment for Application/Network Load Balancer (ELBv2) Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/traffic-source-attachment.md Example configuration for attaching an ALB or NLB target group to an Auto Scaling group. This is recommended for modern deployments. The `traffic_source_identifier` is the ARN of the target group. ```hcl traffic_source_attachments = { alb_target_group = { traffic_source_identifier = aws_lb_target_group.app.arn traffic_source_type = "elbv2" } } ``` -------------------------------- ### Configure a One-Time Event Schedule Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/schedules.md Set up a single scaling event using `start_time` and `end_time` for temporary capacity adjustments. This is useful for promotions or planned maintenance. ```HCL module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "event-asg" # ... other configuration ... schedules = { scale_for_promotion = { desired_capacity = 50 min_size = 25 start_time = "2024-12-20T00:00:00Z" end_time = "2024-12-27T00:00:00Z" } } } ``` -------------------------------- ### Traffic Source Attachment for VPC Lattice Service Network Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/traffic-source-attachment.md Example configuration for attaching a VPC Lattice service network to an Auto Scaling group. This is suitable for microservices architectures. The `traffic_source_identifier` is the ARN of the VPC Lattice service. ```hcl traffic_source_attachments = { vpc_lattice = { traffic_source_identifier = aws_vpclattice_service_network.app.arn traffic_source_type = "vpc-lattice" } } ``` -------------------------------- ### Set Launch Template Tags Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/launch-template.md Assign additional tags directly to the launch template resource itself. These tags help in organizing and identifying the launch template. ```HCL launch_template_tags = var.launch_template_tags ``` -------------------------------- ### Terragrunt Example: Managing Multiple S3 Buckets Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/wrappers/README.md This Terragrunt configuration manages multiple S3 buckets using the autoscaling wrapper module. It sets default bucket configurations and defines specific settings for individual buckets. ```hcl terraform { source = "tfr:///terraform-aws-modules/autoscaling/aws//wrappers" # Alternative source: # source = "git::git@github.com:terraform-aws-modules/terraform-aws-autoscaling.git//wrappers?ref=master" } inputs = { defaults = { force_destroy = true attach_elb_log_delivery_policy = true attach_lb_log_delivery_policy = true attach_deny_insecure_transport_policy = true attach_require_latest_tls_policy = true } items = { bucket1 = { bucket = "my-random-bucket-1" } bucket2 = { bucket = "my-random-bucket-2" tags = { Secure = "probably" } } } } ``` -------------------------------- ### Module Creates Launch Configuration Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/docs/UPGRADE-4.0.md Use these variables when the module is responsible for creating the launch configuration. This is the default behavior for most use cases. ```hcl lc_name = "module-will-create" use_lc = true create_lc = true ``` -------------------------------- ### Basic Autoscaling Group Deployment Source: https://github.com/terraform-aws-modules/terraform-aws-autoscaling/blob/master/_autodocs/api-reference/autoscaling-group.md Deploys a basic autoscaling group with specified capacity, network configuration, and launch template details. The launch template is created automatically by the module. ```hcl module "asg" { source = "terraform-aws-modules/autoscaling/aws" name = "example-asg" # Capacity min_size = 1 max_size = 5 desired_capacity = 2 # Network vpc_zone_identifier = ["subnet-abc123", "subnet-def456"] # Launch template (created automatically) image_id = "ami-0c55b159cbfafe1f0" instance_type = "t3.micro" # Health health_check_type = "ELB" health_check_grace_period = 300 tags = { Environment = "production" } } ```