Search code examples
google-cloud-platformterraformcloudgoogle-compute-engine

Can you attach a firewall rule to a instance template


Lets say I have the following instance template:

resource "google_compute_instance_template" "label_studio_template" {
  name         = "label-studio-template"
  machine_type = "e2-micro"  # Free tier instance
  tags         = ["label-studio-server-template"]
  
  disk {
    auto_delete = false
    source_image = "debian-11-bullseye-v20230509"
  }

  network_interface {
    network = "default"
    access_config {
      // Public IP
      nat_ip = google_compute_address.standard.address
      network_tier = "STANDARD"
    }
  }
  metadata = {
    label_studio_username   = var.label_studio_username
    label_studio_password   = var.label_studio_password
    label_studio_user_token = var.label_studio_user_token
  }
  metadata_startup_script = file("${path.module}/compute_metadata.sh")
}

is it possible to use the tags here to attach firewall policies to all instances that are created from the template?


Solution

  • As per the documentation:

    Every firewall rule in Google Cloud must have a target which defines the instances to which it applies. The default target is all instances in the network, but you can specify instances as targets using either target tags or target service accounts.

    The target tag defines the Google Cloud VMs to which the rule applies. The rule is applied to a specific VPC network. It is made applicable to the primary internal IP address associated with the network interface of any instance attached to that VPC network that has a matching network tag.

    Both ingress and egress firewall rules have targets:

    Ingress rules apply to traffic entering your VPC network. For ingress rules, the targets are destination VMs in Google Cloud.

    Egress rules apply to traffic leaving your VPC network. For egress rules, the targets are source VMs in Google Cloud.

    Consider an ingress firewall rule that allows traffic on TCP port 80 from any source. The rule has a target tag of http-server. This rule would apply only to instances that have the http-server network tag, which means that incoming traffic on port 80 would be allowed to those instances.

    Here's a sample from the documentation:

    resource "google_compute_instance" "default" {
      project      = var.project_id # Replace this with your project ID in quotes
      zone         = "southamerica-east1-b"
      name         = "backend-instance"
      machine_type = "e2-medium"
      boot_disk {
        initialize_params {
          image = "debian-cloud/debian-9"
        }
      }
      network_interface {
        network = "default"
      }
      tags = ["health-check", "ssh"]
    }