DEV Community

Rafaf Tahsin
Rafaf Tahsin

Posted on

DRY your terraform code using dynamic block

Without dynamic block a security group resource looks like this

resource "aws_security_group" "instance_security_group" {
  ingress {
    # TLS (change to whatever ports you need)
    from_port   = 80
    to_port     = 80
    protocol    = "TCP"
    cidr_blocks = [ "0.0.0.0/0" ] # add a CIDR block here
  }

  ingress {
    # TLS (change to whatever ports you need)
    from_port   = 443
    to_port     = 443
    protocol    = "TCP"
    cidr_blocks = [ "0.0.0.0/0" ] # add a CIDR block here
  }

  ingress {
    # TLS (change to whatever ports you need)
    from_port   = 22
    to_port     = 22
    protocol    = "TCP"
    cidr_blocks = [ "${var.office_IP}/32" ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Above code can be dried with terraform dynamic block to look like this.

locals {
  ingress_rules = [
    { from_port = 80, to_port = 80, cidr_blocks = [ "0.0.0.0/0" ] },
    { from_port = 443, to_port = 443, cidr_blocks = [ "0.0.0.0/0" ] },
    { from_port = 22, to_port = 22, cidr_blocks = [ "${var.office_IP}/32" ] }
  ]
}

resource "aws_security_group" "instance_security_group" {
  dynamic "ingress" {
    for_each = local.ingress_rules
    iterator = i
    content {
      from_port   = i.value.from_port
      to_port     = i.value.to_port
      protocol    = "TCP"
      cidr_blocks = i.value.cidr_blocks
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

More about terraform dynamic block - https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks

Top comments (0)