Jolly Molly
Jolly Molly

Reputation: 53

Terraform v0.13+ : Using count in modules

I am using Terraform version v0.14.3. I am using count in modules to create multiple Azure resources (network interface card, VM) of the same type. Below is the parent module, calling child modules NIC and VM :

module "NIC" {
  source = "./NIC"
  count  = 2

  nic_name      =  "vm-nic-${count.index + 1}" 
  nic_location  = "eastus2"
  rg_name       = "abc-test-rg"
  ipconfig_name = "vm-nic-ipconfig-${count.index + 1}" 
  subnet_id     = "/subscriptions/***********/resourceGroups/abc-test-rg/providers/Microsoft.Network/virtualNetworks/abc-test-vnet/subnets/abc-test-vnet"
  
}
output "nic_id" {
  value = module.NIC[*].nic_id
}
module "VM" {
  source = "./VM"
  count = 2

  vm_name        = "test-vm"
  rg_name        = "abc-test-rg"
  location       = "eastus2"
  admin_password = var.admin_password
  nic_id         = [module.NIC[*].nic_id]
  
}

I am getting below error during terraform plan :

Error: Incorrect attribute value type

  on VM\main.tf line 8, in resource "azurerm_linux_virtual_machine" "vm":
   8:   network_interface_ids           = var.nic_id
    |----------------
    | var.nic_id is tuple with 1 element

Inappropriate value for attribute "network_interface_ids": element 0: string
required.

How do I loop around the two NIC ids generated and pass them to the two VMs in the VM module? Thanks in advance!

Upvotes: 2

Views: 1442

Answers (1)

Tyler
Tyler

Reputation: 501

Use count.index to reference a specific value of your output in relation to the the number of VMs you are provisioning in your second module call.

  nic_id         = [module.NIC[count.index].nic_id]

Upvotes: 3

Related Questions