我以前从未实现过ASG,所以我想我可以创建一个实例和一个带有启动模板的ASG,如下所示:
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"
}
}
这是一个堡垒主机,所以我也有一个安全组,只允许SSH,但所有这些都是创建3个堡垒主机(如我想要的),然后3个独立的实例,因为自动伸缩组。我尝试使用自动伸缩组附件,但基于文档,我只能使用它来附加到负载平衡器?
我的目标是有3个实例作为堡垒主机并连接到ASG。是否完全省略aws_instance资源块,并通过ASG +启动模板部署实例?或者是否有一种方法可以将ASG与部署在aws_instance资源块中的实例相关联
您不需要单独的aws_instance资源。ASG将负责从启动模板本身创建实例。
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"
}
}