I'm trying to have this Terraform configured so that all someone needs to do to add a new SG ingress rule is to add a block to the .tfvars file, and the new ingress rule will be added to the single SG.
I have a .tfvars file that looks like this:
rules = [
{
protocol = "tcp"
port = 22
cidr = ["10.0.0.0/8"],
},
{
protocol = "tcp"
port = 80
cidr = ["10.0.0.0/8"]
},
{
protocol = "tcp"
port = 443
cidr = ["10.0.0.0/8"]
},
{
protocol = "icmp"
port = -1
cidr = ["10.0.0.0/8"]
}
]
And my Terraform is:
variable "rules" {
type = list(object({
protocol = string
port = number
cidr = list(string)
}))
description = "Specify the protocol, port range, and CIDRs."
}
resource "aws_security_group" "this" {
...
dynamic "ingress" {
for_each = { for rule in var.rules : rule.id => rule }
content {
from_port = var.rules.port
to_port = var.rules.port
protocol = var.rules.protocol
cidr_blocks = var.rules.cidr
}
}
...
I've tried to loop through the above, and also with using for_each = var.rules but I just get the following error (occurs for each of the below):
protocol = var.rules.protocol
from_port = var.rules.port
to_port = var.rules.port
cidr_blocks = var.rules.cidr
-----------------------------
var.rules is list of object with 4 elements.
This value does not have any attributes.`
I'm a bit stuck and not sure what else to try, so does anyone have any ideas?