0

I'm trying to deploy two subnets with different ip prefixes and different names and not create too much repeated code. I'm not sure how to approach it best. I tried the below but its not working. My terraform version is 0.14.11 so I think some of what I am doing below might be outdated

My main.tf in root module

module "deploy_subnet" {
source              = "./modules/azure_subnet"
subscription_id     = var.subscription_id
resource_group_name = var.resource_group_name
region              = var.region
vnet_name           = var.vnet_name
count_subnets       = "${length(var.subnet_prefix)}"
subnet_name         = "${lookup(element(var.subnet_prefix, count.index), "name")}"
address_prefix      = "${lookup(element(var.subnet_prefix, count.index), "ip")}"
}

My variables.tf in root module (only pasting relevant part)

variable "subnet_prefix" {
type = "list"
default = [
  {
    ip      = "10.0.1.0/24"
    name     = "aks-sn"
  },
  {
    ip      = "10.0.2.0/24"
    name     = "postgres-sn"
  }
]

}

My main.tf in my child module folder

resource "azurerm_subnet" "obc_subnet" {
name = var.subnet_name
count = var.count_subnet
resource_group_name   = var.resource_group_name
virtual_network_name  = var.vnet_name
address_prefixes      = var.address_prefix

}

My variables.tf in my child module folder (only relevant part)

variable "subnet_name" {
  description = "Subnet Name"
}
variable "count_subnet" {
  description = "count"
}
variable "address_prefix" {
  description = "IP Address prefix"
}

I get the error below

Reference to "count" in non-counted context
on main.tf line 8, in module "deploy_subnet":
 8:   subnet_name         = "${lookup(element(var.subnet_prefix, count.index),"name")}"
 The "count" object can only be used in "module", "resource", and "data"
 blocks, and only when the "count" argument is set

Reference to "count" in non-counted context
on main.tf line 9, in module "deploy_subnet":
9:   address_prefix      = "${lookup(element(var.subnet_prefix, count.index), "ip")}"
The "count" object can only be used in "module", "resource", and "data"
blocks, and only when the "count" argument is set.

1 Answer 1

1

It is exactly what it says. In the root module you try to reference a count.index but there is nothing being counted. All you do is pass a variable to the child module.

You should just pass subnet prefix to the child module, and in the child module set the count to the length of it, and reference count.index for the values of address_prefix and name

Alternatively, and probably more elegant you might look into for_each and each.value

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.