0

I'm trying create a resource in terraform that will create a number of subnets based on a list variable.

I'm having trouble with references to existing resources. For example in the following code network_security_group_id is hardcoded to azurerm_network_security_group.k8s.id:

variable "resources_large" {
    description = "List of Large Networks" 
    default = [
      "k8s",
      "storm"
    ]
}

resource "azurerm_subnet" "large" {
  name                      = "ue-${var.environment}-${var.resources_large[count.index]}-subnet-${replace("${cidrsubnet("${local.subnet_ranges["large"]}", "${var.newbit_size["large"] }", count.index )}", "/[./]/", "-"  ) }"
  resource_group_name       = "ue-${var.environment}-${var.resources_large[count.index]}-rg"
  virtual_network_name      = "${azurerm_virtual_network.dev.name}"
  address_prefix            = "${cidrsubnet("${local.subnet_ranges["large"]}", "${var.newbit_size["large"] }", count.index )}"
  network_security_group_id = "${azurerm_network_security_group.k8s.id}"

  count  = "${length(var.resources_large)}"

  depends_on = ["azurerm_virtual_network.dev"]
}

This needs to reference existing security groups based on the name in the resources_large list. What I'd like to have is something which looks likes this:

network_security_group_id = "${azurerm_network_security_group.${var.resources_large[count.index]}.id}"

Which doesn't work, I'm guessing due to the lack of variable interpolation support.

Is there any way to reference other resources based on variable?

1 Answer 1

1

Maybe something like this

locals {
  sgs = {
    k8s = "${azurerm_network_security_group.k8s.id}"
    storm = "${azurerm_network_security_group.storm.id}"
  }
}

...

network_security_group_id = "${lookup( locals.sgs, var.resources_large[count.index])}"

may work.

If you create the SG using the same counter, it can be just

network_security_group_id = "${element(azurerm_network_security_group.*.id, count.index)}"

HTH

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

3 Comments

Except they didn't create their network security group in a loop by the looks of it so that won't work.
Just to point out, we actually will be creating the security groups in a loop, just haven't gotten to that part yet. I will test out the above.
I edited again to save the initial answer, in case someone needs it

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.