I am new to terraform and trying to create an AWS security group with ingress and egress rules. Rather than hardcoding the values and creating multiple ingress and egress blocks, I am trying to make use of terraform lookup function.
main.tf file looks like this:
provider "aws" {
version = "~> 2.0"
region = var.region
profile = var.profile
}
resource "aws_security_group" "this" {
name = "test-sg"
description = "test security group"
dynamic "ingress" {
for_each = var.ingress_rules
content {
description = lookup(ingress.value, "description", null)
from_port = lookup(ingress.value, "from_port", null)
to_port = lookup(ingress.value, "to_port", null)
protocol = lookup(ingress.value, "protocol", null)
cidr_blocks = lookup(ingress.value, "cidr_blocks", null)
}
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "test-sg"
}
}
variables.tf file looks like this
variable "ingress_rules" {
default = {
"description" = ["For HTTP", "For SSH"]
"from_port" = ["80", "22"]
"to_port" = ["80", "22"]
"protocol" = ["tcp", "tcp"]
"cidr_blocks" = ["0.0.0.0/0", "0.0.0.0/0"]
}
type = map(list(string))
description = "Security group rules"
}
When I run terraform validate it shows configuration is valid, but when I run terraform plan, it shows the following error:
ingress.value is list of string with 2 elements
Invalid value for "inputMap" parameter: lookup() requires a map as the first
argument.
After spending a long time still, I am not able to figure out how to solve this error. What is the correct way to pass lookup values to variables.tf file.