elhostis
elhostis

Reputation: 1087

With Terraform, how to create a google firewall from port to port

I have already created firewall (security groups) on AWS using the feature from_port/to_port. For exemple, here I create a SG from port 5000 to port 5100, from port 6000 to 6100, from port 7000 to 7100 ...

variable "list_port" {
    type = "list"
    default = [
    "5000-5100",
    "6000-6100",
    "7000-7100",
  ]
}

resource "aws_security_group" "test" {
  name     = "test"
}

resource "aws_security_group_rule" "test" {
  count             = "${length(var.list_port)}"
  type              = "ingress"
  from_port         = "${ element(split("-", element(var.list_port, count.index)), 0) }"
  to_port           = "${ element(split("-", element(var.list_port, count.index)), 1) }"
  protocol          = "TCP"
  cidr_blocks       = ["0.0.0.0/0"]
  security_group_id = "${aws_security_group.test.id}"
}

I'm trying to do the same thing with google, but it seems there is no from_to options. I want to be the more DRY possible and not repeat the ports. An other good reason is that I'm using terraform module with a variable containing ports to open. So I want to avoid something like that.

resource "google_compute_firewall" "firewall" {
  name          = "test"
  direction     = "INGRESS"
  allow {
    protocol = "tcp"
    ports    = [5000, 5100]
  }
  allow {
    protocol = "tcp"
    ports    = [6000, 6100]
  }
  allow {
    protocol = "tcp"
    ports    = [7000, 7100]
  }

} 

Does anyone known a better solution ?

Thanks

BR,

Eric

Upvotes: 0

Views: 1778

Answers (1)

Ewan
Ewan

Reputation: 15058

You can specify port ranges in the array:

resource "google_compute_firewall" "gaming-blacknut" {
    name          = "test"
    direction     = "INGRESS"
    allow {
        protocol = "tcp"
        ports    = ["5000-5100"]
   }
} 

Edit

After seeing your problem I believe you can still use port ranges in the allow rules, specifically the variable.

Example:

    allow {
        protocol = "tcp"
        ports    = ["${var.list_port}"]  // You may not need the surrounding [ ] as the variable is already defined as a list.
   }

You can see an example rule using a list of single ports and a port range in the documentation.

Upvotes: 1

Related Questions