kick07
kick07

Reputation: 664

Terraform expression

I'm working on this azure_rm nsg (network security group) terraform module and i'm try to make it as much as variable driven and generic. everything is working as expected but one flag is erroring out.

Main.tf file

`resource "azurerm_network_security_rule" "Inbound" {
  count                      = length(var.inbound_port_ranges)
  name                       = "sg-rule-${count.index}"
  direction                  = "Inbound"
  access                     = "Allow"
  priority                   = element(var.priority, count.index) 
  source_address_prefix      = "*"
  source_port_range          = "*"
  destination_address_prefix = "*"
  destination_port_range     = element(var.inbound_port_ranges, count.index) 
  protocol                   = "TCP"
  resource_group_name         = azurerm_network_security_group.this.resource_group_name
  network_security_group_name = azurerm_network_security_group.this.name
}

`

Variables.tf file:

`variable "resource_group_name" {
  default = "test"
}
variable "priority" {
  default = ["100", "101"]
}
variable "inbound_port_ranges" {
  default = ["8000", "8001"]
}
variable "outbound_port_ranges" {
  default = ["9000", "9001"]
}
`

I was able to read the list into variables for 'destination_port_range' but not for priority variable and it kept erroring out with below error and i'm not sure why ?

`Error: Incorrect attribute value type

  on main.tf line 20, in resource "azurerm_network_security_rule" "Inbound":
  20:   priority                   = "element(var.priority, ${count.index})"
    |----------------
    | count.index is 1

Inappropriate value for attribute "priority": a number is required.
`

It would be a great help and highly appreciated if anyone can point me in the right direction to solve it. All i want is to read values from list with index so that I can use same inbound rule to create multiple rules.

Thanks in advance.

Upvotes: 1

Views: 179

Answers (1)

Marcin
Marcin

Reputation: 238071

Your priority is a list of strings. Also, it will be literally string "element(var.priority, <number>)" rather then actual number.

It should be a list of numbers:

variable "priority" {
  default = [100, 101]
}

and then:

priority                   = element(var.priority, count.index)

You will have same issue with destination_port_range from what I can tell.

Upvotes: 1

Related Questions