Cycle throughout an array

Hi,

I’m trying to create network security groups for each subnet in Azure. I’ve created variables that contain a list of nsg names. How do i tell the module to cycle through each value in the array to create each NSG, I don’t want to manually specify each nsg resource?

Or this not possible?

module "network-security-group" {
  source                = "Azure/network-security-group/azurerm"
  resource_group_name   = var.resource_group_name
  security_group_name   = var.nsg_names

}

Thanks

Use a ‘for loop’; you can find out how to do this in the Terraform documentation.

Thanks kpfleming, but i still ca’t get this to work.

module "network-security-group" {
  source                = "Azure/network-security-group/azurerm"
  resource_group_name   = var.resource_group_name
  security_group_name   = [
    for name in var.nsg_names:
    security_group_name]
}

Can you explain what i’m doing wrong here?

Thanks, i did search but didn’t come across the page. I think i understand now.

Thanks very much, and stay safe

Hey Kpleming.

Sorry to keep asking questions - i’ve searched but cant find the answer.
I have the NSGs creating based on the links you provided, but now i need to to assign each NSG to each subnet. I did this before by explicitly deploying each NSG and taking the output and passing the ID into the subnet creation. How to i get the output of the NSGS when being create via the array? Is this even possible?

Thanks

Yes, if you’ve created the NSGs using the for_each method, your resource block is now an array, and each resource accessible using an index (zero-based) into that array.

Man i finding this tough. Seems so much harder than ARM Templates, or maybe the documentation is hard to come by. But i cant find any examples of how to do this. Please would you mind showing how you pass the vaule of something created from an array to another resource.

Thanks

Sure, here’s an example of creating an array of resources (with the size of the array controlled by a variable), and then another array of resources which refer to them:

variable "web-node-count" {
  type    = number
  default = 2
}

resource "openstack_networking_port_v2" "web-port" {
  count = var.web-node-count

  name           = "grimoire-web-${count.index}"
  network_id     = data.openstack_networking_network_v2.dev.id
  admin_state_up = true
}

resource "openstack_compute_instance_v2" "web-node" {
  count = var.web-node-count

  name      = "grimoire-web-${count.index}"
  flavor_id = data.openstack_compute_flavor_v2.large.id
  key_pair  = openstack_compute_keypair_v2.grimoire.name
  scheduler_hints {
    group = openstack_compute_servergroup_v2.web-group.id
  }
  network {
    port = openstack_networking_port_v2.web-port[count.index].id
  }
}