How to split values of a map in terraform to create lists?

Viewed 8706

I have a map variable with many values (NACL rules). I am trying to add rules accordingly

variable "rules" {
  default = {
    a = "200,false,tcp,allow,0.0.0.0/0,23,23"
    b = "100,true,tcp,allow,0.0.0.0/0,1024,65535"
  }
}


resource "aws_network_acl_rule" "bar" {
  network_acl_id = "<id>"
  rule_number    = "${split(",",element(values(var.rules),count.index))[0]}"
  egress         = "${split(",",element(values(var.rules),count.index))[1]}"
  protocol       = "${split(",",element(values(var.rules),count.index))[2]}"
  rule_action    = "${split(",",element(values(var.rules),count.index))[3]}"
  cidr_block     = "${split(",",element(values(var.rules),count.index))[4]}"
  from_port      = "${split(",",element(values(var.rules),count.index))[5]}"
  to_port        = "${split(",",element(values(var.rules),count.index))[6]}"
  count          = "${length(values(var.rules))}"
}

Error: expected "}" but found "["

Since maps with lists as values aren't supported, I am trying to split the values and iterate

2 Answers

Another option, easier to read, is with lookup():

variable "rules" {
  default = [
    {
      rule_number = 200
      egress = false
      protocol = "tcp"
      rule_action = "allow"
      cidr_block = "0.0.0.0/0"
      from_port= 23
      to_port = 23
    },
    {
      rule_number = 100
      egress = true
      procotol = "tcp"
      rule_action = "allow"
      cidr_block = "0.0.0.0/0"
      from_port = 1024
      to_port = 65535
    },
  ]
}

resource "aws_network_acl_rule" "bar" {
  count          = "${length(var.rules)}"
  network_acl_id = "<id>"
  rule_number    = "${lookup(var.rules[count.index], "rule_number")}"
  egress         = "${lookup(var.rules[count.index], "egress")}"
  protocol       = "${lookup(var.rules[count.index], "protocol")}"
  rule_action    = "${lookup(var.rules[count.index], "rule_action")}"
  cidr_block     = "${lookup(var.rules[count.index], "cidr_block")}"
  from_port      = "${lookup(var.rules[count.index], "from_port")}"
  to_port        = "${lookup(var.rules[count.index], "to_port")}"
}
Related