I'm working on modulating our Terraform code and doing some testing to work out the possible options.
I'm trying to create a module to create VMs. I want to have the option of creating more than 1 VM by using the count operator. The Root modules will be for different server Role types with their specific resource block requirements for disks etc but will all create the base VM via the same VM child module (if possible).
In the root module I want to call the VM child module to create the VM and it's vnics then in root I create a data disk and then a disk attachment but the disk attachment wants the VM id, I can add the count operator to the disk attachment but how do I reference the count index from the VMs created in the module? Is this even possible? I thought about using the VM outputs but I don't believe that can use count so I'm a bit stuck. Can you even reference resource indexes created in child modules?
I did get most configuration going through when creating with a count of 1 by using [*] in the outputs but then when increasing the count to 2 it all obviously didn't like it.
resource "azurerm_virtual_machine_data_disk_attachment" "ddisk-b
attach" {
count = var.instance_count
managed_disk_id = azurerm_managed_disk.ddisk01[count.index].id
virtual_machine_id =
lun = "1"
caching = "ReadWrite"
depends_on = [module.virtual_machine] }
The above is in the root module for a specific server role that requires a data disk. Is it even possible to pull the count.index value from the VM child module that creates the VMs that the disk/s would be attached to, to be able to populate the "virtual_machine_id" input?
There is a count set in the child VM module that is called from the root. Like I said I tried an output in the module but that can't use count. Is there another way to do this? Thanks
Instead of creating multiple VMs in the module maybe you can run the module multiple times? I find that it's generally easier to manage when a module is as simple as possible.
Either way, it is very much possible to use output from iteratively created objects. Here is a simplified example of how to do it.
variable "instances" {
type = list(string)
}
resource "some_resource" "this" {
count = length(var.instances)
name = instance[count.index]
}
# can be written as [ for i in some_resource.this : i.id ]
output "ids" {
value = some_resource.this.*.id
}
Then you would use it like this
module "my_module" {
source = "path"
instances = ["test-1", "test-2", "test-3"]
}
resource "some_other_resource" "this" {
count = length(module.my_module.ids)
reference_id = module.my_module.ids[count.index]
}
Just keep in mind that since count produces a list, resources are referenced by their index. This means that if you remove an index all subsequent indices are shifted and terraform will interpret that as a change in their configuration.