Terraform Version: 1.4.6
I have a variable for AWS Security Group rules defined thus:
type = list(object({
rule_type = string
description = string
from_port = string
to_port = string
protocol = string
cidr_blocks = optional(list(string))
ipv6_cidr_blocks = optional(list(string))
source_security_group_id = optional(string)
}))
If this variable is empty, I want to construct a default value that has the port set to the value of another variable. I attempted to do this with locals in the following manner:
locals {
default_sg_rules = [
{
rule_type = "ingress"
description = "Allow listening port from instances"
from_port = var.port
to_port = var.port
protocol = "tcp"
},
{
rule_type = "egress"
description = "Allow all out"
from_port = 0
to_port = 0
protocol = "-1"
}
]
sg_rules = var.sg_rules == null ? local.default_sg_rules : var.sg_rules
}
However, when I do this, I get the following error:
The true and false result expressions must have consistent types. The 'true' value is tuple, but the 'false' value is list of object.
I have tried using tolist
to cast the variable as a list, but then get an error stating the false value has cidr_blocks
, ipv6_cidr_blocks
, and source_security_group_id
defined and the true value doesn’t. Even though the value is either null or an empty list and those attributes are optional.
I got around it by defining another variable and doing some hacky ternaries to test for a specific string in the to_port
and from_port
but would like to make it work more elegantly.
Any thoughts?