Define Security Group Rules as Object Variables

Create Terraform variables using list(object({...})) to define flexible security group ingress and egress rules with typed fields.

Networking

Detailed Explanation

Security Group Rules as Object Variables

Security group rules are a prime example of using complex object types in Terraform variables. Rather than hardcoding rules in resources, defining them as variables makes your modules reusable across projects.

Variable Definition

variable "ingress_rules" {
  type = list(object({
    description = string
    from_port   = number
    to_port     = number
    protocol    = string
    cidr_blocks = list(string)
  }))
  description = "List of ingress rules for the security group"
  default = [
    {
      description = "HTTPS from anywhere"
      from_port   = 443
      to_port     = 443
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    },
    {
      description = "HTTP from anywhere"
      from_port   = 80
      to_port     = 80
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  ]
}

Using in Resources

resource "aws_security_group" "web" {
  name        = "web-sg"
  description = "Web server security group"
  vpc_id      = aws_vpc.main.id

  dynamic "ingress" {
    for_each = var.ingress_rules
    content {
      description = ingress.value.description
      from_port   = ingress.value.from_port
      to_port     = ingress.value.to_port
      protocol    = ingress.value.protocol
      cidr_blocks = ingress.value.cidr_blocks
    }
  }
}

Object Type Benefits

  • Type safety: Terraform validates that each rule object has all required fields
  • Self-documenting: The type definition shows exactly what fields are expected
  • IDE support: Type-aware editors can autocomplete field names
  • Error prevention: Missing or mistyped fields are caught at plan time

Per-Environment Rules

# dev.tfvars — open access for development
ingress_rules = [
  { description = "All from VPC", from_port = 0, to_port = 0, protocol = "-1", cidr_blocks = ["10.0.0.0/16"] }
]

# prod.tfvars — restricted access
ingress_rules = [
  { description = "HTTPS only", from_port = 443, to_port = 443, protocol = "tcp", cidr_blocks = ["0.0.0.0/0"] }
]

Use Case

Reusable security group modules where different environments or applications need different firewall rules, from wide-open development to locked-down production.

Try It — Terraform Variable Generator

Open full tool