# Create a subnet, vpc access connector, router and nat to allow a cloud run instance # to be assigned a static ip. # The VPC connector is assigned to the cloud run's annotations. # This follows the steps detailed here: https://cloud.google.com/run/docs/configuring/static-outbound-ip resource "google_compute_subnetwork" "isolated-subnet" { count = var.enable_static_egress_ip ? 1 : 0 name = "${var.name}-isolated-subnet-for-static-ip" ip_cidr_range = var.static_egress_ip_cidr_range network = "default" region = var.cloud_run_region } resource "google_vpc_access_connector" "static-ip-connector" { count = var.enable_static_egress_ip ? 1 : 0 name = "${var.name}-connector" subnet { name = google_compute_subnetwork.isolated-subnet[0].name } region = var.cloud_run_region provider = google-beta } resource "google_compute_router" "static-ip-router" { count = var.enable_static_egress_ip ? 1 : 0 name = "${var.name}-ip-router" network = "default" region = var.cloud_run_region } resource "google_compute_address" "static-ip" { count = var.enable_static_egress_ip ? 1 : 0 name = "${var.name}-static-ip" region = var.cloud_run_region # We do not expect that static IPs should be regularly removed and recreated, # as it's likely that they will be used within firewall configuration outside # of our GCP deployment. So we make them difficult to destroy, guarding against # an accidentally removal. lifecycle { prevent_destroy = true } } resource "google_compute_router_nat" "static-ip-nat" { count = var.enable_static_egress_ip ? 1 : 0 name = "${var.name}-static-ip-nat" router = google_compute_router.static-ip-router[0].name nat_ips = [google_compute_address.static-ip[0].self_link] nat_ip_allocate_option = "MANUAL_ONLY" region = var.cloud_run_region min_ports_per_vm = var.min_ports_per_vm source_subnetwork_ip_ranges_to_nat = "LIST_OF_SUBNETWORKS" subnetwork { name = google_compute_subnetwork.isolated-subnet[0].id source_ip_ranges_to_nat = ["ALL_IP_RANGES"] } }