Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

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 VMmain.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!

question from:https://stackoverflow.com/questions/65600886/terraform-v0-13-using-count-in-modules

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...