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