Terraform Locals

Terraform Locals are named values which can be assigned and used in your code. It mainly serves the purpose of reducing duplication within the Terraform code.

Example in a security group:

locals {
    vpn = ["172.68.123.2/32"]
    cidr = ["198.12.22.182/32", var.vpc-cidr]
    all = ["0.0.0.0/0"]
}

locals {
  inbound-ports = [
    { port = 22, protocol = "tcp", cidr-blocks = local.vpn, description = "ssh access" },
    { port = 80, protocol = "tcp", cidr-blocks = local.all, description = "http access" },
    { port = 443, protocol = "tcp", cidr-blocks = local.all, description = "https access" },
    { port = 514, protocol = "udp", cidr-blocks = local.all, description = "syslog access" },
    { port = 3100, protocol = "udp", cidr-blocks = local.cidr, description = "loki access" },
    { port = "-1", protocol = "icmp", cidr-blocks = local.all, description = "ping" }
  ]
  outbound-ports = [
    { port = 0, protocol = "-1", cidr-blocks = local.all, description = "outbound internet access" }
  ]
}

locals.tf

resource "aws_security_group" "resource-sgroup" {
  name = "sgroup-${var.name}-${terraform.workspace}"
  description = "Created with Terraform, used for ${var.name} on environment ${terraform.workspace}"
  vpc_id = var.vpc-id
  
  dynamic "ingress" {
    for_each = local.inbound-ports
    content {
      from_port = ingress.value.port
      to_port = ingress.value.port
      protocol = ingress.value.protocol
      cidr_blocks = ingress.value.cidr-blocks
      description = ingress.value.description
    }
  }
  dynamic "egress" {
    for_each = local.outbound-ports
    content {
      from_port = egress.value.port
      to_port = egress.value.port
      protocol = egress.value.protocol
      cidr_blocks = egress.value.cidr-blocks
      description = egress.value.description
    }
  }

  tags = {
      Name = "sgroup-${var.name}-${terraform.workspace}"
  }
}

sgroup.tf