Search code examples
amazon-web-servicesterraformvolumes

Terraform assign volume to AWS instances list


I have created a AWS instance list using Terraform:

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}"
        }
}

How can I assign volumes to that instances like in a loop? I just trying using the next:

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

But I don't thing it is working fine, because when I try to write the AWS volumes in a file, it writes only one volume name.

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

I have tried defining the volume like this:

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

But it throws the next error:

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.

Solution

  • You'll need to tell it which instance specifically maps to which volume. You can do that with element():

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