Terraform 将卷分配给 AWS 实例列表

Terraform assign volume to AWS instances list

我已经使用 Terraform 创建了一个 AWS 实例列表:

resource "aws_instance" "masters" {
    count = 2
    ami = "${var.aws_centos_ami}"
    instance_type = "t2.micro"
    availability_zone = "eu-west-1b"

    tags {
            Name = "master-${count.index}"
        }
}

如何像在循环中一样为该实例分配卷? 我只是尝试使用下一个:

data "aws_ebs_volume" "masters_ebs_volume" {
    most_recent = true
    filter {
      name   = "attachment.instance-id"
      values = ["${aws_instance.masters.*.id}"]
    }
}

但我不认为它工作正常,因为当我尝试将 AWS 卷写入文件时,它只写入一个卷名。

provisioner "local-exec" {
    command =  "echo \"${join("\n", data.aws_ebs_volume.masters_ebs_volume.*.id)}\" >> volumes"
}

我试过这样定义音量:

data "aws_ebs_volume" "masters_ebs_volume" {
    count = 2
#   most_recent = true
    filter {
      name   = "attachment.instance-id"
      values = ["${aws_instance.masters.*.id}"]
    }
}

但它抛出下一个错误:

data.aws_ebs_volume.masters_ebs_volume.0: Your query returned more than one result. Please try a more specific search criteria, or set `most_recent` attribute to true.

您需要告诉它哪个实例具体映射到哪个卷。您可以使用 element():

data "aws_ebs_volume" "masters_ebs_volume" {
    count = 2
    filter {
      name   = "attachment.instance-id"
      values = ["${element(aws_instance.masters.*.id, count.index)}"]
    }
}