0
votes

How would I go about creating and attaching more than one EBS volume to an instance?

The code below works when attaching a single EBS volume. My main concern is creating a map between the size of the EBS volume and the device name. I've tried a variant of things, creating a list, etc. But no luck.

# Create EBS volume
resource "aws_ebs_volume" "ebs_volume" {
  count                 = "${var.ec2_create_volume == true ? var.ec2_instance_count : 0 }"
  availability_zone     = "${aws_instance.ec2.*.availability_zone[count.index]}"
  size                  = "${var.ec2_ebs_volume_size}"
  type                  = "${var.ec2_ebs_volume_type}"
}

# Attach EBS Volume
resource "aws_volume_attachment" "volume_attachment" {
  count                 = "${var.ec2_create_volume == true ? var.ec2_instance_count : 0 }"
  device_name           = "${var.ec2_device_name}"
  volume_id             = "${aws_ebs_volume.ebs_volume.*.id[count.index]}"
  instance_id           = "${aws_instance.ec2.*.id[count.index]}"
}
1
Will the number of EBS per instance vary or be constant? - Matt Schuchard
@MattSchuchard they'll be constant - hfranco
If you got error,where are the error logs? - BMW
So you want to be able to create multiple drives of different sizes based on command line parameters? - kichik
@kichik no. I simply want to create and attach more than one EBS volume to a single instance without creating multiple resources for each volume. - hfranco

1 Answers

3
votes

You almost there, try using element(list, index) - it will loop over the list. For example, this config will successfully create 2 ec2 instances with 3 additional ebs volumes attached to each:

variable "ec2_device_names" {
  default = [
    "/dev/sdd",
    "/dev/sde",
    "/dev/sdf",
  ]
}

variable "ec2_instance_count" {
  default = 2
}

variable "ec2_ebs_volume_count" {
  default = 3
}

resource "aws_instance" "ec2" {
  count         = "${var.ec2_instance_count}"
  ami           = "${var.aws_ami_id}"
  instance_type = "${var.ec2_instance_type}"
}

resource "aws_ebs_volume" "ebs_volume" {
  count             = "${var.ec2_instance_count * var.ec2_ebs_volume_count}"
  availability_zone = "${element(aws_instance.ec2.*.availability_zone, count.index)}"
  size              = "${var.ec2_ebs_volume_size}"
}

resource "aws_volume_attachment" "volume_attachement" {
  count       = "${var.ec2_instance_count * var.ec2_ebs_volume_count}"
  volume_id   = "${aws_ebs_volume.ebs_volume.*.id[count.index]}"
  device_name = "${element(var.ec2_device_names, count.index)}"
  instance_id = "${element(aws_instance.ec2.*.id, count.index)}"
}