0

My code is as follow,

nsg.tf:

locals {
  nsg_names = ["pri_nsg_1_subnet","pri_nsg_2_subnet"]
}

resource "azurerm_network_security_group" "nsg_creation" {
  count = length(local.nsg_names)
  name                = local.nsg_names[count.index]
  location            = var.location
  resource_group_name = var.resource_group_name

  dynamic "security_rule" {
    for_each = var.nsg_list == [] ? [] : var.nsg_list
      content {
          name                        = security_rule.value[0]
          priority                    = security_rule.value[1]
          direction                   = security_rule.value[2]
          access                      = security_rule.value[3]
          protocol                    = security_rule.value[4]
          source_port_range           = security_rule.value[5]
          destination_port_range      = security_rule.value[6]
          source_address_prefix       = security_rule.value[7]
          destination_address_prefix  = security_rule.value[8]
      }
  }
}

nsg.tfvars:

# nsg_list = [["rule1", "100", "Inbound", "Allow", "*","*", "3389", "*", "*"],
#             ["rule2", "110", "Inbound", "Allow", "*","*", "3389", "*", "*"],
#             ["rule3", "120", "Outbound", "Allow", "*","*", "3389", "*", "*"]]
nsg_list = []

So basically I created 3 rules for the two new NSG pri_nsg_1_subnet and pri_nsg_2_subnet. It work fine during creation... However, when i try to comment out the 3 rules, then use nsg_list = [] instead. By right i would like to have it such that it can somehow define as empty slice -> [] in order to remove all the rules. The rules removal is fine if i reduce from 3 rules to 1 rules, the terraform apply still work perfectly. but it is unable to remove ALL of the rules when i try to define it as [] Base on the hashicorp registry below, it says that we would have to define the security_rule = [] in order to remove it. However, it seems not feasible because if I were to create a NSG with multiple rule, the only logical way to do it is via the dynamic block... https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/network_security_group

How can I be able to remove all the rules if i am using dynamic block in the code above. Actually I'm trying to create a module that is able to create let's say 100NSG at one time with the same rules (yes i know if it's same rules, might as well they use same NSG or some other methods. but i just want to know if dynamic block is do-able)

eggbud
  • 1
  • 1
    I'd probably go with something like `for_each = length(var.nsg_list) > 0 ? var.nsg_list : []`. – Marko E Aug 11 '22 at 14:35
  • I tried the above before as well. But it is unable to remove/satisfy the criteria of setting an empty slice [] for security_rule as stated in the hashicorp registry, in order to remove all the security rules set – eggbud Aug 12 '22 at 00:35

0 Answers0