Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I expose extra ports on my Google Compute Instance using Terraform?

I have a Google Compute Instance defined by some Terraform code.

provider "google" {
  credentials = "${file("auth.json")}"
  project     = "aqueous-depth-189023"
  region      = "europe-west2"
}

resource "google_project" "website" {
  name = "Website"
  project_id = "aqueous-depth-189023"
}

resource "google_compute_instance" "default" {
  name         = "website"
  machine_type = "n1-standard-1"
  zone         = "europe-west1-b"

  network_interface {
    network = "default"

    access_config {
      // Ephemeral IP
    }
  }

  metadata {
    sshKeys = "james:${file("website.pem.pub")}"
  }

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-8"
    }
  }
}

By default, Google only exposes port 22 and a few others for Google Compute Instances. Can I update my Terraform code so as to achieve exposing port 80 and some other ports, without having to resort to using the web console? What Terraform resource would I need to add or edit?

like image 602
James Hiew Avatar asked Dec 23 '22 07:12

James Hiew


1 Answers

Use google_compute_firewall. You'll need to tag your instance with the instance resource and set target_tags on the firewall resource. You can refer to how these tags work here.

Example

Add a tag to the instance

resource "google_compute_instance" "default" {
  name         = "website"
  machine_type = "n1-standard-1"
  zone         = "europe-west1-b"

  tags = ["web"]

  network_interface {
    network = "default"

    access_config {
      // Ephemeral IP
    }
  }

  metadata {
    sshKeys = "james:${file("website.pem.pub")}"
  }

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-8"
    }
  }
}

Add a firewall resource

resource "google_compute_firewall" "default" {
 name    = "web-firewall"
 network = "default"

 allow {
   protocol = "icmp"
 }

 allow {
   protocol = "tcp"
   ports    = ["80"]
 }

 source_ranges = ["0.0.0.0/0"]
 target_tags = ["web"]
}

You'll also want to define source_tags or source_ranges, the example above uses a source range of 0.0.0.0/0 which is 'anything'. This may not be appropriate for all rules.

like image 132
Brandon Miller Avatar answered Jan 13 '23 14:01

Brandon Miller