Specify namespace when creating kubernetes PV/PVC with Terraform

1/17/2020

I am trying to create PV/PVC on a kubernetes GKE cluster using Terraform

However the documentation does not mention how can one specify the namespace that these resources should be created in.

I have tried adding it both in the spec and the metadata section but I get an error message:

resource "kubernetes_persistent_volume" "jenkins-persistent-volume" {
  metadata {
    name = "${var.kubernetes_persistent_volume_metadata_name}"
    # tried placing it here -->> namespace = "${var.kubernetes_jenkins_namespace}"

  }
  spec {
    # tried placing it here -->> namespace = "${var.kubernetes_jenkins_namespace}"
    capacity = {
      storage = "${var.kubernetes_persistent_volume_spec_capacity_storage}"
    }
    storage_class_name = "standard"
    access_modes = ["ReadWriteMany"]
    persistent_volume_source {
      gce_persistent_disk {
        fs_type = "ext4"
        pd_name = "${google_compute_disk.jenkins-disk.name}"
      }
    }
  }
}

Error: module.jenkins.kubernetes_persistent_volume.jenkins-persistent-volume: spec.0: invalid or unknown key: namespace

Where such a configuration be placed?

-- pkaramol
kubernetes
terraform

1 Answer

1/17/2020

Persistent volumes are cluster-global objects and do not live in specific namespaces. ("It is a resource in the cluster just like a node is a cluster resource.") Correspondingly you can't include a namespace name anywhere on a kubernetes_persistent_volume resource.

If you're running in a cloud environment (and here your PV is creating a Google storage volume) its typical to only create a persistent volume claim, and let the cluster allocate the underlying volume for you. PVCs are namespace-scoped, and the Terraform kubernetes_persistent_volume_claim resource explicitly documents that you can include a namespace in the metadata block.

-- David Maze
Source: StackOverflow