I have a terraform tfvars file with a map of values that looks like this:
name_map = [
{
name = "devbox"
device_names = ["/dev/xvdg", "/dev/xvdh"]
volume_size = ["900", "200"]
group = "hosts"
instance_type = "m5a.2xlarge"
},
{
name = "devbox2"
device_names = ["/dev/xvdg", "/dev/xvdh"]
volume_size = ["300", "200"]
group = "hosts"
instance_type = "m5a.2xlarge"
}
]
] My tf file looks like this:
resource "aws_instance" "node" {
count = length(var.name_map)
dynamic "ebs_block_device" {
for_each = [for device in var.name_map.*.device_names[count.index] : {
device_name = device,
volume_size = var.name_map.*.volume_size[count.index]
}]
content {
device_name = ebs_block_device.value.device_name
volume_type = "gp2"
volume_size = ebs_block_device.value.volume_size
delete_on_termination = true
}
}
So basically for the "devbox" instance I’d like "/dev/xvdg" to be 900 gbs, and "/dev/xvdh" to be 200 gbs. I’d like The current setup works to iterate through the device names of each mapping and get a single volume size but I’m trying to expand it to include different volume sizes for each device.
How would I do this?
I’ve tried a nested for_each statement but I keep getting errors. Would a flatten structure be the solution here? I’d love to see an example of what this would look like.
2
Answers
I think what you want to do is the following:
While this works, I suggest you do the following:
Note, the
device_name
and thevolume_size
are grouped together. Now we can use a simplefoor
loop where we don’t have to rely on indexing:I would nest your map further to create something like this:
and then in your resource code you can loop over the set for each instance:
If you want the root volume to persist post termination I would suggest adding an EBS root volume, otherwise you can ignore the root_block_device and it will create an ephemeral device that contains the image.