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