how to add existing subnetwork for gke cluster using terraform

2/23/2019

I am adding vpc, subnet and gke cluster referring to that vpc and subnet. However, vpc and subnet are getting created but while creating gke cluster it is throwing error that

Create cluster cannot be created with existing subnetwork.

I have added the below script which is creating VPC, subnetwork and gke cluster. Please see the terraform script below

provider "google" {
  credentials = "gkecredential"
  project     = "abc"
  region      = "us-central1"
}

resource "google_compute_network" "vpc" {
  name                    = "test"
  auto_create_subnetworks = "false"
}

resource "google_compute_subnetwork" "gkesubnet" {
  name          = "testgkesubnet"
  ip_cidr_range = "10.105.0.0/24"
  network       = "${google_compute_network.vpc.self_link}"
  region        = "us-central1"

  secondary_ip_range {
    range_name    = "container-range-1"
    ip_cidr_range = "10.75.0.0/20"
  }

  secondary_ip_range {
    range_name    = "service-range-1"
    ip_cidr_range = "10.8.0.0/14"
  }
}

resource "google_container_cluster" "gcp_kubernetes" {
  name               = "gkecluster"
  zone               = "us-west1-a"
  initial_node_count = "1"
  network            = "${google_compute_network.vpc.self_link}"
  subnetwork         = "${google_compute_network.gkesubnet.self_link}"

  additional_zones = [
    "us-west1-b",
    "us-west1-c",
  ]

  private_cluster_config {
    enable_private_endpoint = false
    enable_private_nodes    = true
    master_ipv4_cidr_block  = "172.16.0.0/28"
  }

  master_auth {
    username = "abc"
    password = "abc"
  }

  master_authorized_networks_config {
    cidr_blocks = [
      {
        cidr_block   = "10.102.0.0/24"
        display_name = "Office"
      },
    ]
  }

  ip_allocation_policy {
    create_subnetwork = true
  }

  node_config {
    oauth_scopes = [
      "https://www.googleapis.com/auth/compute",
      "https://www.googleapis.com/auth/devstorage.read_only",
      "https://www.googleapis.com/auth/logging.write",
      "https://www.googleapis.com/auth/monitoring",
    ]

    labels {
      this-is-for = "dev-cluster"
    }

    tags = ["dev", "work"]
  }
}
-- Sarabjeet Singh
google-cloud-platform
google-kubernetes-engine
terraform
terraform-provider-gcp

0 Answers