Sample Terraform Code to Manage Temporary Access to GCP


TL; DR: This is a way to grant a temporary access to some GCP resources using Terraform’s time_static and google_project_iam_member resources.

resource "time_static" "iam_starts_at" {
  # rfc3339 = timestamp()
  # the current timestamp is the default value and will be saved in the state file
  # so the through time won't change if this is applied again
}

resource "google_project_iam_member" "temporary_iam" {
  project = var.project
  # a sample role can be "roles/container.viewer"
  role    = var.role
  # this should be the user's email address in the organization's domain
  # such as "[email protected]"
  member  = "user:${var.user}"

  condition {
    # the duration can be something like "24h" as a default
    title       = "expires_after_${var.duration}"
    description = "Expiring in ${var.duration} after ${time_static.iam_starts_at.rfc3339}"
    # adds the expression so this grant will be invalidated after 1 day
    # so it doesn't matter even if I forgot to revoke this grant
    # the through time is calculated using current time and the duration
    expression  = format("request.time < timestamp(\"%s\")", timeadd(time_static.iam_starts_at.rfc3339, var.duration))
  }
}

🙂