Terraform 多个实例,但通过单独执行

Terraform multiple instances but by separate execution

我正在尝试创建具有负载均衡器、安全组和三个实例的 AWS 实例 ---> GROUP 1

我可以通过声明适当的资源来做到这一点。

现在我想创建多个独立于先前实例的此类实例 ---> GROUP 2

我想要这个是因为群组的安全性,一个群组的信息不应与其他群组重叠。

我查了很多,都找不到方法。

实例如下:

resource "aws_instance" "node" {
  ami                    = data.aws_ami.ubuntu.id
  subnet_id              = aws_subnet.development-private-1a.id
  key_name               = aws_key_pair.nodes.key_name
  instance_type          = var.instance_type
  vpc_security_group_ids = [aws_security_group.dev-ec2-sg.id]
  
  tags          = {
    Name        = "${var.app_name}"
    #Environment = "production"
  }
  
  root_block_device {
        volume_type     = "gp2"
        volume_size     = 8
        delete_on_termination   = true
  }

  user_data = file("install_apache.sh")
}

resource "aws_lb_target_group_attachment" "node" {
  target_group_arn = aws_lb_target_group.dev.arn
  target_id        = aws_instance.node.id
  port             = 80
}

我想添加多个具有不同安全组和负载平衡器以及所有其他内容的实例。但我不想在 terraform 文件中添加相同的副本。我希望这些实例独立于这个实例,但我面临的问题是 terraform 仅操纵这个实例。

根据评论,您可以考虑将实例代码及其依赖项(例如目标组附件)组织为 terraform (TF) modules. Also since you are wish to create multiple instance of the same type, you could consider using aws_autoscaling_group,这样您不仅可以轻松创建多个实例,还可以轻松管理它们。

随后,您可以定义一个模块如下。以下只是部分示例。我也不使用 aws_autoscaling_group,而是使用 count:

创建多个实例

./module/ec2/main.tf


variable "subnet_id" {}

variable "app_name" {}

variable "key_pair" {}

variable "security_group_id" {}

variable "target_group_arn" {}

variable "instance_count" {
   default = 1
}

data "aws_ami" "ubuntu" {
 # ...
}

resource "aws_instance" "node" {
 
  count = var.instance_count
  
  ami                    = data.aws_ami.ubuntu.id
  subnet_id              = var.subnet_id
  key_name               = var.key_pair
  instance_type          = var.instance_type
  vpc_security_group_ids = [var.security_group_id]
  
  tags          = {
    Name        = "${var.app_name}"
    #Environment = "production"
  }
  
  root_block_device {
        volume_type     = "gp2"
        volume_size     = 8
        delete_on_termination   = true
  }

  user_data = file("install_apache.sh")
}

resource "aws_lb_target_group_attachment" "node" {

  count = var.instance_count

  target_group_arn = var.target_group_arn
  target_id        = aws_instance.node[count.index].id
  port             = 80
}

# some outputs skipped 

有了这样的模块,在您的 父 file/module 中,您将创建 GROUP 1 和 2 实例如下(同样,只是部分示例):

./main.tf


# resoruces such as LB, SGs, subnets, etc.


module "group1" {
  
  source = "./module/ec2/"

  instance_count = 3

  security_group_id = <security-group-id1>

  target_group_arn = aws_lb_target_group.dev.arn

  # other parameters
}

module "group2" {
  
  source = "./module/ec2/"

  instance_count = 3

  security_group_id = <security-group-id2>

  target_group_arn = aws_lb_target_group.dev.arn

  # other parameters
}