2 min read | by Jordi Prats
Launch templates were introducted in late 2017 as a replacement for launch configurations: They are very similar, although launch templates provide much deeper and wider options to configure the instances that are going to be launched (by using an Auto Scaling Group)
To convert a launch configuration to a launch template we are not going to need many changes, but once we have it converted we will be able to configure much more details on the launch template than we could have configured before.
Assuming we have the following aws_launch_configuration:
resource "aws_launch_configuration" "demo" {
iam_instance_profile = aws_iam_instance_profile.worker.arn
image_id = data.aws_ami.eks.id
instance_type = "m5a.xxlarge"
name_prefix = "demo_lc_"
key_name = "testkey"
user_data_base64 = base64encode(
<<-EOT
#!/bin/bash
echo "demo userdata"
EOT
)
security_groups = [
aws_security_group.worker.id,
]
root_block_device {
volume_size = "100"
volume_type = "standard"
}
lifecycle {
create_before_destroy = true
}
}
A equivalent aws_launch_template would look like this:
data "template_file" "user_data_demo" {
template = <<EOF
#!/bin/bash
echo "demo userdata"
EOF
)
}
resource "aws_launch_template" "demo" {
name = "demo_lt"
iam_instance_profile {
arn = aws_iam_instance_profile.worker.arn
}
image_id = data.aws_ami.eks.id
instance_initiated_shutdown_behavior = "terminate"
instance_type = "m5a.xxlarge"
key_name = "testkey"
vpc_security_group_ids = [
aws_security_group.worker.id,
]
user_data = base64encode(data.template_file.user_data_demo.rendered)
block_device_mappings {
device_name = "/dev/xvda"
ebs {
volume_size = "100"
volume_type = "standard"
}
}
}
On the aws_autoscaling_group we will have something like this for the launch configuration:
resource "aws_autoscaling_group" "demo" {
desired_capacity = "10"
capacity_rebalance = true
launch_configuration = aws_launch_configuration.demo.id
(...)
To be able to use the launch template we will have to take also specify the launch template version (one of the selling points is that is is versioned)
It can be:
If we want to always use the latest version we can configured the ASG like so:
resource "aws_autoscaling_group" "demo" {
desired_capacity = "10"
capacity_rebalance = true
launch_template {
id = aws_launch_template.demo.id
version = "$Latest"
}
(...)
Posted on 27/08/2021