尝试使用 Terraform 部署卡时出错

getting an error while trying deploy a crd using terrafom

我正在尝试使用 terraform 和下面的代码部署一个 crd

resource "kubectl_manifest" "crd-deploy" {
  for_each  = [ for crd in var.crdslist : crd ]
  yaml_body = (fileexists("${path.module}/crds/${crd}.yaml") ? file("${path.module}/crds/${crd}") : "")
}

但我仍然收到错误消息

 Error: Invalid reference
 
   on ../../00-modules/00-global/25-crd/10-crd.tf line 3, in resource "kubectl_manifest" "crd-deploy":
    3:   yaml_body = (fileexists("${path.module}/crds/${crd}.yaml") ? file("${path.module}/crds/${crd}") : "")
 
 A reference to a resource type must be followed by at least one attribute access, specifying the resource name.

input.tf 在 module_level

variable "crdslist" {
  type        = list(string)
  default     = []
}

input.tf 执行中_module_level

locals {
  crdslist            = ["crd-test"]
}

从哪里我运行 terraform 计划部署 K8s CRD

module "crds" {
  source   = "../../modules/global/25-crd"
  crdslist = local.crdslist
}

由于使用的变量是 list(string) 类型,这意味着它不能以其原始形式与 for_each 一起使用。 for_each meta-argument 要求变量的类型为 mapset [1]:

If a resource or module block includes a for_each argument whose value is a map or a set of strings, Terraform will create one instance for each member of that map or set.

为了使当前配置按预期工作,使用 Terraform built-in 函数 toset [2] 就足够了。唯一需要进行的更改是在模块内部:

resource "kubectl_manifest" "crd-deploy" {
  for_each  = toset(var.crdslist)
  yaml_body = (fileexists("${path.module}/crds/${each.vlaue}.yaml") ? file("${path.module}/crds/${each.vlaue}") : "")
}

请注意,当列表转换为集合时,键和值是相同的,即each.keyeach.value可以互换使用[3]。


[1] https://www.terraform.io/language/meta-arguments/for_each

[2] https://www.terraform.io/language/functions/toset

[3] https://www.terraform.io/language/meta-arguments/for_each#the-each-object