# Add multiple block volumes to multiple VM instances nd be able to scale in terms of VM instances and block volumes

**URL:** <https://discuss.hashicorp.com/t/add-multiple-block-volumes-to-multiple-vm-instances-nd-be-able-to-scale-in-terms-of-vm-instances-and-block-volumes/24576>\
**Category:** Terraform\
**Created:** [May 20, 2021, 2:22pm UTC](https://discuss.hashicorp.com/t/add-multiple-block-volumes-to-multiple-vm-instances-nd-be-able-to-scale-in-terms-of-vm-instances-and-block-volumes/24576 "2021-05-20T14:22:01Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![4matic](https://avatars.discourse-cdn.com/v4/letter/4/b3f665/32.png) [@4matic](https://discuss.hashicorp.com/u/4matic)\
**Post date:** [May 20, 2021, 2:22pm UTC](https://discuss.hashicorp.com/t/add-multiple-block-volumes-to-multiple-vm-instances-nd-be-able-to-scale-in-terms-of-vm-instances-and-block-volumes/24576/1 "2021-05-20T14:22:01Z")

</div>

I’m new to terraform and have been using this blog to help with some of my coding,  
currently I’m trying to create multiple VM instances, block volumes and attaching them to instance(s).  
While I’m able to do so, the current code does not allow scaling up or down in terms of both VM instances or block volumes.  
So for ex. if 2 VM’s are created initially with 2 block volumes attached to each of them, I need the code to handle if a new block volume is created,  
also if it is removed only the specific one should be removed, same goes with the instances.

So far I have written below code, it works fine for scaling up or down volumes, however when I change the no\_of\_instances value,  
it re-builts the VM to block association which messes up the attachments.  
I’m not sure how everyone else is handling this situation and if this is the right way to handle attachments, I’m trying to be careful here since this is very critical  
and a destruction of wrong volume can result in data loss.

##Variables  
variable “vol\_size” {  
description = “Size of Disks”  
type = list  
default = [  
“100”,  
“50”,  
]  
}

variable “no\_of\_instances” {  
description = “Number of VMs”  
default = “2”  
}

#### creates 4 volumes

resource “oci\_core\_volume” “volume\_os” {  
count = length(var.vol\_size) \* var.no\_of\_instances  
availability\_domain = “AD-1”  
compartment\_id = data.oci\_identity\_compartments.test\_compartment.compartments[0][“id”]  
display\_name = Volume${format(“%01d”, count.index + 1)}"  
size\_in\_gbs = element(var.vol\_size, count.index)  
}

resource “oci\_core\_volume\_attachment” “volume\_attachment1” {  
count = var.no\_of\_instances \* length(var.vol\_size)  
attachment\_type = var.volume\_attachment\_type  
is\_pv\_encryption\_in\_transit\_enabled = “false”  
use\_chap = “false”  
instance\_id = oci\_core\_instance.instance[count.index % var.no\_of\_instances].id  
volume\_id = oci\_core\_volume.volume\_os[count.index].id  
}

Thanks
