Reputation: 1733
When I update the AMI associated with a aws_launch_template
, Terraform creates a new version of the launch template as expected and also updates the aws_autoscaling_group
to point to the new version of the launch template.
However, no "rolling update" is performed to switch out the existing instances with new instances based on the new AMI, I have to manually terminate the existing instances and then the ASG brings up new instances using the new AMI.
What changes do I have to make to my config to get Terraform to perform a rolling update?
Existing code is as follows:
resource "aws_launch_template" "this" {
name_prefix = "my-launch-template-"
image_id = var.ami_id
instance_type = "t3.small"
key_name = "testing"
vpc_security_group_ids = [ aws_security_group.this.id ]
lifecycle {
create_before_destroy = true
}
}
resource "aws_autoscaling_group" "this" {
name_prefix = "my-asg-"
vpc_zone_identifier = var.subnet_ids
target_group_arns = var.target_group_arns
health_check_type = "ELB"
health_check_grace_period = 300
default_cooldown = 10
min_size = 4
max_size = 4
desired_capacity = 4
launch_template {
id = aws_launch_template.this.id
version = aws_launch_template.this.latest_version
}
lifecycle {
create_before_destroy = true
}
}
Upvotes: 9
Views: 5039
Reputation: 731
ASG instance refresh is also an option that replaces all old instances with newer instances as per the newest version in the launch template ( make sure to set LaunchTemplateVersion = $Latest
in ASG settings). other benefits are:
Below is terraform code block. More about the feature here
instance_refresh {
strategy = "Rolling"
preferences {
min_healthy_percentage = 50
}
triggers = ["tag"]
}
Upvotes: 2
Reputation: 628
I recently worked on that exact same scenario.
We used the random_pet
resource to generate a human readable random name that links with the AMI changes.
resource "random_pet" "ami_random_name" {
keepers = {
# Generate a new pet name every time we change the AMI
ami_id = var.ami_id
}
}
You can then use that random_pet name id on a variable that would force the recreation of your autoscaling group.
For example with name_prefix
:
resource "aws_autoscaling_group" "this" {
name_prefix = "my-asg-${random_pet.ami_random_name.id}"
vpc_zone_identifier = var.subnet_ids
target_group_arns = var.target_group_arns
health_check_type = "ELB"
health_check_grace_period = 300
default_cooldown = 10
min_size = 4
max_size = 4
desired_capacity = 4
launch_template {
id = aws_launch_template.this.id
version = aws_launch_template.this.latest_version
}
lifecycle {
create_before_destroy = true
}
}
Upvotes: 9