I've never implemented an ASG before, so I thought I could create an instance and an ASG w/ a launch template like-so:
resource "aws_instance" "bastion" {
count = var.azs
ami = data.aws_ami.AL2_ami.id
key_name = aws_key_pair.bastion_auth.id
instance_type = var.instance_type
security_groups = [aws_security_group.bastion-sg.id]
associate_public_ip_address = true
subnet_id = module.vpc.public_subnets[count.index]
user_data = file("userdata.tpl")
root_block_device {
volume_size = var.main_vol_size
}
tags = {
Name = "${var.name}-bastion-host-${count.index 1}"
}
}
resource "aws_launch_template" "bastion_launch_template" {
name_prefix = "bastion-launch-template"
image_id = data.aws_ami.AL2_ami.id
instance_type = var.instance_type
key_name = aws_key_pair.bastion_auth.id
tags = {
Name = "${var.name}-bastion-launch-template"
}
}
resource "aws_placement_group" "bastion_placement_group" {
name = "bastion-placement-group"
strategy = "spread"
tags = {
Name = "${var.name}-bastion-placement-group"
}
}
resource "aws_autoscaling_group" "bastion_asg" {
name = "bastion-asg"
max_size = 3
min_size = 3
health_check_grace_period = 60
health_check_type = "EC2"
placement_group = aws_placement_group.bastion_placement_group.id
availability_zones = module.vpc.azs
launch_template {
id = aws_launch_template.bastion_launch_template.id
version = "$Default"
}
}
It's a bastion host so I also have a security group to allow only SSH, but all this did was create 3 bastion hosts (like I wanted) and then 3 separate instances because of the auto-scaling group. I tried looking into using an auto scaling group attachment but based off the docs, I can only use it to attach to load balancers?
My goal is to have 3 instances that act as a bastion host and are attached to an ASG. Do I completely omit the aws_instance resource block and deploy the instances through the ASG launch template? Or is there a way to associate the ASG with my instances that get deployed with the aws_instance resource block
CodePudding user response:
You don't need a separate aws_instance resource. ASG will take care of creating instances from the launch-template itself.
resource "aws_launch_template" "bastion_launch_template" {
name_prefix = "bastion-launch-template"
image_id = data.aws_ami.AL2_ami.id
instance_type = var.instance_type
key_name = aws_key_pair.bastion_auth.id
tags = {
Name = "${var.name}-bastion-launch-template"
}
}
resource "aws_placement_group" "bastion_placement_group" {
name = "bastion-placement-group"
strategy = "spread"
tags = {
Name = "${var.name}-bastion-placement-group"
}
}
resource "aws_autoscaling_group" "bastion_asg" {
name = "bastion-asg"
max_size = 3
min_size = 3
health_check_grace_period = 60
health_check_type = "EC2"
placement_group = aws_placement_group.bastion_placement_group.id
availability_zones = module.vpc.azs
launch_template {
id = aws_launch_template.bastion_launch_template.id
version = "$Default"
}
}