2

I have an EC2 module, which determines the number of instances via a count variable, like so

resource "aws_instance" "this" {
  count = var.instance_count

I would like to subsequently create EBS volumes in the same module, and attach them to each of the instances created. The problem I encountered with this though, is that I need a way to pass the id of each volume to all of the volume_attachment resource, in order to attach each EBS volume to each EC2 instance, so I'd have to have a way to loop through each ec2 id, to then attach all volumes to it.

Which leads to my question: Is there a way to loop through each EC2 instance id, and attach all the EBS volumes to it?

resource "aws_volume_attachment" "this" {
  for_each    = toset(var.ebs_volume_attachments)
  device_name = each.name
  volume_id   = aws_ebs_volume.this.id
  instance_id = module.ec2.id
}

resource "aws_ebs_volume" "this" {
  for_each          = toset(var.ebs_volume_attachments)
  availability_zone = each.availability_zone
  size              = each.size
  encrypted         = each.encrypted
  snapshot_id       = each.snapshot_id
  type              = each.type
  kms_key_id        = each.kms_key_id

  tags = local.tags
} 
1
  • I had to do something similar but for IAM roles. One way is to provide the ec2 instances as outputs and feed them to the volume_attachment as it should output them as a list or try to give them directly like instance_id = module.ec2.instances where instances should be the resource for the ec2 you are trying to create, if you get my point. You can check this article, it helped me in that case, but do look up if you can use outputs. If that doesn't work try using 2 modules. Link Commented Sep 21, 2021 at 8:45

1 Answer 1

0

What would the value of var.ebs_volume_attachments be?

Wouldn't this work?

resource "aws_volume_attachment" "this" {
  count       = var.instance_count
  device_name = "/dev/sdh"
  volume_id   = aws_ebs_volume.this[count.index].id
  instance_id = aws_instance.this[count.index].id
}

resource "aws_ebs_volume" "this" {
  count             = var.instance_count
  ...
} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.