I am trying to get ip addresses added to NSG using "for_each".
My code. Those are my VMs i am spinning
module "appserver" {
source = "../modules/appserver"
instances = {
TICEKET-FR13235 = {}
TICEKET-FR13421 = {}
TICEKET-FR13336 = {}
}
}
And here it is a NSG rule
resource "azurerm_network_security_rule" "appserver" {
name = "appserver_in_from_xt"
priority = "670"
direction = "Inbound"
access = "Allow"
protocol = "Tcp"
source_port_range = "*"
destination_port_range = "8679"
source_address_prefixes = ["IP.IP.IP.IP"]
dynamic "destination_address_prefixes" {
for_each = var.instances
content {
destination_address_prefixes = [azurerm_network_interface.appserver-nic[destination_address_prefixes.key].private_ip_address]
}
}
resource_group_name = var.resource_group
network_security_group_name = var.nsg
}
The problem I m having is here dynamic destination_address_prefixes. How can I get dynamic addresses in NSG?
You are getting this error because you have used the dynamic block incorrectly in the
azurerm_network_security_ruleresource. Dynamic blocks are for creating repeated nested blocks in Terraform. But thedestination_address_prefixis not a nested block. It is a field in thedestination_address_prefixeslist. That is why Terraform gives you an error.You can solve this problem by modifying how the NSG rule assigns dynamic IP addresses. Instead of using a dynamic block, you should specify the IP addresses in the
destination_address_prefixesattribute.My file structure:
My terraform configuration:
main.tfmodules/appserver/main.tfmodules/appserver/variable.tfOutput: