gcp,

Easy login to GCP VM instances using IAP

Mar 24, 2023 · 2 mins read · Post a comment

IAP or Identity-Aware Proxy, is a GCP service that allows for secure and fine-grained control access mostly to cloud resources such as VMs and Kubernetes clusters. Here I’m going to show you how to configure one, using Terraform of course.

Prerequisites

  • GCP (privileged) account
  • Terraform
  • VM deployed

Solution

Basically, you need three things: a VM, IAM role configured and a firewall rule. I’ll skip the VM deployment, since it shouldn’t be a problem to deploy one.

IAM role assignment

Assuming that you have your VM instances deployed, the only thing you got to do is assign the roles/iap.tunnelResourceAccessor IAM role to certain member(s) in certain projects. For instance:

resource "google_project_iam_binding" "vm_ssh_iap" {
  project = "devcoops-vm"
  role    = "roles/iap.tunnelResourceAccessor"

  members = [
    "user:[email protected]"
  ]
}

Note(s): You can even use google_project_iam_member instead of google_project_iam_binding, but there is a catch. The former one is non-authoritative, and the latter one is authoritative. To sum up, google_project_iam_member manages membership for IAM policies, while google_project_iam_binding controls the roles and permissions that members have. google_project_iam_member alone is not enough to fully control access to a GCP project, and must be used with google_project_iam_binding to create a complete IAM policy. google_project_iam_binding is authoritative because it fully defines the IAM policy. So, use google_project_iam_binding whenever possible.

Firewall rule

Next you need to add a firewall rule that will allow port number 22 from IP address: 35.235.240.0/20. Confirm the port and IP address from the official GCP docs though. Example code block:

resource "google_compute_firewall" "this" {
  name        = "ssh_iap"
  project     = "devcoops"
  network     = "devcoops_main"
  description = "Allow IAM TCP forwarding"
  direction   = "INGRESS"

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

  source_ranges = ["35.235.240.0/20"]
  target_tags   = ["vms"]
}

Once that being deployed, feel free to click on the SSH button placed on the right side of the VM instance name.

Conclusion

Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.