terraform-provider-kubectl: for_each on kubectl_path_documents errors with The "for_each" value depends on resource attributes that cannot be determined until apply

Hi, I am trying to use the provider but terraform errors:

 Error: Invalid for_each argument
│
│   on ..\..\..\..\modules\kube\kyverno.tf line 26, in resource "kubectl_manifest" "kyverno_policies":
│   26:   for_each   = toset(data.kubectl_path_documents.kyverno_policy_manifests.documents)
│     ├────────────────
│     │ data.kubectl_path_documents.kyverno_policy_manifests.documents is a list of string, known only after apply
│
│ The "for_each" value depends on resource attributes that cannot be determined until apply, so Terraform cannot predict how many instances will be created. To work around this, use the -target argument to  
│ first apply only the resources that the for_each depends on.

I followed the exmple from the docs:

data "kubectl_path_documents" "kyverno_policy_manifests" {
  pattern = "${path.module}/manifests/kyverno/*.yaml"
}

resource "kubectl_manifest" "kyverno_policies" {
  depends_on = [helm_release.kyverno]
  for_each   = toset(data.kubectl_path_documents.kyverno_policy_manifests.documents)
  yaml_body  = each.value
}

Its strange because I have this in a module and it only fails in 1 out of 2 places where the module is used.

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 24
  • Comments: 19

Most upvoted comments

I managed to get this working by looping over fileset instead:

data "kubectl_path_documents" "kyverno_policy_manifests" {
  pattern = "${path.module}/manifests/kyverno/*.yaml"
}

resource "kubectl_manifest" "kyverno_policies" {
  depends_on = [helm_release.kyverno]
  for_each   = length(fileset("${path.module}/manifests/kyverno", "*.yaml"))
  yaml_body  = element(data.kubectl_path_documents.kyverno_policy_manifests.documents, count.index)
}

Official kubernetes provider already supports creating an any manifest - https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/resources/manifest

On my side, I got this issue with a depends_on in my data “kubectl_file_documents” … I removed it and it works like a charm …

In my terraform project, I ve 2 different files with these documents/manifest…

Given the lack of a comment from the maintainer, despite the high amount of users facing the problem. I think it’s safe to say that this provider is not maintained anymore.

https://registry.terraform.io/providers/gavinbunney/kubectl/latest/docs/data-sources/kubectl_path_documents#load-all-manifest-documents-via-for_each-recommended The doc is wrong and should be fixed to

resource "kubectl_manifest" "test" {
    for_each  = data.kubectl_path_documents.docs.manifests
    yaml_body = each.value
}