Terraform将卷分配给AWS实例列表

时间:2018-02-07 08:30:28

标签: amazon-web-services terraform volumes

我使用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.

1 个答案:

答案 0 :(得分:2)

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

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